如何解决点击地图获取经度和纬度
我正在使用React Leaflet做一个小应用程序,我想每次单击某处时在地图上添加一个标记,
我不知道该怎么做,我在下面尝试了一些操作,但是控制台日志未返回任何内容,
function App() {
const [position,setPosition] = useState([48.8534,2.3488]);
const [markers,setMarkers] = useState([]);
function addMarker(e) {
console.log("e",e);
const newMarker = e;
setMarkers([...markers,newMarker]);
}
return (
<div className="App" style={{ width: "100%",height: "100vh" }}>
<MapContainer
center={position}
zoom={6}
scrollWheelZoom={true}
style={{ width: "100%",height: "100vh" }}
onClick={addMarker}
>
<MyComponent />
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
{markers &&
markers.map((marker,index) => {
<Marker key={`marker-${index}`} position={marker}>
<Popup>
<span>Popup</span>
</Popup>
</Marker>;
})}
</MapContainer>
</div>
);
}
export default App;
解决方法
react-leaflet刚刚更新为版本3,该版本不再支持onClick
之类的内联事件。您需要使用useMapEvents
挂钩。示例here。
import { MapContainer,useMapEvents } from 'react-leaflet'
function AddMarkerToClick() {
const [markers,setMarkers] = useState([]);
const map = useMapEvents({
click(e) {
const newMarker = e.latlng
setMarkers([...markers,newMarker]);
},})
return (
<>
{markers.map(marker =>
<Marker position={marker}>
<Popup>Marker is at {marker}</Popup>
</Marker>
)}
</>
)
}
function App() {
return (
<div className="App" style={{ width: "100%",height: "100vh" }}>
<MapContainer {...} > {/* omit onClick */}
<AddMarkerToClick />
</MapContainer>
</div>
);
}
export default App;
我还没有机会进行测试,但这应该可以给您一个想法。
,从“反应”中导入React,{备忘录,useEffect,useState}
从'react-leaflet'导入{Map,TileLayer} 导入'leaflet / dist / leaflet.css' 从“ ./Markers”导入标记
const initialState =({ lat:'18 .4942031', lng:“-69.8919176”, 缩放:“ 13” })
export const MapView = memo(({{dataMap,searchHistory})=> {
const [ properties,setProperties ] = useState(initialState)
const setPropertiesOnMap = () =>{
setTimeout(function(){
setProperties({
lat: dataMap[0]?.latitude || '18.4942031',lng: dataMap[0]?.longitude || '-69.8919176',zoom: '18',})
},500)
}
useEffect(() =>{
if(dataMap.length === 1){
setPropertiesOnMap()
}else{
setProperties(initialState)
}
//eslint-disable-next-line
},[dataMap])
return (
<Map center={{lat: properties.lat,lng: properties.lng}} zoom={properties.zoom} minZoom={8}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{dataMap[0] && <Markers dataMap={dataMap} searchHistory={searchHistory} />}
</Map>
)
})
我做了类似的事情,希望它可以为您提供帮助
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。