Carl.UmpaLumpa
Carl.UmpaLumpa

Reputation: 43

Google maps infowindow share same lat/long

I was helped out by an SO member with the following code which allows me to use multiple markers from a PHP array and plot them on a map:

    for (i = 0; i < locations.length; i++) 
    { 

  marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][0], locations[i][1]),
    map: map
   });


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

      infowindow.setContent(locations[i][2]);
      infowindow.open(map, marker);
    }
  })(marker, i));
    }

So that code is grabbing my array and putting my markers on the map and in the infowindow, printing out the customer name. I quickly came across an issue however. If a customer share's the same lat/long (they're derived from postcode), only one of the customers appear - e.g. Customer1 at LN1 7HQ and Customer2 at LN1 7HQ, only customer 1 will appear in the info window. A few solutions I found include clustering markers and offsetting them - but what I would like is the have 1 infowindow for each postcode and then list the customers located there in the window. I haven't found a way to do it but would assume it will involve altering the For loop below and adding something like "If lat, long === lat, long, then locations[i][2] ++ ..." but I'm just about grasping PHP and javascript is still new to me. Any help would be much appreciated.

Upvotes: 2

Views: 762

Answers (1)

Anto Jurković
Anto Jurković

Reputation: 11258

One possible solution: track created markers using array

var markers = [];

with information about location indexes using following object:

function MarkerInfo(marker, idx) {
    this.marker    = marker;
    this.locations = [idx];
}

There are two loops. The 1st loop build array of MarkerInfo with marker and list of indexes from locations array. The 2nd loop prepares content string for infowindow and creates listeners.

See example at jsbin.

Note: for the future changes: solution won't work properly if you change locations array with information about customers between those two loops.

Upvotes: 0

Related Questions