开发者

Get markers outside geocode function

I want to be able to catch the marker object outside the geocode function and cant figure out how to.

Please help me.

The开发者_开发知识库 code:

geocoder.geocode({ address: address }, 
    function(results, status) {
        if (status == google.maps.GeocoderStatus.OK && results.length) {
            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map
                });
            }
        }
    });

Thanks in advance!


Just declare your marker variable outside the callback and assign it a value inside the callback:

var marker = null;
geocoder.geocode({ address: address }, 
    function(results, status) {
        if (status == google.maps.GeocoderStatus.OK && results.length) {
            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                map.setCenter(results[0].geometry.location);
                marker = new google.maps.Marker({
                    position: results[0].geometry.location,
                    map: map
                });
            }
        }
    }
);

Be careful though, the callback is asynchronous so you won't have anything useful in marker until the callback has been triggered.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