Utilize ngmap to draw a connection between two designated points

I have successfully utilized ngmap and AngularJS to display a series of markers on a map. However, I am now looking to draw a line that connects these markers.

Below is my code:

In the view:

 <map center="{{markers[0].lat}},{{markers[0].lng}}" zoom="12">
   <marker ng-repeat="pos in markers" position="{{pos.lat}}, {{pos.lng}}"></marker>
</map>

In my controller:

var app = angular.module('Items', ['ngMap'])

app.controller('CICtrl', function($scope){
    $scope.markers = [{id:1, lat:37.772323, lng: -122.214897}, {id:2, lat:21.291982, lng: -157.821856}, {id:3, lat:-27.46758, lng: 153.027892}];
});

Answer №1

To achieve this, you can make use of the shape directive, like so:

<shape name="polyline" path="{{path}}" geodesic="true" stroke-color="#FF0000" stroke-opacity="1.0" stroke-weight="2"></shape>

The path property is initialized from the markers array in this way:

$scope.path = $scope.markers.map(function(marker){
    return [marker.lat, marker.lng];
});

Check out a live demo below:

var app = angular.module('appMaps', ['ngMap']);
app.controller('mainCtrl', function ($scope) {
    $scope.markers = [{ id: 1, lat: 37.772323, lng: -122.214897 }, { id: 2, lat: 21.291982, lng: -157.821856 }, { id: 3, lat: -27.46758, lng: 153.027892 }];
    $scope.path = $scope.markers.map(function(marker){
        return [marker.lat, marker.lng];
    });
});
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=weather,visualization,panoramio"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script src="https://rawgit.com/allenhwkim/angularjs-google-maps/master/build/scripts/ng-map.js"></script>
<div id="map_canvas" ng-app="appMaps" ng-controller="mainCtrl" >
        <map center="{{markers[0].lat}},{{markers[0].lng}}" zoom="5">
            <marker ng-repeat="pos in markers" position="{{pos.lat}}, {{pos.lng}}"></marker>
            <shape name="polyline" path="{{path}}" geodesic="true" stroke-color="#FF0000" stroke-opacity="1.0" stroke-weight="2">
            </shape>
        </map>
</div>

View the Code Demo on Plunker

Answer №2

For those seeking to display driving directions between markers and customize the look of the line connecting each marker:

Example in Action:

In your controller:

$scope.directions = [
  {
    origin:"Salt Lake City, Utah", 
    destination:"West Valley City, Utah", 
    panelName:"p1",
    renderingOptions: {
      polylineOptions: {
        strokeColor: 'red'
      }      
    },
    wayPoints: [
      {
        location: {lat:40.6812675, lng: -111.9622787},
        stopover: true
      },
      {
        location: {lat:40.6812675, lng: -110.9622787},
        stopover: true
      },
    ]
  },
  {
    origin:"West Valley City, Utah", 
    destination:"West Jordan, Utah", 
    panelName:"p1",
    renderingOptions: {
      polylineOptions: {
        strokeColor: 'blue'
      }      
    },
    wayPoints: [
      {
        location: {lat:40.6812675, lng: -111.9622787},
        stopover: true
      },
      {
        location: {lat:40.6812675, lng: -109.9622787},
        stopover: true
      },
    ]
  },
  {
    origin:"West Jordan, Utah", 
    destination:"Salt Lake City, Utah", 
    panelName:"p2",
    renderingOptions: {
      polylineOptions: {
        strokeColor: 'green'
      }      
    },
    wayPoints: [
      {
        location: {lat:40.6812675, lng: -111.9622787},
        stopover: true
      },
      {
        location: {lat:40.6812675, lng: -108.9622787},
        stopover: true
      },
    ]
  }
];   

HTML: Provide an object like this:

renderingOptions: {polylineOptions: {strokeColor: 'red'}}

in the options attribute of the <directions> element

          <div style="width: 100%; float:left; height:70%" >     
            <ng-map zoom="3" center="current-location" default-style="false" style="height: 450px; display:block; ">
                <directions ng-repeat="dir in directions"
                  draggable="true"
                  options="{{dir.renderingOptions}}"
                  travel-mode="DRIVING"
                  waypoints="{{dir.wayPoints}}"
                  panel="{{dir.panelName}}"
                  origin="{{dir.origin}}"
                  destination="{{dir.destination}}">
                </directions>            
            </ng-map>
          </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

Leveraging ES6 Symbols in Typescript applications

Attempting to execute the following simple line of code: let INJECTION_KEY = Symbol.for('injection') However, I consistently encounter the error: Cannot find name 'Symbol'. Since I am new to TypeScript, I am unsure if there is somet ...

Executing the .click() function of jQuery within a loop

These specific elements are scattered throughout my HTML code <input id="1" type="button" value="1" > and then there's this one <input type="text" name="answer" id="answer"> In my JavaScript, I've defined a function sum =(eve)=&g ...

