2

如何获得标记集合的边界,以便这些边界可用于显示react-leaflet地图上的所有标记?这是我的渲染功能:

render() {
    const position = [51.505, 4.12];

    return (
        <Map center={position} zoom={3} style={{width: '100%', height: '600px'}} >
            <TileLayer
                attribution='&copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
            />
            {this.state.markers || null}
        </Map>
    );
}

标记添加到this.state.markers

this.state.markers.push(
    <Marker position={position}>
        <Popup>
            <span>Hello</span>
        </Popup>
    </Marker>
);
this.setState({markers: this.state.markers});

标记正在显示,但我希望调整地图的边界和中心,以便标记很好地适合地图的视口并具有一定的填充量。

关于如何做到这一点的任何想法?

编辑:这是我的导入声明:import {Map, Marker, Popup, TileLayer} from 'react-leaflet';

4

4 回答 4

7

您可以向Map 组件添加 bounds 参数。它接受传单 latLngBounds参数。因此,您可以执行以下操作:

import {latLngBounds} from 'leaflet'

...

render () {
  const bounds = latLngBounds([firstCoord, firstCoord])
  markerData.forEach((data) => {
    bounds.extend(data.latLng)
  })

  return (
    <Map bounds={bounds} >
      ...
    </Map>
  )
}
于 2017-02-15T18:31:39.340 回答
1

使用钩子,这对我有用

   // 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>
  )

于 2020-07-15T16:58:46.103 回答
0

我在 Angular 中使用了以下函数,但我相信它也应该对你有用。

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,
        });
    }
}
于 2020-05-28T19:06:45.290 回答
0

创建一个数组bounds,将标记的所有坐标推入其中并将其作为道具传递给地图:

import { Map, latLngBound } from "react-leaflet";

const Map = () => {

  const bounds = []

  positions.map((position,i) => {
    bounds.push([position.lat, position.lon])
  })

  return (

    <MapContainer
      bounds={bounds}
    >
    ...
    </MapContainer>

  );
};

export default Map;

于 2021-03-03T18:35:56.750 回答