angulartypescriptleafletmapsngx-leaflet

How to change coordinates runtime on ngx-leaflet?


There is any alternative to change ngx-leaflet map coordinates in runtime? This is possible with google maps and i'm trying do the same with leaflet.

Changes to leafletOptions are ignored after they are initially set. This is because these options are passed into the map constructor, so they can't be changed anyways. So, make sure the object exists before the map is created. You'll want to create the object in ngOnInit or hide the map DOM element with *ngIf until you can create the options object.

component:

  private   options = {
      layers: [
        tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
          attribution: '© OpenStreetMap contributors'
        })
      ],
      zoom: 7,
      center: latLng([ 46.879966, -121.726909 ])
    };

html:

<div style="height: 500px;"
    leaflet
     [leafletOptions]="(options)"
     ></div>

Solution

  • You need to get a reference to the map when the map is loaded and then use that reference to change the view.

    component

    import * as L from 'leaflet';
    import {
        latLng,
        tileLayer
    } from 'leaflet';
    
    map: L.Map;
    
    options = {
        layers: [
            tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: '&copy; OpenStreetMap contributors'})
        ],
        zoom: 7,
        center: latLng([ 46.879966, -121.726909 ])
    };
    
    // get the reference to the map
    onMapReady(map: L.Map) {
        this.map = map;
    }
    
    // change the view using that map reference to another location
    changeView() {
        this.map.panTo(new L.LatLng(40.737, -73.923));
    }
    

    template

    <div style="height: 500px;"
        leaflet 
        [leafletOptions]="options"
        (leafletMapReady)="onMapReady($event)">
    </div>
    
    <button (click)="changeView()">Change view</button>
    

    Demo