Skip to content Skip to sidebar Skip to footer

Multiple Markers Not Showing In Google Maps With Javascript Api V3?

I'd like to know how to put multiple markers for Google Maps using Javascript API v3. I tried the solution posted here, but it does not work for me for some reason: var directionDi

Solution 1:

This question is already a few months old, but I noticed that it remained unanswered. I guess the OP already found a way through this, but let me attempt an answer for the sake of completeness.


I can spot a few major problems in your code above:

  1. First of all, you are trying to pass the properties array to the setMarkers() function, before properties is defined. Therefore setMarkers() will receive undefined for the second argument, which is why nothing is showing on your map.

  2. Then, you are having a very common closure problem in that for in loop. Variables enclosed in a closure share the same single environment, so by the time the click callback from the addListener is called, the loop will have run its course and the i variable will be left pointing to the last value it had when loop ended.

  3. In addition, you have a dangling comma in the array literal, which can cause a syntax error in some browsers.


To fix the first problem, simply define the properties array before calling setMarkers():

var properties = [
  ['106 Ft Washington Avenue',40.8388485,-73.9436015,'Mjg4'],
];

setMarkers(map, properties);

You can then solve the closure problem with even more closures, using a function factory:

functionmakeClickCallback(buildings, i) {  
   returnfunction() {  
      window.location = ('detail?b=' + buildings[i][3]);
   };  
} 

for (var i in buildings) {
   // ...

   google.maps.event.addListener(marker, 'click', 
                                 makeClickCallback(buildings, i);
}

This can be quite a tricky topic, if you are not familiar with how closures work. You may to check out the following Mozilla article for a brief introduction:

Then you may want to make sure to remove the dangling comma in your array literal:

var properties = [
  ['106 Ft Washington Avenue',40.8388485,-73.9436015,'Mjg4']  // no comma
];

In addition, note that since there is just one element in your properties array, you will only get one marker on the map. I'm not sure if the other elements were removed for the sake of this example, but if it wasn't, simply add more locations like this:

var properties = [
  ['106 Ft Washington Avenue',40.8388485,-73.9436015,'Mjg4'],
  ['Another Location',50.505050,-75.505050,'Mjg5']
];

Post a Comment for "Multiple Markers Not Showing In Google Maps With Javascript Api V3?"