【问题标题】:fill google maps autocomplete with prediction results用预测结果填充谷歌地图自动完成
【发布时间】:2015-01-01 10:43:42
【问题描述】:

我目前拥有的是一个地方自动完成功能,它显示一个国家/地区的结果。 我想做的是让它显示更多国家/地区的结果(限制为 2 或 3 个)。

据我了解,当前版本的自动完成功能无法做到这一点(https://code.google.com/p/gmaps-api-issues/issues/detail?id=4233) 所以我要做的是获取两个预测列表并显示它们而不是自动完成结果。

有什么方法可以触发自动完成的下拉部分并用预测列表填充它?

输入的onChange中的触发代码:

var inputData  = this.value;
var options = {
        componentRestrictions: { country: "be" }
};
service = new google.maps.places.AutocompleteService();
var request = {
    input: inputData,
    componentRestrictions: {country: 'be'},
};
var secondaryRequest = {
    input: inputData,
    componentRestrictions: {country: 'lu'},
};
service.getPlacePredictions(request, callback);
service.getPlacePredictions(secondaryRequest, callback);

回调函数:

function callback(predictions, status) {
  if (status != google.maps.places.PlacesServiceStatus.OK) {
    alert(status);
    return;
  }  
    //here I need to display that dropdown if it isn't already
    // and then add the results of the current predictions.
}

更新

2017 年 1 月,Maps JavaScript API 3.27 版中引入了多个国家/地区过滤器自动完成功能:

您现在可以将自动完成预测限制为仅来自多个国家/地区的显示。您可以通过在 AutocompleteOptions 的 componentRestrictions 字段中指定最多 5 个国家/地区来做到这一点。

来源:https://developers.google.com/maps/documentation/javascript/releases#327

【问题讨论】:

  • 所以我使用上面的代码和一个自定义的“弹出”div 来显示结果。如果有人有更好的主意,我会将这个问题留几天。之后我会发布我的解决方案(因为它需要一些清理)。

标签: google-maps autocomplete


【解决方案1】:

这是我的演示解决方案。如评论中所述。它使用几个调用来获取预测并用它们建立结果列表。选择结果后,地址将被地理编码。 这意味着使用自动完成功能需要 3 次调用而不是 1 次调用,但到目前为止我还没有找到解决方法。

<!DOCTYPE html>
    <html>
    <head>
    <title>Retrieving Autocomplete Predictions</title>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places&v=3.exp"></script>
    <script>

    function initialize() {  
       $("#place").live("keyup", function (evt) {           
            // Clear any previously set timer before setting a new one
            window.clearTimeout($(this).data("timeout"));
            $(this).data("timeout", setTimeout(function () {
                //whe the timeout has expired get the predictions
                var inputData = $("#place").val();          
                service = new google.maps.places.AutocompleteService();
                var request = {
                    input: inputData,
                    componentRestrictions: {country: 'be'},
                };
                var secondaryRequest = {
                    input: inputData,
                    componentRestrictions: {country: 'lu'},
                };
                $('#resultWindow').empty();
                service.getPlacePredictions(request, callback);
                service.getPlacePredictions(secondaryRequest, callback);            
            }, 1000));
        });

        function callback(predictions, status) {
            if (status != google.maps.places.PlacesServiceStatus.OK) {
                console.log(status);
                return;
            }    
            var resultHTML = '';
            for (var i = 0, prediction; prediction = predictions[i]; i++) {
                resultHTML += '<div>' + prediction.description + '</div>';
            }
            if($('#resultWindow').html() != undefined && $('#resultWindow').html() != ''){      
                resultHTML = $('#resultWindow').html()+ resultHTML;
            }       
            if(resultHTML != undefined && resultHTML != ''){        
                $('#resultWindow').html(resultHTML).show();
            }
            //add the "powered by google" image at the bottom -> required!!
            if($('#resultWindow').html() != undefined){
                $('#resultWindow #googleImage').remove();
                var imageHtml = $('#resultWindow').html() + '<img id="googleImage" src="powered-by-google-on-white2.png"/>';
                $('#resultWindow').html(imageHtml);
            }
        }

        function geocodeAddress(address) {      
            var geocoder = new google.maps.Geocoder();      
            geocoder.geocode({'address': address}, function (results, status) 
            {   
              if (status == google.maps.GeocoderStatus.OK) 
              {
                $('#latitude').val(results[0].geometry.location.lat());
                $('#longitude').val(results[0].geometry.location.lng());        
              }
              else {
                console.log("Error: " + google.maps.GeocoderStatus);
              }
            });
        }
        $('#resultWindow div').live('click',function(){
            //get the coördinates for the selected (clicked) address
            $('#resultWindow').hide();
            var address = $(this).text();
            var addressParts = address.split(',');
            $('#country').val(addressParts[2]);
            $('#city').val(addressParts[1]);
            $('#place').val(addressParts[0]);
            if(address != ''){
                geocodeAddress(address);
            }
        });
      /*end custom autocomplete stuff*/
    }
    google.maps.event.addDomListener(window, 'load', initialize);

    </script>
    <style type="text/css">
    #resultWindow{  
        position: fixed;
       /* top: 0;
        left: 0;
        width: 100%;
        height: 100%;*/
        background-color: #fff;
        filter:alpha(opacity=50);
        -moz-opacity:0.5;
        -khtml-opacity: 0.5;
        opacity: 0.5;
        z-index: 10000;
        border: 1px solid black;
        color:black;
        display:none;
    }
    </style>
    </head>
<body>
<div id="placeholder">  
    <input type="text" id="place" style="width:200px;"/>
    <label for="latitude">Latitude</label>
    <input type="text" id="latitude"/>
    <label for="longitude">Longitude</label>
    <input type="text" id="longitude"/>
    <label for="city">city</label>
    <input type="text" id="city"/>
    <label for="country">selected country</label>
    <input type="text" id="country"/>
    <div id="resultWindow"></div>   
</div>
</body>
</html>

【讨论】:

    猜你喜欢
    • 2015-03-22
    • 1970-01-01
    • 2016-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多