Navigating through an array for drawing a polyline on Google Maps

Is there a way to efficiently loop through an array of coordinates in order to set markers and draw a line on Google Maps using the path property?

Please see the example below for clarification:

const lineSymbol = {
  path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
  strokeColor: "red",
      scale: 4
};

const locations = [
      ["Tampere", 61.50741562413278, 23.75886761967578,  1, "Termin: xx.xx"],
      ["Helsinki", 60.219957, 25.196776,  2, "test2"],
      ["Travemünde", 55.778989, 18.271974,  2, "test3"],
      ["Stuttgart", 48.7733567672875, 9.174572759931003, 3, "test4"],
      ["Ludwigsburg", 48.8893286910321,  9.197454231637288, 4, "test5"],
]

const line = new google.maps.Polyline({

    path: [
        { lat:  locations[0][1], lng: locations[0][2] },
        { lat:  60.219957, lng:  25.196776 },
        { lat:  locations[2][1], lng: locations[2][2] },
        { lat:  53.941362, lng:  10.860464 },
        { lat: 48.7733567672875, lng: 9.174572759931003 },
    ],
    strokeColor: "red",
        scale: 7,
    icons: [
        {
          icon: lineSymbol,
          offset: "100%",
        },
    ],
 map: map,
});

Implementing the above code will result in generating this visual display on Google Maps:

View the outcome here

Answer №1

To handle the input array and generate a polyline in a loop:

var path = [];
for (var i=0; i<locations.length; i++) {
  // add to polyline
  path.push({lat: locations[i][2], lng: locations[i][1]});
  // create marker
  new google.maps.Marker({
    position: path[path.length-1],
    map: map
  })
}
const line = new google.maps.Polyline({
    path: path,
    strokeColor: "red",
        scale: 7,
    icons: [
        {
          icon: lineSymbol,
          offset: "100%",
        },
    ],
 map: map,
});

link to fiddle for demonstration

(please note that the data in your inquiry does not align with the image provided)

https://i.sstatic.net/XtLva.png

snippet of code:

// This example creates a 2-pixel-wide red polyline showing the path of
// the first trans-Pacific flight between Oakland, CA, and Brisbane,
// Australia which was made by Charles Kingsford Smith.
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 3,
    center: {
      lat: 0,
      lng: -180
    },
    mapTypeId: "terrain",
  });
  const lineSymbol = {
    path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW,
    strokeColor: "red",
    scale: 4
  };

  const locations = [
    ["Tampere", 61.50741562413278, 23.75886761967578, 1, "Termin: xx.xx"],
    ["Helsinki", 60.219957, 25.196776, 2, "test2"],
    ["Travemünde", 55.778989, 18.271974, 2, "test3"],
    ["Stuttgart", 48.7733567672875, 9.174572759931003, 3, "test4"],
    ["Ludwigsburg", 48.8893286910321, 9.197454231637288, 4, "test5"],
  ]
  var path = [];
  var bounds = new google.maps.LatLngBounds();
  for (var i = 0; i < locations.length; i++) {
    path.push({
      lat: locations[i][2],
      lng: locations[i][1]
    });
    bounds.extend(path[path.length - 1]);
    new google.maps.Marker({
      position: path[path.length - 1],
      map: map
    })

  }

  const line = new google.maps.Polyline({

    path: path,
    strokeColor: "red",
    scale: 7,
    icons: [{
      icon: lineSymbol,
      offset: "100%",
    }, ],
    map: map,
  });
  map.fitBounds(bounds);
}
/* Always set the map height explicitly to define the size of the div
       * element that contains the map. */

#map {
  height: 100%;
}


/* Optional: Makes the sample page fill the window. */

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!DOCTYPE html>
<html>

<head>
  <title>Simple Polylines</title>
  <script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
  <!-- jsFiddle will insert css and js -->
</head>

<body>
  <div id="map"></div>

  <!-- Async script executes immediately and must be after any DOM elements used in callback. -->
  <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap&v=weekly&channel=2" async></script>
</body>

</html>

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

What is the process for adding a dot to the package.json file using the npm-pkg command?

