阅读这个 Headers 可能会让人感到困惑......我同意 .
所以我有一个地址,我想在谷歌 Map 上显示 . 我没有lat / long,所以我需要调用Google Maps API提供的Geocoder服务 .
当我请求lat / long一个地址时,服务返回一个合法的值,但是当在地理编码函数的最后一行单步执行javascript时,代码会进入geocoder.js缩小的代码并且永远不会返回(不成功的结果,也不例外) .
我已经做了很多关于使用Google Maps API的研究,据我所知,我已经完全实现了示例的显示方式 . 我在哪里错了?
这是调用lat / long服务的javascript代码:
function getLatLong(street, city, state, zip) {
var geocoder = new google.maps.Geocoder();
var address = street && street.length > 0 ? street + ' ' : '';
address += city && city.length > 0 ? city + ', ' : '';
address += state && state.length > 0 ? state + ' ' : '';
address += zip && zip.length > 0 ? zip : '';
var latLong = {
lat: 0.0,
long: 0.0
};
try {
geocoder.geocode({ 'address' : address }, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
return {
lat: results[0].geometry.location.lat(),
long: results[0].geometry.location.lng()
};
} else {
return latLong;
}
});
} catch (exception) {
alert(e.message);
}
}
(如果您在上面的代码中 catch
上方的行上没有't want to step through, it' s "getting lost")
如果你想看到它在行动并为自己一步一步,这里是URL:http://golfproxy.com/course/list
编辑:如果有帮助,这里是添加 Map 和标记的函数,它调用上面的getLatLong函数:
function plotMapHardCodePos(position) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 9,
center: position
});
$.each(tournaments.Result, function (i, item) {
var latLong = {};
if (!item.Latitude || !item.Longitude) {
latLong = getLatLong(item.Street, item.City, item.State, item.ZipCode);
if (latLong) {
item.Latitude = latLong.lat;
item.Longitude = latLong.long;
}
}
if (!(item.Latitude === 0.0 && item.Longitude === 0.0)) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(item.Latitude, item.Longitude),
map: map
});
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png');
var infoWindow = new google.maps.InfoWindow({
content: "<div class=''><h4><a href=\"#\">" + item.Name + "</a></h4></div>
<span>" +
item.Body1 + "</span>" + "
<span>" + item.Body2 + "</span>"
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
});
}
1 回答
您无法从异步回调函数返回任何内容,您需要在回调函数中使用/何时可用的数据