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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14414445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:35:14  来源:igfitidea点击:

Google maps API V3 - Can't geocode AutocompleteService predictions

javascriptgoogle-mapsgoogle-maps-api-3google-geocoder

提问by badsyntax

I'm using the google.maps.places.AutocompleteServiceto get suggestions for a places search, but I can't geocode some of the predictions.

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

An example of this: When I search for 'storms river mouth', one of the predictions I get back is 'Storms River Mouth Rest Camp, South Africa', but this address cannot be geocoded to get the lattude/longitude, eg: http://maps.googleapis.com/maps/api/geocode/json?address=Storms%20River%20Mouth%20Rest%20Camp,%20South%20Africa&sensor=true

一个例子:当我搜索“风暴河口”时,我得到的预测之一是“南非风暴河口休息营”,但无法对该地址进行地理编码以获取纬度/经度,例如:http ://maps.googleapis.com/maps/api/geocode/json?address=Storms%20River%20Mouth%20Rest%20Camp,%20South%20Africa&sensor=true

Is there any way to get lattitude/longitude values for the autocomplete predictions?

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

Alternatively, I don't understand why google autocomplete is returning predictions that I cannot geocode.

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

Here is a basic example of the logic and code i'm working with:

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

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] - View a working example here: http://demos.badsyntax.co/places-search-bootstrap/example.html

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

回答by Dr.Molle

Use getPlacePredictions()instead of getQueryPredictions(). This will return a referencefor the place, which you can use to retrieve details by using placesService.getDetails(). The details will contain the geometry for the place.

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

Note: placesService is a google.maps.places.PlacesService-object.

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

回答by Parmjeet Singh

Predictions returned by AutocompleteService has a PlaceIdproperty. You can pass PlaceId instead of address to the geocoder according to documentation https://developers.google.com/maps/documentation/javascript/geocoding.

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);
            }
        });
    }
});

回答by Kkk

Try this:

试试这个:

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);
        }
    });
}

Then, the call and the callback:

然后,调用和回调:

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

Sorry for my english. I got a question for you: Can you show me the method showInAutoComplete() ??? I'm showing the predictions on a list of href, but I don't know how save the 'clicked' address value.

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

回答by foxybagga

Here is the code I have written that is inspired from @Dr.Molle

这是我编写的代码,其灵感来自@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.

我看到的问题是每次按键时都有一个新的 PlacesService 对象,这可能是一种矫枉过正——尽管我不知道解决方法。

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

在这里张贴以防万一有人正在寻找它。

回答by gondo

If you need to return all results at once in proper order, use this:

如果您需要以正确的顺序一次返回所有结果,请使用以下命令:

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);
}

回答by Li Dian

Maybe this could could help you.

也许这可以帮助你。

 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());
 }