如何使用React-Leaflet获取标记集合的边界

时间:2017-01-29 23:00:52

标签: javascript reactjs leaflet react-leaflet

如何获取标记集合的边界,以便这些边界可用于显示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 个答案:

答案 0 :(得分:2)

您可以向Map component添加bounds参数。它接受leaflet latLngBounds参数。所以你可以做到以下几点:

import {latLngBounds} from 'leaflet'

...

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

  return (
    <Map bounds={bounds} >
      ...
    </Map>
  )
}

答案 1 :(得分: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>
  )

答案 2 :(得分: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,
        });
    }
}

答案 3 :(得分: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;