views:

58

answers:

2

Hi

I am trying to add markers onto a google map to identify the states using:

function initialize() {
 var map = new GMap2(document.getElementById("map_canvas"));
 map.setCenter(new GLatLng(-25.641526,134.472656), 4);
 map.setMapType(G_NORMAL_MAP);
 map.setUIToDefault();

var states =["-35.083236,138.503909","-24.607069,144.667969","-18.229351,133.417969","-24.686952,123.574219","-32.398516,146.953125","-35.46067,149.150391","-37.020098,143.701172","-42.682435,146.733398"]; 
  for (i = 0; i == states.length; i++) {
  var point = new GLatLng(parseFloat(states[i]));
  map.addOverlay(new GMarker(point));
  }
}

But no markers come up when I load the map (which loads fine, properly centered and of the correct map type). What am I doing wrong here?

EDIT: I changed it to this and now it works:

var lats =[-35.083236,-24.607069,-18.229351,-24.686952,-32.398516,-35.46067,-37.020098,-42.682435];
var longs =[138.503909,144.667969,133.417969,123.574219,146.953125,149.150391,143.701172,146.733398];

for (i = 0; i <= lats.length; i++) {
var point = new GLatLng(lats[i],longs[i]);
map.addOverlay(new GMarker(point));
+5  A: 

It looks like a typo in your for loop. Try it as follows:

for (i = 0; i < states.length; i++) {

Also note the float problem that Tomas pointed out.

Daniel Vassallo
Thanks, I am new to using `for` loops.
Jonno_FTW
@Jonno: Also note the float problem that Tomas pointed out. It wasn't just the for loop.
Daniel Vassallo
i is referring to some global variable right now. if that's not on purpose, its better to declare it in the loop itself - `for(var i = 0; `
Anurag
+3  A: 

You are parsing a single float value and try to use that as both latitude and longitude.

This ...

var point = new GLatLng(parseFloat("-35.083236,138.503909"));

won't parse two distinct float values and pass them to the GLatLng. One solution is to split the values in the array:

function initialize() {
 var map = new GMap2(document.getElementById("map_canvas"));
 map.setCenter(new GLatLng(-25.641526,134.472656), 4);
 map.setMapType(G_NORMAL_MAP);
 map.setUIToDefault();

 var states =[-35.083236, 138.503909, -24.607069, 144.667969, ...
 for (i = 0; i < states.length; i+=2) {
   var point = new GLatLng(states[i], states[i+1]);
   map.addOverlay(new GMarker(point));
}

}

Also note that your for loop was incorrect as Daniel pointed out.

Tomas
+1 for seeing beyond the for loop bug :)
Daniel Vassallo
Actually I missed the loop bug :)
Tomas