AJSwift
AJSwift

Reputation: 719

Unable to pop up InfoWindow on clicking a marker google map

What am I doing wrong?? I am basically trying to pop open an info window, a very simple one, on clicking the markers.. The markers are showing up fine but the markers click event is not being responded..I am pretty sure the InfoWindow code is not in the right spot .. the addresses for correspoding markers are being fed in by jquery for each..

var geocoder;
var map;    
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(39.88445,-86.11084);
var myOptions = {
  zoom: 10,
  center: latlng,
  mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
  myOptions);


$('span.Address .ms-rtestate-field').each(function(index) {
    var addy = $(this).text();
    geocoder.geocode( { 'address': addy}, 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,
            title:addy
        });
        }else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });


    // Creating an InfoWindow          
    var infowindow = new google.maps.InfoWindow({
    content: 'Hello world'
   });

    // Adding a click event to the marker
    google.maps.event.addListener(marker, 'click', function() {
    return function(){
     // Opening the InfoWindow
    infowindow.open(map, marker);
    }
   });

});

Upvotes: 0

Views: 2726

Answers (1)

Bryan Weaver
Bryan Weaver

Reputation: 4473

You only need one instance of the infowindow and then change the content during the onclick event using the setContent() method. Also, you should put the event handler in the geocode callback function to make sure it gets connected when the geocoder completes.

Try this:

// Creating an InfoWindow          
var infowindow = new google.maps.InfoWindow({});

$('span.Address .ms-rtestate-field').each(function(index) {
    var addy = $(this).text();
    geocoder.geocode( { 'address': addy}, 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,
                title:addy
            });

            // Adding a click event to the marker
            google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent("Hello World!");
                infowindow.open(map, this);
            }); 

        }else {
            alert("Geocode was not successful for the following reason: "
                  + status);
        }
    });

});

Upvotes: 1

Related Questions