Xeen
Xeen

Reputation: 7003

Google maps api marker is not defined error

I need to place multiple markers on the map with the ability to click on them. That should then fire up a certain JS within my website and for that I'm using the following code:

function initialize() {
        geocoder = new google.maps.Geocoder();
        var mapCanvas = document.getElementById('map_canvas');
        var mapOptions = {
          center: new google.maps.LatLng(64.113598, -21.8569031),
          zoom: 12,
          scrollwheel: false,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(mapCanvas, mapOptions)

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

        getAddress("some address here");

      }
      google.maps.event.addListener(marker, 'click', function() {
        map.setZoom(8);
      });
      google.maps.event.addDomListener(window, 'load', initialize);

But this gives me Uncaught ReferenceError: marker is not defined error. What am I doing wrong?

Upvotes: 0

Views: 12502

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

You have defined the var marker inside the function getAddress, and therefore this variable will only be available within this scope. Please move the variable definition outside of getAddress like this:

var marker;

function initialize() {
    // ...

    function getAddress (address) {
        geocoder.geocode( { 'address': address}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                marker = new google.maps.Marker({
                    map: map,
                   position: results[0].geometry.location
                });
            } else {
                return;
            }
        });
    }

    getAddress("some address here");
}

Upvotes: 2

Related Questions