gpt4 book ai didi

javascript - React-Leaflet Map 不更新

转载 作者:行者123 更新时间:2023-12-05 00:45:12 25 4
gpt4 key购买 nike

我的问题是 react-leaflet <MapContainer>不以我动态设置的位置为中心。基本逻辑是我有一个表格,我在其中输入街道和门牌号码,然后调用 Nominatim 并获取一些 JSON 格式的数据,从中提取建筑物的纬度和经度。这些经纬度我传递给我的<MapContainer>但它无论如何都没有回应。使用 react-leaflet v2 运行良好,但在我更新到 v3 后它停止了。

每当我设置默认位置值时,MapContainer 都会以该位置为中心。但是当我通过 Nominatim 调用动态传递另一个值时,它不起作用。

我在这里呼吁提名:

const getSearchData = async () => {
const exampleReq = `https://nominatim.openstreetmap.org/search/${query}?format=json&building=*&addressdetails=1&limit=1&polygon_geojson=1`;
const response = await fetch(exampleReq);
const data = await response.json();
// console.log(data);
if (data === undefined || data.length === 0) {
// array empty or does not exist
console.log("data array is empty");
alert("Given address unrecognized! Try again please.")
setLatitude(DEFAULT_LATITUDE);
setLongitude(DEFAULT_LONGITUDE);
}else{
setLatitude(data[0].lat);
setLongitude(data[0].lon);
}
};

这是我的表单提交:

<form className={style.searchForm} onSubmit={e => {
e.preventDefault();
setQuery(street + " " + houseNumber.replace(/\//g, "-") + ", Tallinn");
setPosition({
ltd: lat,
lng: long
});

这是我的 MapBox 组件,其中包含我的传单 map :

const MapBox = (props) => {

useEffect(()=>{
console.log("MAPBOX!");
console.log("updateMap() - lat ---> " + props.latitude);
console.log("updateMap() - long ---> " + props.longitude);
updateMap();
},[props.street, props.houseNumber]);

const passStreet = props.street;
const passHouseNumber = props.houseNumber;

const updateMap = () => {
// console.log("updateMap() - lat ---> " + props.latitude);
// console.log("updateMap() - long ---> " + props.longitude);
return(
<MapContainer center={[props.latitude, props.longitude]} zoom={20}>
<TileLayer
url='https://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<OverpassLayer street={passStreet} houseNumber={passHouseNumber} />
</MapContainer>
);
}

return(
updateMap()
);
}

最佳答案

我能够解决它。在文档中它被声明为:

Except for its children, MapContainer props are immutable: changing them after they have been set a first time will have no effect on the Map instance or its container.The Leaflet Map instance created by the MapContainer element can be accessed by child components using one of the provided hooks or the MapConsumer component.

这段代码有助于理解:

function MyComponent() {
const map = useMap()
console.log('map center:', map.getCenter())
return null
}

function MyMapComponent() {
return (
<MapContainer center={[50.5, 30.5]} zoom={13}>
<MyComponent />
</MapContainer>
)
}

我实现了什么:

function MyComponent(props) {
const map = useMap();
map.setView(props.center, props.zoom);
return null;
}

关于javascript - React-Leaflet Map 不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64736789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com