我一直在尝试使用一些ajax在我的应用程序中保存地点位置,并在堆栈溢出时偶然发现了以下代码
function getLatLong(address)
{
var geocoder = new google.maps.Geocoder();
var result = "";
geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result[lat] = results[0].geometry.location.Pa;
result[lng] = results[0].geometry.location.Qa;
} else {
result = "Unable to find address: " + status;
}
});
return result;
}我的问题是,当我调用函数时,它不返回任何东西,而当我在chrome中调试和设置断点时,它首先在返回结果上中断,然后在resultlat =results.geometry.location.Pa上中断;
我知道数组应该声明为类型数组,但是即使在我只是返回results.geometry.location对象时,也没有返回任何内容
我可以做什么来返回位置的经度/纬度,以便可以存储在我的数据库中?
发布于 2012-01-11 01:03:17
您面临的问题是,您将geocoder.geocode函数视为在返回结果之前立即完成。实际发生的情况是,geocoder.geocode被触发,然后立即返回结果。因为异步结果很可能没有返回,所以结果是空的。将地理编码结果视为推,而不是拉。storeResult函数(未显示)是保存信息所需的任何代码。因为要将结果与错误字符串组合在一起,所以必须在storeResult函数中处理。或者,您可以在结果中具有指示成功或失败的状态。
function getLatLong(address) {
var geocoder = new google.maps.Geocoder();
var result = "";
geocoder.geocode( { 'address': address, 'region': 'uk' }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
result[lat] = results[0].geometry.location.Pa;
result[lng] = results[0].geometry.location.Qa;
} else {
result = "Unable to find address: " + status;
}
storeResult(result);
});
}发布于 2012-01-15 08:17:05
这不是答案,但不要使用Pa和Qa,始终使用lng()和lat()函数:
place.geometry.location
{...}
Pa: 56.240477
Qa: -0.902655999999979
toString: function(){return"("+this.lat()+", "+this.lng()+")"}
equals: function(a){return!a?k:Cd(this.lat(),a.lat())&&Cd(this.lng(),a.lng())}
lat: function(){return this[a]}
lng: function(){return this[a]}
toUrlValue: function(a){a=Hd(a)?a:6;return $d(this.lat(),a)+","+$d(this.lng(),a)}发布于 2018-10-26 20:37:25
function getLatLong(address)
{
var geocoder = new google.maps.Geocoder();
var result = '';
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// Call the lat/lng functions to return a computed value.
result[lat] = results[0].geometry.location.lat();
result[lng] = results[0].geometry.location.lng();
} else {
result = 'Unable to find address: ' + status;
}
});
return result;
}
getLatLong('address'); https://stackoverflow.com/questions/8807141
复制相似问题