8

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

一个例子:当我搜索“ storms river mouth ”时,我得到的预测之一是“ Storms River Mouth Rest Camp, South Africa ”,但无法对该地址进行地理编码以获取纬度/经度,例如: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
  });
}

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

4

6 回答 6

11

使用getPlacePredictions()而不是getQueryPredictions(). 这将返回reference该地点的一个,您可以使用它来检索详细信息placesService.getDetails()。详细信息将包含该地点的几何形状。

注意:placesService 是一个 google.maps.places.PlacesService 对象。

于 2013-01-19T13:02:55.517 回答
8

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);
            }
        });
    }
});
于 2016-07-19T06:49:30.613 回答
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 列表中显示预测,但我不知道如何保存“点击”地址值。

于 2013-02-07T09:22:18.390 回答
2

Here is the code I have written that is inspired from @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());
    });

Issue I see is a new PlacesService object on every key press that might be an overkill - I don't know the work around although.

Posting it here in-case someone is looking for it.

于 2013-08-06T19:57:04.360 回答
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);
}
于 2015-07-19T00:15:35.787 回答
-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());
 }
于 2013-01-19T12:56:31.297 回答