从地理编码器功能中取出位置

时间:2014-05-26 04:48:11

标签: javascript google-maps-api-3

我试图将我的地址值分配给另一个变量,但我得到的是未定义的或类似我的变量中的url

这是我的编码。因为这个我几乎要崩溃了。

function geoCoding(displayname, trackerModel, setupType, marker, index){


var setupMessageInfoWindow;
var geocoder = new google.maps.Geocoder();

    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {

            var location = results[1].formatted_address;


        } else {
            alert('No results found at marker ' + marker.position);
        }
    } else {
        alert('Geocoder failed due to: ' + status);
    }
    });



    setupMessageInfoWindow = "<div height=\"300\" width=\"300\"><b>" + displayname + "</b>"
                        + " <br> Location : " + location
                        //+ " <br> Tracker id : " + userid
                        //+ " <br> imei : " + imei
                        + " <br> Tracker Type : " + trackerModel
                        //+ " <br> Mobile Number : " + 
                        //+ " <br> Location : " + location;
                        + " <br> " + setupType
                        + "</div>" ;



    return setupMessageInfoWindow;

}

1 个答案:

答案 0 :(得分:1)

geocode是异步的,因此在正确设置变量setupMessageInfoWindow之前创建location变量。如果要设置某个信息窗口,可以在成功检索位置时从geocode()调用函数。例如:

function setContent(marker, content) {
    infoWin.setContent(content);
    google.maps.event.addListener(marker, 'click', function() {
        infoWin.open(map, marker);
    });
}

function geoCoding(displayname, trackerModel, setupType, marker, index){

var setupMessageInfoWindow;
var geocoder = new google.maps.Geocoder();

    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        console.log('status ok');
        console.log(results);

        if (results[1]) {

            var location = results[1].formatted_address;
            setupMessageInfoWindow = "<div height=\"300\" width=\"300\"><b>" + displayname + "</b>"
                                + " <br> Location : " + location
                                //+ " <br> Tracker id : " + userid
                                //+ " <br> imei : " + imei
                                + " <br> Tracker Type : " + trackerModel
                                //+ " <br> Mobile Number : " + 
                                //+ " <br> Location : " + location;
                                + " <br> " + setupType
                                + "</div>" ;

            setContent(marker, setupMessageInfoWindow);

        } else {
            console.log('No results found at marker ' + marker.position);
        }
    } else {
        console.log('Geocoder failed due to: ' + status);
    }
    });

}

example at jsbin。为标记设置了单击事件处理程序,显示找到的位置。