[英]Update global variable in javascript
我在javascript中有一个全局变量,例如
var EventLocation = {
'center' : '35.59214,-121.046048',
'zoom' : 10
};
现在在函数中,我们将此变量更新为
var geocoder = new google.maps.Geocoder();
var address = $j('#EventLocation').text(); //record.Location;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
EventLocation.center = new google.maps.LatLng(latitude, longitude);
//onSuccessMaps(latitude,longitude);
} else {
alert('Fail to find location');
}
});
但是在另一个未更新EventLocation.center的函数中,该函数将先前的值设为('35.59214,-121.046048')
。 我该如何解决?
地址解析调用是异步的,因此代码将在等待响应的同时继续运行。 实际上,您必须先将控件返回到浏览器,然后才能处理响应。
这意味着必须从成功回调方法中调用任何需要坐标的方法:
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
EventLocation.center = new google.maps.LatLng(latitude, longitude);
// here the coordinates _are_ set
// this is where you put the code that needs to use the coordinates
} else {
alert('Fail to find location');
}
});
// here the coordinates are _not_ set yet
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.