Search code examples
angulartypescriptleafletopenstreetmap

Access Leaflet map in different component in Angular


I have a component, OpenStreetMapComponent, which views my whole map. In the same component I also have a number of buttons (zoom, current location...). Having all of that in one component soon makes things unreadable so I would like to have the buttons in a different component. I do not know how to get access the map if the buttons are in another component though.

Below my OpenStreetMap Component:

import { Component, OnInit } from '@angular/core';
declare let L; //this is the leaflet variable!

@Component({
  selector: 'app-open-street-map',
  templateUrl: './open-street-map.component.html',
  styleUrls: ['./open-street-map.component.css']
})
export class OpenStreetMapComponent implements OnInit {

  constructor( ) { }

  ngOnInit() {

    const map = L.map('map', {
      center: [48.208, 16.373],
      zoom: 13,
      zoomControl: false,
    });
// button to center map
    L.easyButton('<span><i class="fa fa-compass fa-2x"></i></span>', function(btn, map) {
      map.setView([48.208, 16.373], 13);
    },
      {
        position: 'topright'
      }).addTo(map);

    // get current location
    L.easyButton('<span class="myLocationIcon"><i class="myLocationIcon fa fa-map-marker fa-2x"></i></i></span>', function(btn, map) {
      map.locate({ setView: true, watch: false, enableHighAccuracy: true }) // set watch "true", to get realtime location, if im not mistaken
        .on('locationfound', function(e) {
          L.marker([e.latitude, e.longitude], { icon: personIcon }).addTo(map);
          L.circle([e.latitude, e.longitude], {
            weight: 1,
            color: 'blue',
            fillColor: '#cacaca',
            fillOpacity: 0.2
          }).addTo(map);
        })
        .on('locationerror', function(e) {
          alert("Cannot access your location!");
        })
    },
      {
        position: 'topright'
}).addTo(map);

these two buttons I would like to have in a different component called MapButtonsComponent.

Any ideas?


Solution

  • In my opinion you don't need a component as you don't have to do with html and logic but pure instance calls. Therefore you can create a class named MapButtons and there create two public static methods by passing as an argument the map instance object.

    map-buttons.ts:

    import 'leaflet';
    declare let L;
    
    export class MapButtons {
        public static renderCompass(map: object) {
            // tslint:disable-next-line:no-shadowed-variable
            return L.easyButton('fa fa-compass fa-2x', function(btn, map) {
                map.setView([48.208, 16.373], 13);
            }, { position: 'topright' }).addTo(map);
        }
    
        public static renderMarker(map: object) {
            // tslint:disable-next-line:no-shadowed-variable
            return L.easyButton('<span class="myLocationIcon"><i class="myLocationIcon fa fa-map-marker fa-2x"></i></i></span>', function(btn, map) {
            // tslint:disable-next-line:max-line-length
            map.locate({ setView: true, watch: false, enableHighAccuracy: true }) // set watch "true", to get realtime location, if im not mistaken
                .on('locationfound', function(e) {
                    // L.marker([e.latitude, e.longitude], { icon: personIcon }).addTo(map);
                    L.circle([e.latitude, e.longitude], {
                        weight: 1,
                        color: 'blue',
                        fillColor: '#cacaca',
                        fillOpacity: 0.2
                    }).addTo(map);
                }).on('locationerror', function(e) {
                    alert('Cannot access your location!');
                });
            },
            {
                position: 'topright'
            }).addTo(map);
        }
    }
    

    app.component.ts or open-street-map-component.ts:

    import 'leaflet';
    import 'leaflet-easybutton';
    
    import { MapButtons } from './map-buttons';
    
    ngOnInit() {
        const map = L.map('map', {
            center: [48.208, 16.373],
            zoom: 13,
            zoomControl: false
        });
    
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        }).addTo(map);
    
        MapButtons.renderCompass(map);
        MapButtons.renderMarker(map);
    }
    

    app.component.html or open-street-map-component.html:

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet-easybutton@2/src/easy-button.css">
    
    <div id="map"></div>