[英]how to get latitude longitude from function and send it to new google.maps.LatLng( latitude ,longitude ) 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);
}
所以我的问题是如何从功能中获取经度和纬度? 谢谢
根据您的标题(可能是错误的,您应该明确指出代码在问题中的作用),听起来好像您已成功获取经度和纬度,但没有将其发送到地图。
问题可能出在以下事实:
由于Google Maps API需要调用外部服务器,因此访问地理编码服务是异步的。 因此,您需要传递一个回调方法以在请求完成时执行。 此回调方法处理结果。 请注意,地理编码器可能会返回多个结果。 ( API文档 )
这是异步的,这意味着当您的回调函数( function(results, status) {...})
等待响应时,您还将执行以下行:
var center = new google.maps.LatLng(latitude,longitude );
但是,当然,由于我们还没有回应,因此尚未定义纬度和经度。
要明确地看到这一点,请将代码定义center
替换为alert()
或console.log()
,然后将另一个放置在回调函数中,看看首先触发什么:
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");
最简单的解决方案可能是将需要此特定经度和纬度的代码放置在回调函数中,以使该代码直到您收到响应并扩展为纬度和经度后才执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.