簡體   English   中英

如何使用Javascript解碼Google Places JSON?

[英]How to decode Google Places JSON using Javascript?

我這里有一個腳本:

<!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, administrative_area_level_1administrative_area_level_2 short_name,請參見下圖。

我想要的截圖

使用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>

這很簡單但很難找到:

最后使用以下方法實現了GeoComplete JS:

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

網站足以記錄以協助實施。

如果要在選擇位置后處理結果,則必須綁定如下所示的事件

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

以下頁面上的代碼對您非常有幫助https://google-developers.appspot.com/maps/documentation/javascript/examples/places-autocomplete

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM