Fredovsky
Fredovsky

Reputation: 387

Javascript array from JSON not working

I quite don't understand what's going on here, probably due to my lack of knowledge in JSON.

I have a php script returning a JSON into an ajax query (with dataType:'json'). Here is what I end up with in the javascript :

 alert(JSON.stringify(data.polylines[i]));

I guess data.polylines[i] is already an object as I need JSON.stringify() function to show it properly. This alert shows :

 [["40.632099151611","8.2907695770263"],["57.774700164794","11.870400428772"]]

which is exactly the array I need for the variable path in the following script (drawing a line in Google Maps Api):

map.drawPolyline({
     path: path,
     strokeColor: '#131540',
     strokeOpacity: 0.6,
     strokeWeight: 6
});

when I do :

 var path = data.polylines[i];
 map.drawPolyline({
     path: path,
     strokeColor: '#131540',
     strokeOpacity: 0.6,
     strokeWeight: 6
});

... it's not working, but when I do :

var path = [["40.632099151611","8.2907695770263"],["57.774700164794","11.870400428772"]];
 map.drawPolyline({
     path: path,
     strokeColor: '#131540',
     strokeOpacity: 0.6,
     strokeWeight: 6
});

it works. I can't figure out why one works and not the other one, as the 'alert' test shows exactly the same value...

Upvotes: 1

Views: 107

Answers (2)

Lars Anundskås
Lars Anundskås

Reputation: 1355

Path is a Collection of two or more points and each Point is an array of two coords. When you use polylines[i] you Are trying to Draw a path with one point, which Will fail

Upvotes: 0

Fredovsky
Fredovsky

Reputation: 387

Sorry, my mistake was in the loop condition as pointed out by @Pointy. It's working now.

Upvotes: 1

Related Questions