2

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>
kboul
  • 13,836
  • 5
  • 42
  • 53
John
  • 1,697
  • 4
  • 27
  • 53
  • When do you want exactly to change the map coordinates? After the map has been loaded like clicking on a button and then change the map location? Please clarify. – kboul Oct 13 '18 at 08:47
  • @kboul kboul that's exactly what I want to do – John Oct 14 '18 at 23:57

1 Answers1

8

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

kboul
  • 13,836
  • 5
  • 42
  • 53