如何从功能获取经纬度并将其发送到新的google.maps.LatLng(经度,纬度)的JavaScript
我使用这个脚本从一个地址获取经纬度,如何从功能获取经纬度并将其发送到新的google.maps.LatLng(经度,纬度)的JavaScript
var latitude="";
var longitude ="";
function codeAddress(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address}, function(results, status) {
if (status == 'OK') {
latitude = results[0].geometry.location.lat();
longitude = results[0].geometry.location.lng();
// myAfterFunction();
// console.log(this.latitude);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
var center = new google.maps.LatLng(latitude,longitude);
我的问题是我无法在这部函数来获取经纬度值,我尝试使用其他功能
function myAfterFunction(){
console.log(latitude);
}
所以我的问题是如何从我的功能得到纬度和经度?谢谢
基于你的标题(我可能是错的,你应该清楚地表明你的代码做在什么的问题),这听起来像您成功获得纬度和经度,但随后未能将其发送到地图。
问题可能在于这样一个事实:
访问地理编码服务是异步的,因为谷歌地图 API需要外部服务器的呼叫。因此, 需要传递回调方法,以在完成 请求时执行。这个回调方法处理结果。请注意, 地理编码器可能会返回多个结果。 (API docs)
这样做的异步特性意味着,当你的回调函数(function(results, status) {...})
)是在响应等待,你也执行这一行:
var center = new google.maps.LatLng(latitude,longitude);
但是,当然,经纬度还没有定义,因为我们还没有回应。
要在行动中明确地看到这一点,替代与alert()
或console.log()
定义center
的代码,并将陆续在回调函数,并首先看到触发:
function codeAddress(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address}, function(results, status) {
console.log("Response recieved");
}
});
}
console.log("Tried to use response");
最简单的解决办法可能是地方在回调函数中需要这个特定经度和纬度的代码,这样它才会执行,直到你有一个响应,并扩展一个经度和纬度。
感谢您的回复,但即使我在我的函数中放置了var center = new google.maps.LatLng(纬度,经度),我稍后需要这个中心值,因为我有长脚本 –
如果你想使用这些变量(经度和纬度),你必须在回调函数中使用它,除非你有一个方法来确定回调完成的时间(可能是一个函数,检查每一秒,看看那些变量被定义),但是将所有长脚本放入函数并在回调函数内调用该函数应该相当容易(实际上,这是一种将需要经度和纬度的所有代码放入调用的视觉上不同的方式后退功能)。 –
你得到的错误是什么? –
当我写console.log(纬度); console.log(longitude);出了函数,它说undefined undefined –