繁体   English   中英

添加到全局数组变量的项不会在添加函数之外保留

[英]Items added to a global array variable do not persist outside of the adding function

我正在尝试使用Google地图JavaScript API在两点之间划一条线。 这两个点需要进行地理编码(转换为google.maps.LatLong对象)才能用于绘制线条。

Geocoding函数是codeAddress,当它返回时,它调用回调函数,该函数将新latlong添加到名为points的全局数组中。 由于某种原因,添加到点的值不会在数组外部持久存在。 我对JavaScript比较陌生,所以我不知道可能出现什么问题,任何想法都会受到赞赏!

var points = new Array();

function addGeocodedLatLongToGlobalList(address) {
        points.push(address);
        alert("added a point " + points[0]); // correctly outputs latlong object
    }

function codeAddress(address) {
    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': address, }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            addGeocodedLatLongToGlobalList(results[0].geometry.location);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

function drawLine(address1, address2, color) {

    codeAddress(address1);
    codeAddress(address2);

    alert("there is a point " + points[0]);  //now the points[0] value is undefined
    ...

我猜你在异步地理编码功能完成之前正在查看点数组,并且这些点实际上已被放入数组中。

geocoder.geocode()函数可能是一个异步函数,您对codeAddress函数的调用仅启动该进程,并在稍后完成。 这可以解释为什么drawLine()函数中的alert()没有看到任何点 - 它们还没有。 当geoCode函数实际完成并调用它的回调时,它们将被放入points数组中。

可能的问题是,您作为第二个参数传递给geocoder.geocode的回调函数尚未被调用。 地理编码器可能刚刚存储它以便稍后在某些事件时调用它。 在回调函数中放置一些alert以查看它是否真的被调用!

...
geocoder.geocode({ 'address': address, }, function (results, status) {
        alert("CALLBACK CALLED!!");
        if (status == google.maps.GeocoderStatus.OK) {
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM