Search code examples
angulartypescriptleafletngx-leaflet

Leaflet Map in Angular4 throwing errors


template :

<div id="mapid" style="height: 500px"></div>

I have installed leaflet and the typings for leaflet. When an error showed up saying map container was not found, i added it 's import.

controller :

    import { Component, OnInit, EventEmitter, Output } from 
    '@angular/core';
import * as L from 'leaflet';
import { Map } from 'leaflet';

@Component({
  selector: 'app-leafletmap',
  templateUrl: './leafletmap.component.html',
  styleUrls: ['./leafletmap.component.css']
})
export class LeafletmapComponent implements OnInit {
  mymap = L.map('mapid').setView([29.6516, -82.3248], 13);

  L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}',
   {
    attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, 
    <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://mapbox.com">Mapbox</a>',
    maxZoom: 18,
    id: 'mapbox.streets',
    accessToken: '*****************************'
  }).addTo(mymap);

  popup = L.popup();
  marker: any;

  onMapClick(e) {
    if (marker != undefined)
      mymap.removeLayer(marker)
    marker = new L.Marker(e.latlng, { draggable: true });
    mymap.addLayer(marker);
    popup.setLatLng(e.latlng).setContent("You clicked the map at " + e.latlng.toString()).openOn(mymap);
  }
  mymap.on('zoomend', function() {
    console.log(mymap.getZoom());
  })
  mymap.on('click', onMapClick);

  constructor() { }

  ngOnInit() {
  }

}

I am not sure if this is the way to pass access tokens and initializing variables in typescript as I wrote this code following a tutorial that was using regular Javascript.


Solution

  • I've recently worked with leaflet , so I post my code that is fully workable here. Please try it yourself.

    I use next npm module: npm install @asymmetrik/ngx-leaflet --save See: https://github.com/Asymmetrik/ngx-leaflet

    component.ts

    private map: L.Map;
    
    options = {
            layers: [
                L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 15 })
            ],
            zoom: 4,
            center: L.latLng([39.878868, -100.357010])
        };
    
    onMapReady(map: L.Map) {
        this.map = map;
    }
    

    component.html

    <div leaflet
         [leafletOptions]="options"
         (leafletMapReady)="onMapReady($event)">
    </div>
    

    app.module.ts

    imports: [
            BrowserModule,
            FormsModule,
            HttpModule,
            AppRoutingModule,
            BrowserAnimationsModule,
            LeafletModule.forRoot() // Don't forget to include leaflet here.
        ]
    

    You can try my basic variant and then if it works, you can add your options and your login to onMapReady function.

    UPD: If you want to reference something from leaflet, e.g. MapOptions in specific component, simply import leaflet in this way. import * as L from 'leaflet'; then use L.Map , L.MapOptions, etc.

    UPD2: Also it's essential to install types npm install @types/leaflet