Maartin
Maartin

Reputation: 91

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!

Upvotes: 0

Views: 462

Answers (1)

mu is too short
mu is too short

Reputation: 434665

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.

Upvotes: 1

Related Questions