0

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!

1
  • 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 */} Commented Jun 30, 2013 at 22:04

1 Answer 1

1

$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.)

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

1 Comment

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) { ... });

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.