0

我在这里有一个脚本:

<!DOCTYPE html>
<html>
  <head>
    <title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
    <script>
      function initialize() {
        var input = document.getElementById('searchTextField');
        var options = {
            types: ['(cities)'],
            componentRestrictions: {country: 'us'}
        };

        var autocomplete = new google.maps.places.Autocomplete(input, options);
}
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div>
      <input id="searchTextField" type="text" size="50">
    </div>
  </body>
</html>

我要做的就是从自动完成获取 JSON 输出并提取 long_name 、 short_nameadministrative_area_level_1administrative_area_level_2查看下图。

我想要的截图

4

3 回答 3

1

使用http://api.jquery.com/jQuery.parseJSON/ 像这样:

var results = jQuery.parseJSON(google_json);

然后:

alert(results[0].types[0]);
alert(results[0].types[1]);

因此,使用 google-places 自动完成功能,您需要在此链接中执行此操作:https ://developers.google.com/maps/documentation/javascript/places?hl=pl#places_autocomplete

var input = document.getElementById('searchTextField'); // input must be global
function initialize() {

    var options = {
        types: ['(cities)'],
        componentRestrictions: {country: 'us'}
    };

    //var autocomplete = new google.maps.places.Autocomplete(input, options);
    var service = new google.maps.places.AutocompleteService();
    service.getQueryPredictions(input, callback);



}

function callback(predictions, status) {
    for (var i = 0, prediction; prediction = predictions[i]; i++) {
        alert(prediction.types[0]);
        alert(prediction.types[1]);
    }
}
google.maps.event.addDomListener(window, 'load', initialize);

在这里你有活的例子:https ://google-developers.appspot.com/maps/documentation/javascript/examples/places-queryprediction?hl=pl

最终更新

使用这个脚本:

<script>

    function initialize() {
        var input = document.getElementById('searchTextField');
        var options = {
    types: ['(cities)'],
    componentRestrictions: {country: 'us'}
    };

    var autocomplete = new google.maps.places.Autocomplete(input, options);
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
       alert(this.types[0]);
       alert(this.types[1]);          
    });




    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>
于 2012-10-25T09:27:29.653 回答
1

这很简单,但很难找到:

最后使用 GeoComplete JS 实现:

http://ubilabs.github.com/geocomplete/

网站有足够的文档来协助实施。

于 2012-11-09T10:28:31.093 回答
0

如果您想在选择地点后处理结果,您必须绑定如下事件

google.maps.event.addListener(autocomplete, 'place_changed', your_function);

以下页面上的代码将对您非常有帮助https://google-developers.appspot.com/maps/documentation/javascript/examples/places-autocomplete

于 2012-10-25T10:17:03.007 回答