Getting the list of markers when zoomed in leaflet map

别来无恙 提交于 2019-12-04 09:15:28

First, set up a handler on the (leafletMapReady) so you can get a reference to the map. In onMapReady, you can store the reference to the map inside your component so you can use it later.

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

To handle zoom events, register for the zoomend event on the map, so you will get a callback whenever a zoom event ends on the map. You probably also want to handle moveend as well.

On those events, filter your markers based on their position and the bounds of the map. Update the bound layers array to contain the filtered markers. And, since you're making these changes in a Leaflet callback, which is outside of the Angular zone, you will want to run the change in Angular's zone - this.zone.run(...).

See this complete example:

import { Component, NgZone } from '@angular/core';

import { icon, latLng, Layer, Map, marker, Marker, point, polyline, tileLayer } from 'leaflet';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  googleMaps = tileLayer('http://{s}.google.com/vt/lyrs=m&x={x}&y={y}&z={z}', {
    maxZoom: 20,
    subdomains: ['mt0', 'mt1', 'mt2', 'mt3'],
    detectRetina: true
  });

  markers: Marker[] = [
    marker([ 45, -121 ], { icon: this.createIcon() }),
    marker([ 46, -121 ], { icon: this.createIcon() }),
    marker([ 47, -121 ], { icon: this.createIcon() }),
    marker([ 48, -121 ], { icon: this.createIcon() }),
    marker([ 49, -121 ], { icon: this.createIcon() })
  ];

  layers: Layer[] = [];
  map: Map;

  options = {
    layers: [ this.googleMaps ],
    zoom: 7,
    center: latLng([ 46.879966, -121.726909 ])
  };

  constructor(private zone: NgZone) {}

  createIcon() {
    return icon({
      iconSize: [ 25, 41 ],
      iconAnchor: [ 13, 41 ],
      iconUrl: 'leaflet/marker-icon.png',
      shadowUrl: 'leaflet/marker-shadow.png'
    });
  }

  updateMarkers() {
    this.zone.run(() => {
      this.layers = this.markers.filter((m: Marker) => this.map.getBounds().contains(m.getLatLng()));
    });
  }

  onMapReady(map: Map) {
    this.map = map;

    this.map.on('moveend', this.updateMarkers.bind(this));
    this.map.on('zoomend', this.updateMarkers.bind(this));

    this.updateMarkers();
  }

}

This is the key part of the above excerpt:

this.layers = this.markers.filter((m: Marker) => this.map.getBounds().contains(m.getLatLng()));

This is where you are filtering out all of the markers that are not in the current view bounds of the map and then setting the resulting collection of markers to be the new set of map layers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!