我是 jquery 新手,但目前我遇到了一些困难。据我所知,最终的想法是执行以下操作:
- 用户输入地址并点击搜索
- Google 地理编码器运行
- 如果没有结果则出错,或者获取坐标、州、邮政编码、国家/地区、城市并在消息框中打印
我现在的代码甚至无法完成从输入框中抓取坐标的过程。它一直告诉我它正在等待一个支架,但无论我将支架放在哪里,我都无法让它运行。
这是我尝试运行的:
http://jsfiddle.net/QA7Xr/16/
完整代码如下:
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;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("Geocode was successful");
};
} else {
alert("Geocode was not successful for the following reason: " + status);
};
};
}
// GET ADDRESS DETAILS
function getLatLongDetail() {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': myLatlng
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var address = "",
city = "",
state = "",
zip = "",
country = "";
for (var i = 0; i < results[0].address_components.length; i++) {
var addr = results[0].address_components[i];
// check if this entry in address_components has a type of country
if (addr.types[0] == 'country') country = addr.long_name;
else if (addr.types[0] == 'street_address') // address 1
address = address + addr.long_name;
else if (addr.types[0] == 'establishment') address = address + addr.long_name;
else if (addr.types[0] == 'route') // address 2
address = address + addr.long_name;
else if (addr.types[0] == 'postal_code') // Zip
zip = addr.short_name;
else if (addr.types[0] == ['administrative_area_level_1']) // State
state = addr.long_name;
else if (addr.types[0] == ['locality']) // City
city = addr.long_name;
}
alert('City: ' + city + '\n' + 'State: ' + state + '\n' + 'Zip: ' + zip + '\n' + 'Country: ' + country);
}
}
});
}
initialize();
getLatLongDetail();
谁能告诉我哪里错了?我已经陷入了困境。
最佳答案
你的JS乱七八糟,我已经整理好了:http://jsfiddle.net/QA7Xr/19/
按顺序:
- 函数中的两个额外的右括号
- 您使用的
getElementById()
使用的 ID 不存在 - 当 JS 分配更容易时,您可以绑定(bind) onClick
- 您的
geocoder
var 是 getLatLongDetail 中的本地变量。您在 codeAddress 中需要它,所以我将其设置为全局。
需要改进的地方:
- 将代码封装在闭包中以避免命名空间污染
- 使用 Google 事件来控制您的代码分配。现在,如果用户点击太快,您的代码将会抛出
- 简化逻辑
关于javascript - 使用 Google 和 Jquery 进行地理编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16499826/