Question

I'm a javascript noob, so help me someone!

I made an array with several cities in it:

var cities = [
    ['City 1', 59.326294118560725, 17.98754555000005],
    ['City 2', 57.70231523439743, 11.893682500000068],
    ['City 3', 62.39591678065696, 17.292328450000014],
    ['City 4', 59.89396160257896, 10.785116549999998],
    ['City 5', 57.10938174202619, 12.25817589999997]
    ];

I want to be able to pick two or more cities by name and draw a line between them.

I found this code:

var route = new google.maps.Polyline({
  path: something
  strokeColor: "#FF0000",
  strokeOpacity: 0.8,
  strokeWeight: 2,
  map: map
});

How do I modify it so that I can pick a city or two from my array, and use the name of the cities as reference?

Was it helpful?

Solution

var cities = [
    ['City 1', 59.326294118560725, 17.98754555000005],
    ['City 2', 57.70231523439743, 11.893682500000068],
    ['City 3', 62.39591678065696, 17.292328450000014],
    ['City 4', 59.89396160257896, 10.785116549999998],
    ['City 5', 57.10938174202619, 12.25817589999997]
    ];

var something = [];
for (var i=0; i<cities.length; i++) {
  if ((firstCity == cities[i][0]) || (secondCity == cities[i][0])) {
    // assume coordinates are Latitude, Longitude
    something.push(new google.maps.LatLng(cities[i][1],cities[i][2]));
  }
}
var route = new google.maps.Polyline({
  path: something,
  strokeColor: "#FF0000",
  strokeOpacity: 0.8,
  strokeWeight: 2,
  map: map
});

working example with all the points

working example with 2 cities from the array

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top