I am playing around with the Google Maps API V3.
I want to create a series of markers on a map.
I followed a tutorial and got:
Now this code adds one marker – the first one.
I am completely new to Javascript but from my PHP knowledge, I am thinking that the reason this is not working is because all of the markers are being stored in the var named ‘m’.
I.E Number 2 replaces Number 1
My confusion however is that if this were the case, Marker 2 would be shown not Marker 1.
Could anyone postulate a possible explanation/fix?
Thanks
Editted code below:
function initialize(){
// Creating a map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(53.0123601276819, -2.44519164333635),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var m = [];
function addMarker(title, lat, lng) {
m = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: title,
clickable: true
});
}
addMarker('Home', 53.0682143712504, -2.52150736731894);
addMarker('Away', 53.0123601276819, -2.44519164333635);
}
I suspect the problem is that you’re trying to treat the object “m” as if it were an array. Declare it like this:
and see what happens. There’s no “push” function on plain objects, so that line is throwing an exception after your first marker is added.
The Javascript error console, however manifested by the browser you’re using, should always be open while you’re trying out new code. Well, maybe not always, but certainly the minute something weird happens.
edit — The call to the
.push()function in your code is fine; the problem was that you were trying to call it from something that wasn’t an array. All the function does is extend the array with the given element. Javascript arrays are somewhat weird, and the main magic has to do with how the runtime maintains the value of the “length” attribute. You can more directly extend an array like this:You can also simply use some numeric index computed in some way:
When you do that, the runtime makes sure that the “length” attribute is correctly updated, should the number used as an index be greater than the current value.
Now, back to your updated code. Now it works because you’re adding points to the map in succession and not triggering any exceptions. However, by writing:
you are no longer adding those points to an array – you’re reassigning the variable “m” to one of the points, over and over again. Change it back to “push” and — if you also change the declaration of “m” as I suggested — it will still work, and you’ll get your array populated correctly.