我这里有一个脚本:
<!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_1
和administrative_area_level_2
的long_name,short_name,如下图所示。
答案 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);
使用此脚本:
<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)
答案 2 :(得分:0)
如果您想在选择地点后处理结果,则必须绑定事件,如下所示
google.maps.event.addListener(autocomplete, 'place_changed', your_function);
以下页面上的代码对您https://google-developers.appspot.com/maps/documentation/javascript/examples/places-autocomplete
非常有帮助