[英]React leaflet map center not changing
我正在設置一個 map 來查找一個人的坐標,然后將該位置放在 map 上。 但由於某種原因,map 上沒有顯示坐標。 我 console.log 以確保 state 變量(存儲坐標的位置)發出正確的坐標並且它們是正確的。 我不知道為什么 map 不會改變它們。
我的代碼:
import { StatusBar } from "expo-status-bar";
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import Constants from "expo-constants";
import * as Location from "expo-location";
import * as Permissions from "expo-permissions";
import { render } from "react-dom";
import "leaflet/dist/leaflet.css";
export default class App extends React.Component {
constructor() {
super();
this.state = {
ready: false,
where: { lat: '', lng: '' },
error: null,
};
}
componentDidMount() {
let geoOptions = {
enableHighAccuracy: true,
timeOut: 20000,
maximumAge: 60 * 60 * 24,
};
this.setState({ ready: false, error: null });
navigator.geolocation.getCurrentPosition(
this.geoSuccess,
this.geoFailure,
geoOptions
);
}
geoSuccess = (position) => {
console.log(position.coords.latitude);
console.log(position.coords.longitude);
console.log(this.state.where?.lng);
console.log(this.state.where?.lat);
this.setState({
ready: true,
where: { lat: position.coords.latitude, lng: position.coords.longitude
},
});
console.log(this.state.where?.lng);
console.log(this.state.where?.lat);
};
geoFailure = (err) => {
this.setState({ error: err.message });
console.log(this.state.error);
};
render() {
const position = [this.state.where?.lat, this.state.where?.lng];
return (
<>
{(this.state.where != null || this.state.where != undefined) &&
<MapContainer
style={{ height: "100%", width: "100%" }}
center={position}
zoom="30"
scrollWheelZoom={true}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</MapContainer>
}
</>
);
}
}
來自官方文檔
除了它的孩子, MapContainer 道具是不可變的:在它們第一次設置后更改它們不會對 Map 實例或其容器產生影響。
使用將在 position 更改時更改您的 map 視圖的子組件
function ChangeMapView({ coords }) {
const map = useMap();
map.setView(coords, map.getZoom());
return null;
}
像這樣使用它:
<MapContainer
style={{ height: "100vh", width: "100%" }}
center={position}
zoom="30"
scrollWheelZoom={true}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<ChangeMapView coords={position} />
</MapContainer>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.