簡體   English   中英

如何設置 Leaflet 地圖的縮放以顯示 React Leaflet 中的所有標記?

[英]How to Set Leaflet Map's Zoom to Show All Markers in React Leaflet?

我有一個 React Leaflet map 需要在給定一組標記時更改其中心和縮放。 應更改縮放以使所有標記都可見。

目前正在嘗試使用 function ChangeView進行這種視圖更改。

使用下面的代碼,我可以移動 map 視圖,但不能讓 map 適合邊界。 運行代碼給出錯誤:

錯誤:邊界無效。

在線上

map.fitBounds(markerBounds)

我們能做什么? 謝謝!

import L, { LatLng, latLngBounds, FeatureGroup } from 'leaflet';
import React from 'react';
import { MapContainer, TileLayer, Marker, Popup, useMap } from 'react-leaflet';
import MarkerClusterGroup from 'react-leaflet-markercluster';

import { LatLon, MapMarker } from '../../common/types';
import { config } from '../../config';

interface IProps {
    markers: MapMarker[];
    searchCenter: LatLon;
}

interface IChangeView {
    center: LatLon;
    markers: MapMarker[];
}

function ChangeView({ center, markers }: IChangeView) {
    const map = useMap();
    map.setView({lng: center.lon, lat: center.lat}, DEFAULT_ZOOM);
    
    let markerBounds = latLngBounds([]);
    markers.forEach(marker => {
        markerBounds.extend([marker.lat, marker.lon])
    })
    map.fitBounds(markerBounds)   // <===== Error: Bounds are not valid.
    return null;
}


export function MapView({markers, searchCenter}: IProps): JSX.Element {
    
    return (
        <MapContainer
            center={[searchCenter.lat, searchCenter.lon]}
            zoom=14
            style={{ width:'100%', height:'100vh' }}
            className='markercluster-map'
        >
            <ChangeView center={searchCenter} markers={markers} />
            <TileLayer 
                url={`https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/{z}/{x}/{y}?access_token=${config.api.mapbox}`}
            />
            <MarkerClusterGroup>
                {
                    markers.map((marker, index) => (
                        <Marker 
                            position={[marker.lat, marker.lon]} 
                            key={index}
                        />
                    ))
                }
            </MarkerClusterGroup>
        </MapContainer>
    )
}

也嘗試使用FeatureGroup而不是latLngBounds ,但它給出了完全相同的錯誤

錯誤:邊界無效

    let group = new FeatureGroup();
    markers.forEach(marker => {
        L.marker([marker.lat, marker.lon]).addTo(group);
    })
    map.fitBounds(group.getBounds());

如果markers數組為空或null ,則您創建的邊界將沒有._southWest._northEast屬性,並且會拋出該錯誤。 只需使fitBounds語句以數組中有標記為條件:

if (markers.length && markers.length > 0){
  markers.forEach(marker => {
    markerBounds.extend([marker.lat, marker.lon])
  })
  map.fitBounds(markerBounds)
}

甚至只是一個快速的班輪:

markerBounds.isValid() && map.fitBounds(markerBounds)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM