Search code examples
javascriptangularleafletngx-leaflet

Use leaflet-arc in Angular?


How do I use the leaflet-arc plugin in Angular? What I've tried so far:

  1. npm install --save leaflet-arc
  2. Add "scripts": ["node_modules/leaflet-arc/src/leaflet-arc.js"] to angular.json.
  3. Add import '../../../node_modules/leaflet-arc/src/leaflet-arc.js'; to my-component.component.ts.

However when I do the following inside my-component.component.ts, it still gives me an error that Property 'Arc' does not exist on type 'typeof Polyline'.:

L.Polyline.Arc(...)

When I do ng serve this actually works, but it still gives the error when compiling.

Any ideas?


Solution

  • To make it work you need to follow these steps:

    1. npm i leaflet --save
    2. npm install --save leaflet-arc

    Go to angular.json an add the two libraries as follows:

     "styles": [
          "node_modules/leaflet/dist/leaflet.css",
          "src/styles.css"
      ],
      "scripts": [
          "node_modules/leaflet/dist/leaflet.js",
          "node_modules/leaflet-arc/src/leaflet-arc.js"
      ]
    

    In app.component.ts you need to import the two libraries as follows:

    import { Component, OnInit } from '@angular/core';
    import 'leaflet';
    import 'leaflet-arc'; // import leaflet-arc here
    
    declare let L;
    
    @Component({
        selector: 'app-root',
        templateUrl: './app.component.html',
        styleUrls: [ './app.component.css' ]
    })
    export class AppComponent implements OnInit {
        ngOnInit() {
            const map = L.map('map').setView([60, 100], 3);
            // create an arc here
            L.Polyline.Arc([59.56667, 150.80000], [67.50000, 64.03333], {
                color: 'red',
                vertices: 200
            }).addTo(map);
    
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            }).addTo(map);
        }
    }
    

    template:

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

    style:

    #map {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%
    }
    

    Demo