I have a Google Map with some simple buttons added to pan to different locations.
<input id="loc0" type="button" value="Cape Sable (6)">
<input id="loc1" type="button" value="Florida Bay (3)">
Originally, I was using this code to make the buttons work:
var locations = [
new google.maps.LatLng(25.171, -81.060),
new google.maps.LatLng(25.211, -80.650)
];
$('#loc0').click(function(){
map.panTo(locations[0]);
map.setZoom(12);
});
$('#loc1').click(function(){
map.panTo(locations[1]);
map.setZoom(12);
});
This works fine, but I would love to write the click function as a loop, so I don’t have to keep using redundant code. But I can’t seem to figure it out.
I have tried the following:
for (i = 0; i < locations.length; i++) {
$('#loc'+i).click(function() {
map.panTo(locations[i]);
map.setZoom(12);
});
}
But I get an error when trying to use the buttons: panTo: latLng must be of type LatLng (122 out of range 43). I’m not well-versed with jQuery, so I suspect this is something simple I don’t understand yet. Any hints?
Nothing immediately pops out as being wrong, this looks like it should be correct.
Can you put up a JS Fiddle demonstrating the problem at all?
My first hunch would be that your code is correct but somehow you are getting invalid data in the locations array.
If that’s not the case, I wonder if it’s an issue with enclosure and the variables. Something like this may help:
I first made the declaration of the “i” variable specific to each loop, so there’s no way that it can get overwritten improperly somewhere else. I also added the additional “fail safe” of defining the “location” variable in each iteration of the loop so that you can ensure the correct variable makes it to the click function.
EDIT
Definitely an issue with enclosure and the variable content when accessed via click. Something else you could try is this:
1: Add a common class to each button, something like class=”locButton”
2: Try this: