Multiple Markers Not Showing In Google Maps With Javascript Api V3?
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:
First of all, you are trying to pass the
properties
array to thesetMarkers()
function, beforeproperties
is defined. ThereforesetMarkers()
will receiveundefined
for the second argument, which is why nothing is showing on your map.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 theclick
callback from theaddListener
is called, the loop will have run its course and thei
variable will be left pointing to the last value it had when loop ended.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?"