Nitish Nitish - 5 months ago 117
AngularJS Question

Angularjs google maps API drawing polyline

Following code snippet gives me output as (basically on each click a new marker is added and I am fetching it's lat and long values):

0: Latitude: 40.207196906764054 Longitude: -99.68994140625
1: Latitude: 40.202477129519124 Longitude: -99.60823059082031


Code snippet:

$scope.map.markers.push(marker);
// console.log($scope.map.markers);

for (var item in $scope.map.markers) {
console.log(item +': '+ "Latitude: " + $scope.map.markers[item].coords.latitude + " " + "Longitude: " + $scope.map.markers[item].coords.longitude);
}


To draw a polyline I need array in such format:

var flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];


I basically want to draw lines along these markers. How can I construct such a structure inside my for loop to add these lat and long values which I can feed to 'Path' variable for Polilines?

Answer

You should be able to loop trough the markers and add their coordinates into an empty array (provided the for cycle you shown works):

var myCoordinates = [];
for (var item in $scope.map.markers) {
     myCoordinates.push({lat: $scope.map.markers[item].coords.latitude, lng: $scope.map.markers[item].coords.longitude});
}

and then use myCoordinates array the same way you would use flightPlanCoordinates to create a polyline, e.g.:

var myPolyline = new google.maps.Polyline({
    path: myCoordinates,
    geodesic: true,
    strokeColor: '#FF0000',
    strokeOpacity: 1.0,
    strokeWeight: 2,
    map: map
});
Comments