views:

55

answers:

3

Hello

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);



}
+2  A: 
Pointy
Thanks !The premise (as explained by the tut) is that you need to add the markers to an array so you can loop through them and remove them each if you want to.I have editted my code above. It works perfectly.Just for my info. Could you perhaps elaborate on what 'push' is, and why can I add a point to my array 'm' by simply writing var m = ''.In PHP that would REPLACE m..Thanks
Thomas Clowes
I'll extend my answer.
Pointy
A: 

m is scoped to the function it's in so that is not the problem. My guess is that you're getting an error when you call marker.push(m). marker is an object and does not have a push method. Make it an array (var marker = []). Since it is breaking on that line, it never gets to execute the second call to the function. But it has already added the marker on the screen, which is why you see it.

geowa4
A: 

The variable m is in the scope of initialize like the function addMarker.

Each time you set m (which is an array at first) to Marker object, you store a reference to the newly created marker object. That may be the problem as you mentioned.

Instead of setting m to Marker object, use push (a method to add an object to an array) like the following:

m.push(new google.maps.Marker({
  position: new google.maps.LatLng(lat, lng),
  map: map,
  title: title,  
  clickable: true 
});). 
Zafer