-1

I can't succeed to draw on my Google map a polyline with a loop. One of my coworker fill different coordinates separate by a "/". I'd like to split it and make a loop in Maps.

Here is what i want to have at the end :

  var flightPlanCoordinates = [
     new google.maps.LatLng(37.772323, -122.214897),
     new google.maps.LatLng(21.291982, -157.821856),
     new google.maps.LatLng(-18.142599, 178.431),
  ];

Here is what I have :

37.772323, -122.214897/21.291982, -157.821856/-18.142599, 178.431

Here is my code so far :

var coord_itineraire = '37.772323, -122.214897/21.291982, -157.821856/-18.142599, 178.431';
cut_itineraire = coord_itineraire.split("/");
var flightPlanCoordinates = [
$.each(cut_itineraire, function(index, valeur_coord) {
      return ("new google.maps.LatLng("+valeur_coord+"), ");
})
];

But here is the problem my console shows :

InvalidValueError: at index 0: not a LatLng or LatLngLiteral: in property lat: not a number

Infos : To make it simple here I just put the numbers, normally "coord_itineraire" is a variable which take the value recorded in the BO of my website. It could be only 3 point like here, or 20, it's never fixed.

I tried a parseFloat on my "valeur_coord" but the second number of the row is erased.

Any ideas ?

Thanks !!

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
  • possible duplicate of [google maps move marker with lat/lng from ajax success returned data](http://stackoverflow.com/questions/17654989/google-maps-move-marker-with-lat-lng-from-ajax-success-returned-data) – geocodezip Apr 15 '15 at 09:46

2 Answers2

1

Try this one:

        var coord_itineraire = '37.772323, -122.214897/21.291982, -157.821856/-18.142599, 178.431';
        var coord_itineraire_arr = coord_itineraire.split("/");
        var flightPlanCoordinates = [];

        for ( var key in coord_itineraire_arr ) {
            var temp = coord_itineraire_arr[key].split(",");
            flightPlanCoordinates.push( new google.maps.LatLng( parseFloat( temp[0] ) , parseFloat( temp[1] ) ) );
        }

This will result to:

 var flightPlanCoordinates = [
     new google.maps.LatLng(37.772323, -122.214897),
     new google.maps.LatLng(21.291982, -157.821856),
     new google.maps.LatLng(-18.142599, 178.431),
  ];
Eddie
  • 26,593
  • 6
  • 36
  • 58
0

Your are building a string, not an array of LatLng object.

Please check this code :

var coord_itineraire = "37.772323, -122.214897/21.291982, -157.821856/-18.142599, 178.431";
var cut_itineraire = coord_itineraire.split("/");

//Empty array
var flightPlanCoordinates = [];

$.each(cut_itineraire, function(index, valeur_coord) {
  var coords = valeur_coord.split(', ');
  var lat = parseFloat(coords[0]);
  var lng = parseFloat(coords[1])
  flightPlanCoordinates.push(new google.maps.LatLng(lat,lng))
});

console.log(flightPlanCoordinates)

Don't hesitate to ask a question if you have problem

jmgross
  • 2,306
  • 1
  • 20
  • 24