0

我在javascript函数中有问题,有两个变量在函数的全局范围内声明并在jquery插件中设置。如何在 jquery 之外获取这些变量值。

 function GetDirectionFromCurrentLocation(StoreAddress) {
var positionStore = null;
var positionCurrent = null;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': StoreAddress }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        positionStore = results[0].geometry.location;
    }
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            positionCurrent = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

        });
    }

});
window.open("http://maps.google.com/maps?saddr=" + positionCurrent + "&daddr=" + positionStore + "&hl=en&output=html");
 }

这些变量始终为空。

4

3 回答 3

0

您的地理编码调用似乎是异步的,当您的代码到达窗口打开调用时,后台作业尚未完成。

function GetDirectionFromCurrentLocation(StoreAddress) {
    var positionStore = null;
    var positionCurrent = null;
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': StoreAddress }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            positionStore = results[0].geometry.location;
        }
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                positionCurrent = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

            });
        }

        if (positionCurrent && positionStore) {
            window.open("http://maps.google.com/maps?saddr=" + positionCurrent + "&daddr=" + positionStore + "&hl=en&output=html");
        }
    });

 }
于 2013-05-08T11:30:01.530 回答
0

将您的window.open调用移到匿名函数中。您的变量为空,因为window.open在调用匿名函数之前调用了您的代码行。

于 2013-05-08T11:30:14.080 回答
0

我建议你在 jQuery 函数中打开新窗口,因为它需要同步才能获得正确的值。

于 2013-05-08T11:31:06.697 回答