Google maps API V3 - 无法对AutocompleteService预测进行地理编码

时间:2013-01-19 12:38:58

标签: javascript google-maps google-maps-api-3 google-geocoder

我正在使用google.maps.places.AutocompleteService获取地点搜索的建议,但我无法对某些预测进行地理编码。

这方面的一个例子:当我搜索'风暴河口'时,我得到的一个预测是'南非风暴河口休息营' ,但是这个地址不能进行地理编码以获得lattude /经度,例如:http://maps.googleapis.com/maps/api/geocode/json?address=Storms%20River%20Mouth%20Rest%20Camp,%20South%20Africa&sensor=true

有没有办法获得自动完成预测的纬度/经度值?

或者,我不明白为什么谷歌自动完成会返回我无法进行地理编码的预测。

以下是我正在使用的逻辑和代码的基本示例:

var geocoder = new google.maps.Geocoder();
var service = new google.maps.places.AutocompleteService(null, {
  types: ['geocode'] 
});

service.getQueryPredictions({ input: query }, function(predictions, status) {
  // Show the predictions in the UI
  showInAutoComplete(predictions);
};

// When the user selects an address from the autcomplete list
function onSelectAddress(address) {
  geocoder.geocode({ address: address }, function(results, status) {
   if (status !== google.maps.GeocoderStatus.OK) {
      // This shouldn't never happen, but it does
      window.alert('Location was not found.');
    }
    // Now I can get the location of the address from the results
    // eg: results[0].geometry.location
  });
}

[edit] - 在此处查看工作示例:http://demos.badsyntax.co/places-search-bootstrap/example.html

6 个答案:

答案 0 :(得分:10)

使用getPlacePredictions()代替getQueryPredictions()。这将返回该地点的reference,您可以使用placesService.getDetails()来检索详细信息。细节将包含场所的几何形状。

注意:placesService是google.maps.places.PlacesService-object。

答案 1 :(得分:2)

试试这个:

function onSelectAddress(address, callback) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            callback(results[0].geometry.location);
        } else {
            alert("Can't find address: " + status);
            callback(null);
        }
    });
}

然后,呼叫和回调:

onSelectAddress('your address here', function(location){
//Do something with location
if (location)
     alert(location);
});

抱歉我的英文。我有个问题要问你: 你能告诉我showInAutoComplete()方法??? 我在href列表中显示预测,但我不知道如何保存“点击”的地址值。

答案 2 :(得分:2)

以下是我编写的代码,其灵感来自@ Dr.Molle

    function initializePlaces(q) {
        googleAutocompleteService = new google.maps.places.AutocompleteService();            
        if(q){
            googleAutocompleteService.getPlacePredictions({
                input: q
            }, callbackPlaces);
        }else { //no value entered loop }
    }

    function callbackPlaces(predictions, status) {
        if (status != google.maps.places.PlacesServiceStatus.OK) {
            alert(status);
            return;
        }

        for (var i = 0; i < predictions.length; i++) {
            googlePlacesService = new google.maps.places.PlacesService(document.getElementById("q"));
            googlePlacesService.getDetails({
                reference: predictions[i].reference
            }, function(details, status){
                if(details){
                    console.log(details.geometry.location.toString());
                }
            });
            console.log(predictions[i].description);
        }
    };

    google.maps.event.addDomListener(window, 'load', initializePlaces);

    $(document).on('keyup', 'input#q', function(e){
        initializePlaces($(this).val());
    });

问题我看到每个按键上都有一个新的PlacesService对象可能是一种矫枉过正 - 虽然我不知道这方面的工作。

在此处发布,以防有​​人正在寻找它。

答案 3 :(得分:1)

如果您需要按正确顺序一次性返回所有结果,请使用:

var service = new google.maps.places.AutocompleteService();
service.getPlacePredictions({
    input: '*** YOUR QUERY ***'
}, function(predictions, status) {
    var data = [];

    if (status != google.maps.places.PlacesServiceStatus.OK) {
        console.error(status);
        processResults(data);
        return;
    }

    var s = new google.maps.places.PlacesService(document.createElement('span'));
    var l = predictions.length;
    for (var i = 0, prediction; prediction = predictions[i]; i++) {
        (function(i) {
            s.getDetails(
                {
                    reference: prediction.reference
                },
                function (details, status) {
                    if (status == google.maps.places.PlacesServiceStatus.OK) {
                        data[i] = details;
                    } else {
                        data[i] = null;
                    }
                    if (data.length == l) {
                        processResults(data);
                    }
                }
            );
        })(i);
    } });

function processResults(data) {
    console.log(data);
}

答案 4 :(得分:1)

AutocompleteService返回的预测具有 PlaceId 属性。您可以根据文档https://developers.google.com/maps/documentation/javascript/geocoding将PlaceId而不是地址传递给地理编码器。

var service = new google.maps.places.AutocompleteService();
var request = { input: 'storms river mouth' };
service.getPlacePredictions(request, function (predictions, status) {
    if(status=='OK'){
        geocoder.geocode({ 
            'placeId': predictions[0].place_id
        }, 
        function(responses, status) {
            if (status == 'OK') {
                var lat = responses[0].geometry.location.lat();
                var lng = responses[0].geometry.location.lng();
                console.log(lat, lng);
            }
        });
    }
});

答案 5 :(得分:-1)

也许这可以帮到你。

 var autocomplete = new google.maps.places.Autocomplete(this.input);
 //this.input is the node the AutocompleteService bindTo
 autocomplete.bindTo('bounds', this.map);
 //this.map is the map which has been instantiated

 google.maps.event.addListener(autocomplete, 'place_changed', function() {
     var place = autocomplete.getPlace();
     //then get lattude and longitude
     console.log(place.geometry.location.lat());
     console.log(place.geometry.location.lng());
 }