0

我這裏有一個腳本:如何使用Javascript解碼Google Places JSON?

<!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> 

所有我想要做的是,您可以通過自動完成和提取LONG_NAME輸出,SHORT_NAME的administrative_area_level_1的JSON和administrative_area_level_2看到下面的圖片。與谷歌,地方autocompleate你需要做的這個像在這個環節

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

所以:

Screenshot of what I want

回答

1

使用http://api.jquery.com/jQuery.parseJSON/ 像這樣:

var results = jQuery.parseJSON(google_json); 

然後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> 
+0

對不起,超級笨笨,但是,將在初始化()? – Karma

+0

我需要檢查goolge autocompleate語法。 –

+1

你走了!只要取代你JS –

0

如果你要處理的地方選擇之後的結果,你必須像下面

綁定事件
google.maps.event.addListener(autocomplete, 'place_changed', your_function); 

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

+0

Dang!在我的initialize()函數中如何放置它? – Karma

+0

我已經部分複製了我的代碼,只能從該參考鏈接中複製。密切地,我甚至沒有刪除默認的'id' :-) – Karma