¿Cómo puedo obtener los límites de una colección de marcadores, de modo que estos límites puedan usarse para mostrar todos los marcadores en un mapa react-leaflet ? Esta es mi función de renderizado:
render() { const position = [51.505, 4.12]; return ( <Map center={position} zoom={3} style={{width: '100%', height: '600px'}} > <TileLayer attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' /> {this.state.markers || null} </Map> ); } Los marcadores se agregan a this.state.markers con:
this.state.markers.push( <Marker position={position}> <Popup> <span>Hello</span> </Popup> </Marker> ); this.setState({markers: this.state.markers});Los marcadores se muestran, pero quiero que los límites y el centro del mapa se ajusten para que los marcadores encajen bien dentro de la ventana gráfica del mapa con una cierta cantidad de relleno.
¿Alguna idea sobre cómo hacer esto?
Editar: esta es mi declaración de importación: import {Map, Marker, Popup, TileLayer} from 'react-leaflet';
Puede agregar un parámetro de límites al componente Mapa . Acepta un argumento de folleto latLngBounds . Así que puedes hacer lo siguiente:
import {latLngBounds} from 'leaflet' ... render () { const bounds = latLngBounds([firstCoord, firstCoord]) markerData.forEach((data) => { bounds.extend(data.latLng) }) return ( <Map bounds={bounds} > ... </Map> ) }Estoy usando la siguiente función en Angular, pero creo que también debería funcionar para usted.
fitMapBounds() { // Get all visible Markers const visibleMarkers = []; this.map.eachLayer(function (layer) { if (layer instanceof L.Marker) { visibleMarkers.push(layer); } }); // Ensure there's at least one visible Marker if (visibleMarkers.length > 0) { // Create bounds from first Marker then extend it with the rest const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]); visibleMarkers.forEach((marker) => { markersBounds.extend(marker.getLatLng()); }); // Fit the map with the visible markers bounds this.map.flyToBounds(markersBounds, { padding: L.point(36, 36), animate: true, }); } }Usando ganchos, esto funcionó para mí.
// example markers const markers = [ [49.8397, 24.0297], [52.2297, 21.0122], [51.5074, -0.0901], [51.4074, -0.0901], [51.3074, -0.0901], ] // hook so this only executes if markers are changed // may not need this? const bounds = useMemo(() => { const b = latLngBounds() // seemed to work without having to pass init arg markers.forEach(coords => { b.extend(coords) }) return b }, [markers]) ... return ( <Map bounds={bounds} {...rest}> ... </Map> )