将变量传递给javascript公式时出错(“undefined”)

时间:2015-03-25 08:24:34

标签: javascript google-maps-api-3 geocoding var

我有以下脚本,旨在将来自Google Maps API v3地理编码纬度和经度的变量传递给hasrsine公式。但是,每次它说我的地理编码的变量并没有定义":

var address = ['London'];

jQuery.each(address, function(index, item) {
  geocoder = new google.maps.Geocoder(); 
  geocoder.geocode( { 'address': item}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      startlat = results[0].geometry.location.lat();
      startlng = results[0].geometry.location.lng();
    } 
   });
  });

// start of haversine for marker distances
Number.prototype.toRad = function() {
   return this * Math.PI / 180;
};

var mlat = '50.1'; 
var mlng = '-1.05';  

var RDis = '3963'; // miles; Change to 6371 for km 
var x1 = mlat - startlat;
var dLat = x1.toRad();  
var x2 = mlng - startlng;
var dLon = x2.toRad();  
var aDis = Math.sin(dLat/2) * Math.sin(dLat/2) + 
                Math.cos(startlat.toRad()) * Math.cos(mlat.toRad()) * 
                Math.sin(dLon/2) * Math.sin(dLon/2);  
var cDis = 2 * Math.atan2(Math.sqrt(aDis), Math.sqrt(1-aDis)); 
var dDis = RDis * cDis; 
// dDis is the distance

有人可以建议我如何通过脚本传递这些内容吗?将地理编码包含在与hasrsine相同的功能中并不是一个选项(我也需要在其他地方使用它们)。

感谢您的帮助。 :)

1 个答案:

答案 0 :(得分:0)

地图API调用异步,因此在回调发生之前您无法使用startlatstartlng

// ****** Moved this
// start of haversine for marker distances
Number.prototype.toRad = function() {
    return this * Math.PI / 180;
};

var address = ['London'];

jQuery.each(address, function(index, item) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'address': item
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            startlat = results[0].geometry.location.lat();
            startlng = results[0].geometry.location.lng();

            // ********* Moved block starts here *********
            var mlat = '50.1';
            var mlng = '-1.05';

            var RDis = '3963'; // miles; Change to 6371 for km 
            var x1 = mlat - startlat;
            var dLat = x1.toRad();
            var x2 = mlng - startlng;
            var dLon = x2.toRad();
            var aDis = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(startlat.toRad()) * Math.cos(mlat.toRad()) *
                Math.sin(dLon / 2) * Math.sin(dLon / 2);
            var cDis = 2 * Math.atan2(Math.sqrt(aDis), Math.sqrt(1 - aDis));
            var dDis = RDis * cDis;
            // dDis is the distance
            // ********* Moved block ends here *********
        }
    });
});

How to return the response from an asynchronous call?

中的更多信息