如何让 Google Maps API 返回国家名称和城市,并将其保存在变量 django 中
问问题
1139 次
1 回答
2
由于您的问题缺少信息,以下是 Google 自动完整文本输入。您输入位置,它将返回显示在li
标签中的城市、州、国家、邮政编码、纬度、经度(它找到的)。您可以使用该方法存储在其他变量中,而不是li
. 这是它的jsfiddle。
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=true"></script>
<script>
$(document).ready(function(){
var geocoder;
geocoder = new google.maps.Geocoder();
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
var input = document.getElementById('location');
var options = {
bounds: defaultBounds,
types: ['(regions)']
};
autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
var city;
var state;
var country;
var postcode;
var latitude;
var longitude;
if (place){
address_components = place.address_components;
if (address_components){
for (index in address_components){
component = address_components[index];
if (component.types.indexOf('locality') > -1){
city = component.long_name;
}
if (component.types.indexOf('administrative_area_level_1') > -1){
state = component.long_name;
if (!state){
if (component.types.indexOf('administrative_area_level_2') > -1){
state = component.long_name;
if (!state){
if (component.types.indexOf('administrative_area_level_3') > -1){
state = component.long_name;
}
}
}
}
}
if (component.types.indexOf('country') > -1){
country = component.long_name;
}
if (component.types.indexOf('postal_code') > -1){
postcode = component.long_name;
}
}
}
if (place.geometry){
if (place.geometry.location){
latitude = place.geometry.location.lat();
longitude = place.geometry.location.lng();
}
}
}
if (city){
$('.city').text('City: ' + city);
}else{$('.city').text('City: ');}
if (state){
$('.state').text('State: ' + state);
}else{$('.state').text('State: ');}
if (country){
$('.country').text('Country: ' + country);
}else{$('.country').text('Country: ');}
if (postcode){
$('.postcode').text('Postcode: ' + postcode);
}else{$('.postcode').text('Postcode: ');}
if (latitude){
$('.latitude').text('Latitude: ' + latitude);
}else{$('.latitude').text('Latitude: ');}
if (longitude){
$('.longitude').text('Longitude: ' + longitude);
}else{$('.longitude').text('Longitude: ');}
});
});
</script>
</head>
<body>
<input type="text" id="location" name="location">
<ul>
<li class="city">City: </li>
<li class="state">State: </li>
<li class="country">Country: </li>
<li class="postcode">Postcode: </li>
<li class="latitude">Latitude: </li>
<li class="longitude">Longitude: </li>
</ul>
</body>
</html>
于 2012-12-22T22:13:14.620 回答