I need help using the npm pkg set command to create a package.json file with the following structure: { ... "exports": { ".": { "import": "./dist/my-lib.js", "require": "./dist/my-l ...

Even after setting the handler to return false, Angular continues to submit the form

In the following scenario, I have encountered an issue: Here is the HTML template snippet: <form [action]='endpoint' method="post" target="my_iframe" #confirmForm (ngSubmit)="submitConfirmation()"> <button type="submit" (click)="conf ...

Creating a program to ascertain whether two integers inputted by a user are odd numbers

I need assistance in creating a function that can ascertain whether two numbers input by the user are odd and then return a boolean value that is true only if both numbers are odd. I'm already familiar with creating a function to check for even number ...

Managing JavaScript with Scrapy

Spider for reference: import scrapy from scrapy.spiders import Spider from scrapy.selector import Selector from script.items import ScriptItem class RunSpider(scrapy.Spider): name = "run" allowed_domains = ["stopitrightnow.com"] start_urls = ...

Solving the issue of image paths within external SCSS files in Nuxt.js

Trying to organize my component scss files separately from their Vue components has been a bit challenging. I also have a GLOBAL scss file that is not scoped, but no matter which approach I take, I can't seem to get the image paths in /assets or /stat ...

AngularJS Perspectives: Unveiling the Secrets of Successful Implementation

Do you have any tips on troubleshooting AngularJS views? I found a demo at AngularJS: ngView, but the provided jsfiddle doesn't seem to work. I've been trying to play around with it, but still haven't had any success. This is the code I&apo ...

Changing the URL parameters to accommodate a specific query

Currently, I have set up the route as follows: app.get("/employees", (req, res) => { data.getAllEmployees().then((data) => { res.json(data); }).catch(function(err) { console.log("An error was encountered: " + err); }); }) ...

Is there a way to speed up the loading time of React in the browser?

My experience with using React in the browser has been positive, but I'm facing a speed issue. The initial loading time is quite lengthy as it compiles. I am looking for a way to use React/JSX directly in the browser and have it compile instantly wit ...

Creating an effortless RSS feed using jQuery and Ajax

I could use some assistance with creating a basic rss feed that pulls content from websites like arstechnica. I've spent the last few hours researching how to do this, but I'm feeling a bit lost on the correct approach. Currently, I'm trying ...

Establishing parameters in a Socket.io chatroom

I am encountering an issue when attempting to store information in the socket room variables. The error message I receive is: UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'host' of undefined This is the snippet of my code: io ...

Obtain the last x elements

What is the most efficient way to extract a specific number of elements from the end? <div><span>1</span></div> <div><div>looks like 2</div></div> <div>three!!</div> For instance, how could I re ...

Utilize a nested array structure

Hello everyone, I have the following code snippet: array( 'id' => 'tweet_slider', 'name' => __( 'Slide', TB_GETTEXT_DOMAIN ), 'desc' => __( 'Select th ...

Display a single component from a panel with Angularjs

As a newcomer to Angularjs, I am currently exploring the functionality of its different modules. For my project, I am aiming to create an accordion-style layout for a page where clicking on a panel button reveals a table. The dynamic HTML code generated ...

I could really use some assistance with this project for my friend

Whenever I click on the image, it only displays two out of the three possible alerts. How can I make it show all three? Here's my code: <!DOCTYPE html> <html> <head> </head> <body> <img src="http://www.build ...

Addon for Firefox: Image Upload

I am looking for a way to streamline the process of uploading an image to a website through a Firefox Addon. While I know it is possible to use createElement('canvas'), convert Image data to base64, and XHR POST the data, I would prefer to lever ...

Managing multiple ajax requests only functions properly when notifications are raised

I'm looking to efficiently transfer data to the server from multiple lists on a page by using ajax calls to process the information in PHP. My code iterates through each list with the class "dd" and sends the ajax data one by one. Everything works smo ...

Maximizing the potential of typescript generics in Reactjs functional components

I have a component within my react project that looks like this: import "./styles.css"; type InputType = "input" | "textarea"; interface ContainerProps { name: string; placeholder: string; as: InputType; } const Conta ...

How can you locate the position of identified text on a webpage to accurately place the mouse cursor there?

When browsing a webpage in my web browser (preferably Firefox), I have the ability to search for a specific text "abc" using ctrl+f. Once found, I need to move my mouse cursor to another relative position on the page and click. Unfortunately, the necessar ...

Interacting with external domains through ajax queries

I'm encountering an issue with my javascript code that sends an ajax request, but I'm not receiving any response. Can anyone offer some guidance on how to troubleshoot this problem? Thank you! The URL I am attempting to retrieve is: Here's ...

Tips for sending a parameter to an onClick handler function in a component generated using array.map()

I've been developing a web application that allows users to store collections. There is a dashboard page where all the user's collections are displayed in a table format, with each row representing a collection and columns showing the collection ...