Using Google Maps to generate a polyline from an array

I have an array filled with various coordinates and data entries. My goal is to create a polyline that connects all these coordinate points within the array. While I can successfully place markers and infowindows, I am encountering difficulty in generating the polyline.

I intend to iterate through the array using a loop, as I plan to utilize the same method for additional sets of coordinates in the future.

Below is the code snippet:

var places = [
['New Delhi', 28.6139587, 77.208684],
['Amritsar', 31.643628, 74.859624],
['Srinagar', 34.09, 74.79],
['Kargil', 34.55, 76.133333],
['Alchi', 34.2334, 77.1625],
['Leh', 34.145397, 77.567614]
];

for (var i = 0; i < places.length; i++){
    var coords = new google.maps.LatLng(places[i][1], places[i][2]);
    poly.push(coords);
}

console.log(poly);

var Itinerary = new google.maps.Polyline({
    path: poly,
    geodesic: true,
    strokeColor: '#ffd500',
    strokeOpacity: 1.0,
    strokeWeight: 5
});

Itinerary.setMap(map);

Answer №1

You've encountered a JavaScript error in your code:

Uncaught ReferenceError: poly is not defined
.

Here is a link to a working fiddle

Here is the code snippet:

var geocoder;
var map;
var poly = []; // I added this 

function initialize() {
  map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

  var places = [
    ['New Delhi', 28.6139587, 77.208684],
    ['Amritsar', 31.643628, 74.859624],
    ['Srinagar', 34.09, 74.79],
    ['Kargil', 34.55, 76.133333],
    ['Alchi', 34.2334, 77.1625],
    ['Leh', 34.145397, 77.567614]
  ];

  var bounds = new google.maps.LatLngBounds();
  for (c = 0; c < places.length; c++) {
    var coords = new google.maps.LatLng(places[c][1], places[c][2])
    poly.push(coords);
    bounds.extend(coords);
  }

  console.log(poly);

  var Itinerary = new google.maps.Polyline({
    path: poly,
    geodesic: true,
    strokeColor: '#ffd500',
    strokeOpacity: 1.0,
    strokeWeight: 5
  });

  Itinerary.setMap(map);
  map.fitBounds(bounds);

}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map_canvas" style="border: 2px solid #3872ac;"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing user experience with dynamic search results: JQuery AutoComplete powered by XML

As a newcomer to AJAX, JavaScript, and the web, I'm struggling with understanding this concept. When using JQuery's autocomplete feature with a small flat file of limited items (suggestions.xml), everything works perfectly. However, when switchin ...

JavaScript allows for the insertion of values into either a textbox or dropdown menu

Is there a way to restrict the client from inserting both of these fields: either selecting from a textbox (selected Column) or choosing a value from a dropdown menu (selected Column), but only one field is allowed in a gridview? <asp:GridView ID="gvMe ...

Pass the ActiveRecord object retrieved in the success of the ajax call in Rails as a parameter to another subsequent

Imagine this scenario: I have a view named "Dashboard" featuring a basic form and a button labeled "Draw Graphs". The goal is to trigger two ajax requests upon clicking the button, fetching the required data from the database for creating two distinct grap ...

The step-by-step guide for replacing the extJs Controller component

I have developed a versatile component that is being utilized across different products. In this case, I have a generic window and window controller which I am customizing to fit our specific product requirements. This is my generic window: Ext.define(&a ...

Managing AJAX Errors in PHPAJAX error handling tips for developers

My current code is only set up to display a general error message when an error occurs during execution. I want to improve it by returning specific error messages for different scenarios. However, I have not been able to find satisfactory solutions in my s ...

Loop through each row in the Datatable and access the details or child

I need to iterate through each child row in a datatable. For example, if I have AJAX data structured like this: "data": [ { "date" : "1/17/2016", "supplier" : "supplier1", "total" : "$10", "payment" : "Cash", "product" : Array[2] ...

Different ways to enhance max-http-header-size in Vue application

After being redirected from another application, I am unable to open the page and receive an error in the console: Failed to load resource: the server responded with a status of 431 (Request Header Fields Too Large). I came across information about max-h ...

Click Action on CanJS Table

I am currently developing a canJS application and have been able to successfully handle the click event for an HTML table using the code below. 'table td click':function(el,event){ console.log('clicked ',el.text()); } ...

Tips for displaying a modal within a modal in React

Currently, I have two components with modals. My goal is to open one modal from a button in the other component but clicking the button only closes the current active modal and doesn't open a new one. //Modal 1 <div className="modal fade" ...

Exploring the intricacies of React's useEffect: Solving the challenge of updating data when two separate dependency arrays are

I am facing an issue with two different useEffect hooks where the dependency arrays are different. const [dateFilterSort, setDateFilterSort] = useState({ queryText: initialQueryText(params.sortName), cardText: initialCardText(params.sortName), ...

Updating controller variables when the route changes in AngularJS

I'm new to the AngularJS scene and I've encountered a challenge. My goal is to have the selected tab change dynamically based on the URL changes. Here's my JavaScript code: app.config(function($routeProvider, $locationProvider){ $rou ...

Caution: It is important that each child within a list is assigned a distinct "key" prop - specifically in the Tbody component

I encountered the error above while running jest tests on a component. npm start is running without any issues. The component code is as follows: .... .... const [Data, setData] = useState([]); useEffect(() => { const fetchData = async () =&g ...

"Exploring the Allocation of Arrays within Structs Using malloc in a

Here is the struct I have: typedef struct akcie { int *stockArray; } AKCIE; Declaration of idStock: AKCIE *idStock; Allocating memory for idStock: idStock = (AKCIE *)malloc(id * sizeof(int)); // where id is an integer Now, in a function, I want ...

Retrieving information from Mongodb using Angularjs

Although my background is in a LAMP stack, my interest has recently been piqued by the Node.js/Angluarjs combo. I now want to incorporate Mongodb into the mix, but I'm struggling to set it up. Every tutorial I come across seems to use a different stac ...

Mastering the Material-UI Grid in SPAs: Conquering the Negative Margin Dilemma

While attempting to build a single page application (SPA), I've encountered an issue with using the Grid component from material-ui. Normally, I rely heavily on the Grid, but in this new project, something seems amiss. The current problem is evident ...

What is the best way to adjust the equal right padding or margin in the header for both IOS and Android using React Navigation options?

To ensure an equal gap on both sides for both IOS and Android platforms, I utilized a combination of techniques. For the right side, I achieved this using a minus margin, positive padding, and Platform. <Stack.Navigator screenOptions={{ contentSty ...

The Year as a Reference Point

I came across an interesting issue while working with dictionaries and JSON in sessionStorage. Initially, I had a dictionary structured like this: "name" : { "2016" : { "1" : "info" } } After successfully adding it to sessionS ...

The argument provided for the foreach function is not valid

Can anyone help me with this warning message I'm getting: Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\testplanning\modules\planning\planning.module on line 425. Here's the code where the err ...

Ways to identify if there is a problem with the Firestore connection

Can anyone help me understand how I can use angularfire2 to check the accessibility of the cloud firestore database and retrieve collection values? If accessing the cloud database fails, I want to be able to retrieve local data instead. This is an exampl ...

The controller method appears to be unable to detect any parameters

I have been trying to pass an ID in the URL but my controller is not receiving that value. $("#ChangeSlideForm").on("submit", function(){ $.ajax({ type: "POST", url: base_url + "Visualiser/ChangeSlide/21", su ...