Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm building an app using AngularJS and I am trying to plot locations on a google map. I have a JSON response that looks like this:

 locations: [{ 
    id: 123
    latlng:  { 
        lat: 56.3
        lon: -2.1
        } 
    name: TestName
    }]

The directive I'm using (angular-google-maps) requires the markers to be in the below format. What I would like to do is to create a new array containing only the lat and lng values, that looks like this. I also need to rename the lat and lng to longitude and latitude:

markers: [ {
        latitude: 45,
        longitude: -74
    },{
        latitude: 46,
        longitude: -75  
    }]

I'm new to programming, especially in javascript. I tried to see if I can access the latlng object in the JSON response, but get undefined. Here is what that looks like:

for (var latlng in $scope.locations) {
        if ($scope.locations.hasOwnProperty(latlng))
        {
            var latitude = $scope.locations[latlng].lat;
        }
        console.log(latitude);
    }

Thanks in advance!

share|improve this question
    
It's better to iterate over indices rather than keys if you have an Array. var i, latlng; for (i = 0; i < $scope.locations.length; ++i) {latlng = $scope.locations[i]; /* etc */} –  Paul S. Jun 30 '13 at 22:04
add comment

1 Answer

up vote 1 down vote accepted

$scope.locations[latlng] gets you to the object containing the latlng key, not the object referred to by that key. Since the iteration variable is an index into the array, you'll find it less confusing to use a name that reflects this, e.g., i instead of latlng:

for (var i in $scope.locations) {
    …
    var latitude = $scope.locations[i].latlng.lat;
    …
}

In most JavaScript implementations, you have another option:

$scope.locations.forEach(function(location) {
    …
    var latitude = location.latlng.lat;
    …
});

(Also note @rtcherry's comment.)

share|improve this answer
1  
I would suggesting using either angular.forEach or a library like underscore or lodash to provide utility functions such as forEach. Array.forEach was introduced with JavaScript 1.6, which is not supported by some legacy browsers. Example: angular.forEach($scope.locations, function(location) { ... }); –  rtcherry Jun 30 '13 at 23:42
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.