0

I am plotting addresses and having an issue with the infowindow showing the right content everytime. Sometimes it shows the right content in the infowindow when clicked and sometimes it shows the wrong information for that map pin.

var map = null;
var markersArray = [];
var markers = [];
var openedInfoWindow ="";
var geocoder = new google.maps.Geocoder();

function initialize() {

    var mapOptions = {

     zoom: 8,
      center: new google.maps.LatLng(64.85599578876611, -147.83363628361917),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("mapInfoManual"),
        mapOptions);

    google.maps.event.addListener(map, 'zoom_changed', function() {
        zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
            if (this.getZoom() > 20) // Change max/min zoom here
                this.setZoom(18);

            google.maps.event.removeListener(zoomChangeBoundsListener);
        });
});
    addMarker();
  }

function addMarker() {

        var bounds = new google.maps.LatLngBounds();
        for(i=0; i<markersArray.length; i++)
        {
            CodeAddress(markersArray[i]['address']);
            var mytitle = (markersArray[i]['title']);
            var myaddress = (markersArray[i]['displayaddress']);
            var linkurl = (markersArray[i]['linkurl']);

        }
        setTimeout(function()
        {

          for(i=0; i<markers.length; i++)
          {
              var point = new google.maps.LatLng(markers[i]['lat'], markers[i]['lng']);

              var marker = new google.maps.Marker({
                  position: point,
                  map: map
              });
              bounds.extend(point);
              var infoWindowContent = "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>"+ mytitle +"</div><div style='margin-bottom:5px;'>" + myaddress + "</div><div><a href='" + linkurl + "/'>More Details</a></div></div>";

              openInfoWindow(marker,infoWindowContent)      

          }
          map.fitBounds(bounds);

          },2500);

}

// Address To Marker
function CodeAddress(address)
{

    geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        lat = results[0].geometry.location.lat();
        lng = results[0].geometry.location.lng();
        markers.push({
                        'lat':lat,
                        'lng':lng,
                        'address':address
                    }); 
    } 

});   
}
//Info Window
function openInfoWindow(marker,infoWindowContent)
{   
    var infowindow = new google.maps.InfoWindow({
        content: '<div class="cityMapInfoPop">'+infoWindowContent+'</div>'          
    });

    google.maps.event.addListener(marker, 'click', function() {

        if(openedInfoWindow !="")
        {
            openedInfoWindow.close()
        }

        infowindow.open(map,marker);
        openedInfoWindow = infowindow;
    });
}

Variables that I pass in:

 <script type="application/javascript">
     markersArray.push({
    "title":'<?php echo $maptitle;?>',
    "address":'<?php echo $markerAddress;?>',
    "displayaddress":'<?php echo $displayAddress;?>',
    "linkurl":'<?php echo $addressUrl;?>'
     });    
</script>
kelsheikh
  • 1,278
  • 3
  • 17
  • 37
  • What does your array look like? Please provide a [Minimal, Complete, Tested and Readable example](http://stackoverflow.com/help/mcve) that demonstrates the issue. – geocodezip May 19 '15 at 21:27
  • I push variables that include an address, title, and other info into the function above called 'addMarker' that I loop through, geocode, and plot. When they are plotted, the infowindow doesn't display the correct information for that map pin. – kelsheikh May 19 '15 at 21:59

2 Answers2

0

Since you didn't provide a working JSFiddle, it was rather difficult to figure out what your problem is. That said, you can look at this JSFiddle that I made for you to review what I'm doing, vs what you're doing.

Why are you using setTimeout() to place your markers? Also, you may have better results if you create an individual infoWindow per marker, instead of using a "global" infoWindow (which is what it looks like you're doing).

If you edit your post to add a working example of your problem, I can help further.

window.places = [{
  title: "foo",
  address: {
    lat: parseFloat("64.85599578876611"),
    lng: parseFloat("-147.83363628361917")
  },
  displayAddress: "101 BLVD",
  linkURL: "google.com"
}, {
  title: "bar",
  address: {
    lat: parseFloat("62.85599578876611"),
    lng: parseFloat("-147.83363628361917")
  },
  displayAddress: "202 BLVD",
  linkURL: "images.google.com"
}, ]

function initialize() {
  "use strict";
  var myLatlng = new google.maps.LatLng(window.places[0].address.lat, window.places[0].address.lng),
    mapOptions = {
      zoom: 4,
      center: myLatlng
    };

  window.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  $.each(window.places, function(i) {

    var infowindow = new google.maps.InfoWindow({
        content: "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>" + window.places[i].title + "</div><div style='margin-bottom:5px;'>" + window.places[i].displayAddress + "</div><div><a href='" + window.places[i].linkURL + "/'>More Details</a></div></div>"
      }),
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(window.places[i].address.lat, window.places[i].address.lng),
        map: window.map,
        title: window.places[i].title
      });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(window.map, marker);
    });

  });
}

