首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >同步调用Geocoding方法

同步调用Geocoding方法
EN

Stack Overflow用户
提问于 2011-01-31 22:31:24
回答 1查看 5.1K关注 0票数 2

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

基本上我有一个方法:

代码语言:javascript
复制
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);
        }
    });
}

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

代码语言:javascript
复制
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);
        }
    });
}

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-05 20:23:32

答:原版海报

@ edit 4674将此作为对他们问题的编辑。抄袭这里作为答案。

@vale4674 4674取代

代码语言:javascript
复制
marker.setTitle(getGeocodeResults(marker.getPosition()));

使用

代码语言:javascript
复制
setTitle(marker);

并添加了此方法:

代码语言:javascript
复制
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);
        }
    });
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4856881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档