【发布时间】:2013-05-06 12:40:03
【问题描述】:
我想知道是否有人能够帮助我。我很难在地理编码结果的对话框中将坐标和格式化地址返回给我,即使我似乎能够抓住城市、国家。
这是我正在使用的代码:
http://jsfiddle.net/d5DBh/5/
代码
var myLatlng = new google.maps.LatLng(31.272410, 0.190898);
// INITALIZATION
function initialize() {
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
// GEOCODE
function codeAddress() {
var address = document.getElementById("address").value;
new google.maps.Geocoder().geocode({
'address': address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var address = "",
city = "",
town = "",
state = "",
country = "",
location = "",
format = "";
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
if (addr.types[0] == 'country') country = addr.short_name;
else if (addr.types[0] == 'street_address')
address = address + addr.long_name;
else if (addr.types[0] == 'route')
address = address + addr.long_name;
else if (addr.types[0] == ['administrative_area_level_1'])
state = addr.long_name;
else if (addr.types[0] == ['administrative_area_level_2'])
town = addr.long_name;
else if (addr.types[0] == ['locality'])
city = addr.long_name;
else if (addr.types[0] == ['location'])
location = addr.location;
}
alert('Formated Address: ' + format + '\n' + 'City: ' + city + '\n' + 'Town: ' + town + '\n' + 'State: ' + state + '\n' + 'Country: ' + country + '\n' + 'Coordinates: ' + location);
}
} else {
alert("Error: We could not find this address - please try and different location");
};
});
}
initialize();
document.getElementById("searchItem").onclick = function () {
codeAddress();
return false;
};
此外,由于我是 Javascript 新手,因此我愿意接受任何关于更简洁地编写此代码的想法。
【问题讨论】:
-
嗨。这是一个很好的答案,但不包括特定于这个特定问题的坐标或格式化地址。
-
您查看过地理编码器输出的 API 文档吗?它显示返回坐标的位置。developers.google.com/maps/documentation/geocoding/#XML
标签: javascript jquery google-maps google-maps-api-3 geolocation