google.maps.event.addDomListener(window, 'load', initialize);
      html,
      body,
      #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<div id="map-canvas"></div>
kneeki
  • 2,444
  • 4
  • 17
  • 27
0

Your issue is that geocoding is asynchronous. You loop through calling the geocoder on all your addresses, but the order the results are returned in is not predictable.

  1. use function closure to associate the marker with the infowindow
  2. use function closure to associate the address with the marker
  3. use the results of the geocoder inside its callback function.

Note that if you have more that approximately 10 markers in your array you will run into the quota/rate limit of the geocoder.

proof of concept fiddle

code snippet:

var map = null;
var markersArray = [];
var markers = [];
var openedInfoWindow = "";
var geocoder = new google.maps.Geocoder();
var bounds = new google.maps.LatLngBounds();

markersArray.push({
  "title": 'marker 0',
  "address": 'New York,NY',
  "displayaddress": 'New York, NY',
  "linkurl": 'http://google.com'
});
markersArray.push({
  "title": 'marker 1',
  "address": 'Boston, MA',
  "displayaddress": 'Boston, MA',
  "linkurl": 'http://yahoo.com'
});
markersArray.push({
  "title": 'marker 2',
  "address": 'Newark,NJ',
  "displayaddress": 'Newark, NJ',
  "linkurl": 'http://mapquest.com'
});
google.maps.event.addDomListener(window, "load", initialize);

function initialize() {

  var mapOptions = {

    zoom: 8,
    center: new google.maps.LatLng(64.85599578876611, -147.83363628361917),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("mapInfoManual"),
    mapOptions);

  google.maps.event.addListener(map, 'zoom_changed', function() {
    zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function(event) {
      if (this.getZoom() > 20) // Change max/min zoom here
        this.setZoom(18);

      google.maps.event.removeListener(zoomChangeBoundsListener);
    });
  });
  addMarker();
}

function addMarker() {

  var bounds = new google.maps.LatLngBounds();
  for (i = 0; i < markersArray.length; i++) {
    CodeAddress(markersArray[i]);
  }
}

// Address To Marker
function CodeAddress(markerEntry) {
    var mytitle = (markerEntry['title']);
    var myaddress = (markerEntry['displayaddress']);
    var linkurl = (markerEntry['linkurl']);
    geocoder.geocode({
      'address': markerEntry['address']
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var marker = new google.maps.Marker({
          position: results[0].geometry.location,
          map: map
        });
        bounds.extend(marker.getPosition());
        var infoWindowContent = "<div style='padding:2px;'><div style='margin-bottom:5px;font-weight:700;color:#033551;'>" + mytitle + "</div><div style='margin-bottom:5px;'>" + myaddress + "</div><div><a href='" + linkurl + "/'>More Details</a></div></div>";

        openInfoWindow(marker, infoWindowContent);
        markers.push(marker);
        map.fitBounds(bounds);
      } else {
        alert("geocode failed: " + status);
      }
    });
  }
  //Info Window

function openInfoWindow(marker, infoWindowContent) {
  var infowindow = new google.maps.InfoWindow({
    content: '<div class="cityMapInfoPop">' + infoWindowContent + '</div>'
  });

  google.maps.event.addListener(marker, 'click', function() {

    if (openedInfoWindow != "") {
      openedInfoWindow.close();
    }

    infowindow.open(map, marker);
    openedInfoWindow = infowindow;
  });
}
html,
body,
#mapInfoManual {
  height: 500px;
  width: 500px;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?ext=.js"></script>
<div id="mapInfoManual" style="border: 2px solid #3872ac;"></div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • This is amazing! This worked perfectly. Thank you so much. I guess I can throttle my geocode requests with setTimeout or something. Thanks again!! – kelsheikh May 20 '15 at 11:32
  • http://stackoverflow.com/questions/11792916/over-query-limit-in-google-maps-api-v3-how-do-i-pause-delay-in-javascript-to-sl – geocodezip May 20 '15 at 11:45