1

I have this type of data in an object in my project.

{
    "name": "Travel",
    "map": [
        {
            "name": "Montreal",
            "lat": "45.498649",
            "lng": "-73.492729"
        },
        {
            "name": "Brossard",
            "lat": "45.466667",
            "lng": "-73.450000"
        }
    ]
}

How can I create this type of structure code to show my Google Map ?

var locations = [
  {
    name: "Montreal",
    latlng: new google.maps.LatLng(45.498649, -73.492729)
  },
  {
    name: "Brossard",
    latlng: new google.maps.LatLng(45.466667, -73.450000)
  }
];

Thanks a lot.

2 Answers 2

3

It's more simple if you use 'forEach':

json.map.forEach(function(val){
    locations.push({
        name: val.name, 
        latlng: new google.maps.LatLng(val.lat, val.lng)
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

It do not conserves my initial wanted structure with the new google.maps.LatLng part.
2

You were close:

for (i = 0; i < dmap.length; i++) {
    locations.push({name: dmap[i].name, lat: dmap[i].lat,lng:dmap[i].lng});
}

Another way is doing it with Array.map:

dmap.map(function(item){
    return {name: item.name, lat: item.lat, lng:item.lng};
});

JSFIDDLE Example.

Since You Editted this is the relevant code:

for (i = 0; i < dmap.length; i++) {
    locations.push({name: val.name, 
        latlng: new google.maps.LatLng(val.lat, val.lng)
    });
}

Or

dmap.map(function(item){
    return {name: val.name, 
        latlng: new google.maps.LatLng(val.lat, val.lng)
    };
});

3 Comments

Good but how can I include the new google.maps.LatLng part ?
thats an external class that probally comes with adding the google maps js file.
No I really need this part, if not, it will not work.

Your Answer

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