Exploring the Depths of React Routing: The Power

I'm currently diving into React and trying to figure out how to create dynamic routes similar to partial pages in Angular. Here is my main App component: import React from 'react'; import Header from '../common/Header'; export d ...

When the React ref current is accessed from outside the component where it is initialized, it returns

Encountering an issue with React ref. Today, I was pondering on how to access DOM elements from sub-components within a main component. Fortunately, I stumbled upon a solution using React refs on a website. I set up a ref in my main component and linked i ...

Difficulty in accessing controller data in AngularJS with ng-repeat

I am trying to display comments using ng-repeat in a section, but I am having trouble accessing the data. Even after debugging, I cannot access the data without modifying the controller. I am new to Angular and prone to making mistakes. HTML / JS &apo ...

Uncaught ReferenceError: ajaxUrl is undefined

After pressing a green button on the website , instead of the expected popup image and email confirmation, I receive an error message stating "ajaxUrl is not defined". I have attempted to find a solution to this problem by searching on Google and Stackove ...

Can I restrict access to all routes except one in vue-router? Is this a safe practice? Should I explore alternative methods for achieving this?

I am looking to create an online exam consisting of 5 pages, each with a countdown timer set at 120 seconds and 4 questions on each page. Once the timer runs out, users will be automatically redirected to the next page, or they can manually click the "next ...

What could be causing the checkbox filter to malfunction in VueJS?

After spending a solid 8 hours attempting to make this work, I'm still struggling. My main goal is to display a loop that shows all items by default. Then, when a user selects a checkbox, it will filter out the items where they are set to false. Here ...

Issue encountered with edges helper and a partly opaque object rendering

My goal is to create a realistic earth using three.js, similar to this example, which is an improvement from this one. However, I am facing an issue where the rendering order of the sky, earth, and atmosphere is not being properly interpreted by the render ...

Creating fixed values in HTML

I need to maintain consistency in the headings of multiple tables spread across 3 HTML pages. The heading structure is as follows: <thead> <tr> <th>MyHeading</th> </tr> </thead> My goal is to store the string MyHeadin ...

What is the process to manually trigger hot reload in Flutter?

I am currently developing a Node.js application to make changes to Flutter code by inserting lines of code into it. My goal is to view these updates in real-time. Is there a way to implement hot reload so that every time I finish writing a line in the file ...

The functionality of this javascript setTimeout is quite peculiar when it comes to working with ajax requests

I have created this script to monitor the progress of an import script. The script is designed to execute a function that makes an http request every X seconds. function checkImportProgress() { //if(import_status != 'finalizat') { alert("Che ...

Making an AJAX POST request using jQuery to send the current date and time to an ASP

I am working with an ASP.NET Web API endpoint where I need to send POST data. Suppose I want to post the following information: var myObject = { name: "Alice Johnson", age: "29", accountCreated: "CURRENT DATE TIME" }; What is the JavaScript equivalent o ...

What are the steps for testing a function that outputs a promise using $q?

My JavaScript Code: case "start": helper.initiateStart("http://www.example.com").then(function (){begin();}); Explanation of initiateStart Function initiateStart: function (url) { //... return $q.when(); }, Testing the f ...

Should all pages in React be rendered on the server side?

Currently, I rely on Next.js for implementing server-side rendering on my React website. At the moment, I have implemented server-side rendering across almost all pages of the site, including profile information and other content that requires a login to ...

Enhance the impact of "dialogs" to the fullest extent or minimize it to achieve the

How can I position the minimized dialog on the bottom of the div when appending dialogs next to each other in a FB messaging system? To achieve a Facebook messaging effect, the titlebar must go down when minimizing/maximizing the dialog. Perform the follo ...

Grabbing the HTML value and storing it in a JavaScript variable

In my table, each row has multiple columns including one with a checkbox. When this checkbox is checked, a new column cell appears to the right of the table with an up/down spinner to adjust a value. The issue I'm facing is that I want to limit the s ...

Unlock the Power of Core 2 MVC with the Cutting-edge Integration of

Looking for a solution on how to effectively use JQuery Datatables with Core MVC? Check out this helpful resource: Using jQuery DataTables Grid With ASP.NET CORE MVC I recently downloaded the sample project and made some modifications to fit my needs. It ...

Guide to incorporating @types/module with the corresponding npm module that has type definitions available

This is an example of a module I am currently utilizing in my project. I have come across TypeScript type definitions for the npm module polylabel, which can be found at https://github.com/mapbox/polylabel. When I run npm install --save @types/polylabel, ...

Tips for creating a stylish navbar with a faded effect on the right side and integrating a fresh button into its design

I'm looking to enhance my Navbar by implementing a feature where, if the width of the Navbar exceeds that of its parent div, it will fade on the right side and a new button will be added - similar to what can be seen on Youtube. 1- When the Navbar&ap ...