如何使用Javascript解码Google Places JSON?

时间:2012-10-25 09:24:10

标签: javascript json google-maps google-maps-api-3 google-places

我这里有一个脚本:

<!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输出并提取administrative_area_level_1administrative_area_level_2的long_name,short_name,如下图所示。

Screenshot of what I want

3 个答案:

答案 0 :(得分: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>

答案 1 :(得分:1)

这很简单但很难找到:

最后使用:

实现了GeoComplete JS

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

网站足以记录以协助实施。

答案 2 :(得分:0)

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

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

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

非常有帮助