开发者

Call Google Geocoding API method synchronouslly

I need to know marker's address when I change markers postition.

Basically I have a method:

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);
        }
    });
}

If I extract geocoding code into new method:

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);
        }
    });
}

I have n开发者_运维问答o luck because this call is asynchronous. And I need that new addres when I stop moving marker. Is there a solution to this one?


ANSWER by Original Poster

[@vale4674 put this as an edit to their question. Copying here as an answer.]

@vale4674 replaced

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

with

setTitle(marker);

and added this method:

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);
        }
    });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