1

I'm pulling in the below json data from a database using ajax.

{"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]}

How would I got about iterating over it to get lat/long pairs to plot on a map?

user1542125
  • 593
  • 6
  • 16

4 Answers4

3

Assign the JSON data to a variable, and loop through the route object like below:

var j = {"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]}

for(i=0; i<=j.route.length; i++){
  var thisRoute = j.route[i];   
}
Curtis
  • 101,612
  • 66
  • 270
  • 352
  • Remark: This is simply iterating over a javascript array, not JSON data. But that probably is what @user1542125 wanted to do. – Pedro Affonso Aug 27 '15 at 12:21
1

Give it a try:

var j = {"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]};
for(var i= 0,len=j.route.length; i<len; i++){
  var lat = j.route[i].latitude;
  var long = j.route[i].longitude;
  console.log(lat+' '+long);
}
Rayon
  • 36,219
  • 4
  • 49
  • 76
0
var o = {"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]};
var i = 0;
var lat, long;
var len=o.route.length; 
for(i,i<len; i++){
  lat = o.route[i].latitude;
  long = o.route[i].longitude;
  console.log(lat+' '+long);
}
graham o'donnel
  • 385
  • 2
  • 5
  • 18
0

Here's a full implementation of what you're trying to achieve:

JSFIddle with a map

  function createMarker(options) {
        var marker = new google.maps.Marker(options);

        return marker;
    }

    for (i = 0; i < data.route.length; i++) {
        createMarker({
            position: new google.maps.LatLng(data.route[i].latitude, data.route[i].longitude),
            map: map

        });
Hristo Georgiev
  • 2,499
  • 1
  • 16
  • 23