I am new to leaflet. I have set up the map following the steps on https://github.com/Asymmetrik/ngx-leaflet
I am trying to get the list of markers in the zoomed in area of the map that can be used in getting the objects in focus. How do I do this with ngx-leaflet in angular 4?
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.
来源:https://stackoverflow.com/questions/48993885/getting-the-list-of-markers-when-zoomed-in-leaflet-map