【发布时间】:2021-03-28 03:31:53
【问题描述】:
我现在正在使用 React Leaflet,我需要获取我在地图上单击的位置的坐标。当我用谷歌搜索它时,我只能找到 latlng 作为解决方案,但这不起作用。有任何想法吗? TIA
【问题讨论】:
我现在正在使用 React Leaflet,我需要获取我在地图上单击的位置的坐标。当我用谷歌搜索它时,我只能找到 latlng 作为解决方案,但这不起作用。有任何想法吗? TIA
【问题讨论】:
我找到了一个解决方案,附上了可以帮助您解决问题的代码。
import React, {useState} from "react";
import {Map, Marker, TileLayer} from "react-leaflet";
const style = {
height: '400px',
width: '100%'
};
export const Ubication = () => {
const [position] = useState([-0.22021954674229854, -78.5127639770508]);//position intitial of map
const [marker, setMarker] = useState({lat: 0, lng: 0});
function changeUbication(e) {
let {lat, lng} = e.latlng;
console.info("Lat:", lat);
console.info("Lng: ",lng);
setMarker(e.latlng);
}
return (
<div id="map">
<Map center={position}
zoom={13}
onClick={changeUbication}
style={style}>
<TileLayer
url='https://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'/>
{(marker.lat !== 0 && marker.lng !== 0) &&
<Marker position={[marker.lat, marker.lng]}>
</Marker>}
</Map>
</div>)
}
【讨论】: