2

当我更改标记位置时,我需要知道标记的地址。

基本上我有一个方法:

function addNewMarker(latLng) {
    geocoder.geocode({'latLng': latLng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                var address = results[0].formatted_address;
                var marker = new google.maps.Marker({
                    position: latLng, 
                    map: map, 
                    draggable: true,
                    title: address,
                }); 


                google.maps.event.addListener(marker, 'dragend', function() {
                    //marker.setTitle(getGeocodeResults(marker.getPosition()));
                    marker.setTitle(***THIS IS NEW ADDRESS OF THIS MARKER***);
                });
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
}

如果我将地理编码代码提取到新方法中:

function addNewMarker(latLng){
    var address = getGeocodeResults(latLng);
    var marker = new google.maps.Marker({
        position: latLng, 
        map: map, 
        draggable: true,
        title: address,
    }); 


    google.maps.event.addListener(marker, 'dragend', function() {
        marker.setTitle(getGeocodeResults(marker.getPosition()));
    });
}

function getGeocodeResults(latLng){
    geocoder.geocode({'latLng': latLng}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                var address = results[0].formatted_address;
                return address;
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
}

我没有运气,因为这个调用是异步的。当我停止移动标记时,我需要新的地址。这个有解决办法吗?

4

1 回答 1

2

原始海报的回答

[@vale4674 将此作为对他们问题的编辑。复制在这里作为答案。]

@vale4674 已替换

marker.setTitle(getGeocodeResults(marker.getPosition()));

setTitle(marker);

并添加了这个方法:

function setTitle(marker){
    geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                var address = results[0].formatted_address;
                marker.setTitle(address);
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
}
于 2011-06-05T20:23:32.117 回答