一个我似乎无法正常工作的简单方法。
我有以下内容:
function geocode(address, callback) {
if (typeof (geocoder) == 'undefined') geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback({ Latitude: results[0].geometry.location.lat(), Longitude: results[0].geometry.location.lng() });
}
else {
callback(0);
console.log("Geocode was not successful for the following reason: " + status);
}
});
}
通过以下方式调用:
var latitude = '';
var longitude = '';
geocode(self.address(), function (result) {
if (result === 0) {
//Error with geocoding
}
else {
latitude = result.Latitude;
longitude = result.Longitude;
}
});
//Do some stuff with latitude and longitude
现在,结果会返回,但是它们是异步的,这就是我认为回调会克服的结果,例如<{1}}和latitude
值未定义。
答案 0 :(得分:0)
我认为这是正确的方法
var latitude = '';
var longitude = '';
geocode(self.address(), function (result) {
if (result === 0) {
//Error with geocoding
}
else {
....
manage your latitude, longitude
....
}
});
function geocode(address) {
if (typeof (geocoder) == 'undefined') geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
latitude = results[0].geometry.location.lat();
longitude =results[0].geometry.location.lng() });
}
else {
console.log("Geocode was not successful for the following reason: " + status);
}
});