我正在尝试通过以下代码获取当前用户位置:
const OSMap: React.FC = () => {
const [mapState] = useState({ lat: 51.505, lng: -0.09, zoom: 13 })
const handleLocationFound = event => {
console.log('tesr', event.latLng)
}
return (
<Map
center={[mapState.lat, mapState.lng]}
onLocationfound={handleLocationFound}
zoom={mapState.zoom}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</Map>
)
}
handleLocationFound或handleLoad未被调用,这是我做错了吗?
没有可以传递onLocationfound
组件的Map
道具。参见here
我想您要实现的目标是在地图上发生onClick事件,并在单击该事件后获取坐标。您可以这样实现:
const OSMap: React.FC = () => {
const [mapState] = useState({ lat: 51.505, lng: -0.09, zoom: 13 })
const handleLocationFound = event => {
console.log('tesr', event.latlng)
}
return (
<Map
center={[mapState.lat, mapState.lng]}
onClick={handleLocationFound}
zoom={mapState.zoom}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
</Map>
)
}
通过将onLocationfound
替换为onClick
,将e.latLng
替换为e.latlng
Edit:我看了您的示例here,显然有一个onLocationfound
事件使我感到困惑,因为在本机传单中称为locationFound
,在react-leaflet中变成了onLocationFound
。如果您想实现示例中的某项功能,则在地理位置发生后,它便可以工作,您将收到事件对象,并访问坐标,您需要像我前面提到的那样使用e.latlng
。这是一个demo,可以现场观看。