开发者

Get markers outside geocode function

开发者 https://www.devze.com 2023-03-10 00:14 出处:网络
I want to be able to catch the marker object outside the geocode function and cant figure out how to.

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

精彩评论

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