![](/img/trans.png)
[英]How to call fitBounds and getBounds in react-leaflet?
[英]How to flyTo and then getBounds around location based on selected location in react-leaflet
當從城市列表下拉列表和該位置周圍的 getBounds 動態選擇位置時,我如何放大特定位置或動態飛到該特定位置。 我正在嘗試參考這個答案,但這可以在 flyTo 發生后起作用。 那么如何在我的代碼中使用 flyTo 。
useEffect(() => {
const cityFilter = () => {
let geocodes = JSON.parse(sessionStorage.getItem('geocode'));
let mapData = props.allEquipData.filter((filtered) => {
return filtered.city === selectedCity;
});
Promise.all(
mapData.map(async (data) => {
let selectedLocGeo = geocodes.filter((geo) => geo.zip == data.zipcode);
if (selectedLocGeo.length > 0) {
data.coordinates = [selectedLocGeo[0].latitude, selectedLocGeo[0].longitude];
} else {
data.coordinates = [0, 0];
}
return data;
})
)
.then((response) => {
let markerData = [];
let count = 1;
response.map((resp, index) => {
if (resp.coordinates[0] !== 0 && resp.coordinates[1] !== 0) {
let existingPositionIndex = markerData.findIndex(
(mark) =>
mark.positions && mark.positions.length && mark.positions[0] === resp.coordinates[0] && mark.positions[1] === resp.coordinates[1]
);
if (existingPositionIndex > -1) {
markerData[existingPositionIndex].devices.push(resp);
} else {
let obj = {
positions: resp.coordinates,
key: 'marker' + count,
devices: [resp],
location: resp.city + ', ' + resp.state,
};
markerData.push(obj);
count++;
}
}
});
// let group = new L.featureGroup([markerData[0].positions]);
// mapRef.firBounds(group.getBounds());
// console.log('oth position : ', markerData[0].positions);
// const map = mapRef.current;
// // console.log('map : ',map.leafletElement.flyTo);
// // var group = new L.featureGroup([L.marker(markerData[0].positions)]);
// // if (map) map.leafletElement.fitBounds(group.getBounds());
// if (map) {
// map.flyTo(markerData[0].positions, 10);
setFilteredMarkers(markerData);
})
.catch((err) => {
console.log('Err', err);
});
};
cityFilter();
}, [selectedCity]);
<Map
center={position}
zoom={5}
maxZoom={100}>
<LayersControl position='topright'>
<LayersControl.Overlay name='Markers' checked>
<LayerGroup>
<MyMarkersList markers={handleMarkers(markerData)} />
</LayerGroup>
</LayersControl.Overlay>
</LayersControl>
</Map>
當從下拉列表中選擇城市時,將調用 useEffect,然后它會根據所選城市為您提供標記位置,例如 [lat,log]。 從這一點開始,它應該飛到那個位置,並在可能的情況下獲取它周圍的邊界。
在setFilteredMarkers(markerData);
之前添加這兩行代碼setFilteredMarkers(markerData);
const {latitude, longitude} = geoCodes.find(g => g.city === selectedCity)
map.flyTo([ longitude,latitude], 12);
您想找到geoCodes
Object[]
所選城市的坐標。 您可以使用 array.find 使用 eselectedCity 的值來實現這一點。 每次下拉列表中的值更改時都會觸發此操作。
更新演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.