0

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

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I am new to using for loops.
@Jonno: Also note the float problem that Tomas pointed out. It wasn't just the for loop.
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;
3

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.

1 Comment

Actually I missed the loop bug :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.