如何在循环外访问地理编码坐标?

时间:2015-11-04 06:46:28

标签: javascript google-maps google-maps-api-3 google-geocoder

这与此问题类似:HERE。但我仍然无法解决这个问题。 我想从地理编码器获取lat / lng值,但我无法在if语句之外访问它们。我知道大多数事情都有效,因为我可以使用console.log()访问地理编码lat / lng值,但我无法将其删除。我认为这与js范围有关。如果我使用下面的代码,我会收到此错误:

  

"未捕获的TypeError:无法读取属性' geocode'未定义"。

但如果我将此部分var myLoc = codeAddress(addressInput);注释掉,我可以使用console.log()获取数组。

如何获取loc(或每个值)数组?

这是我的代码。

var geocoder;
var map;

var addressInput = '<?php 
    echo $_GET["q"]; ? > ';
var loc = [];

function initialize() {
    geocoder = new google.maps.Geocoder();
    codeAddress(addressInput);
}

function codeAddress(address) {
    // next line creates asynchronous request
    geocoder.geocode({
        'address': address
    }, function(results, status) {
        // and this is function which processes response
        if (status == google.maps.GeocoderStatus.OK) {
            loc[0] = results[0].geometry.location.lat();
            loc[1] = results[0].geometry.location.lng();
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }

        console.log(loc);
        // above shows the correct lat/lng values in the console when I comment out the 'myLoc' code below.
    });
    return loc;

}
var myLoc = codeAddress(addressInput);

google.maps.event.addDomListener(window, 'load', initialize);

1 个答案:

答案 0 :(得分:1)

问题是除了指定全局变量maploc等之外,代码中执行的第一行是:

var myLoc = codeAddress(addressInput);

此时尚未创建geocoder函数所需的codeAddress

鉴于你几乎立刻就在窗口加载时,再次调用codeAddress,我不确定这个初始调用的重点。只需将您的代码更改为:

var geocoder, map, myLoc;

var addressInput = '<?php 
    echo $_GET["q"]; ? > ';
var loc = [];

function initialize() {
    geocoder = new google.maps.Geocoder();
    myLoc = codeAddress(addressInput);
    console.log(myLoc);
}

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

        console.log(loc);
    });
    return loc;
}

google.maps.event.addDomListener(window, 'load', initialize);