如何解决如何使用 React 和 React Leaflet 放置我的调度函数以获得返回坐标 lat + lng
我有一个输入(在子组件上)通过道具(文本)返回坐标:
import React,{ useEffect,useState,useRef,useMemo } from 'react'
import { useEnderecoValue } from '../../contexts/EnderecoContext'
import 'leaflet/dist/leaflet.css'
import Leaflet from 'leaflet'
import { MapContainer,Marker,useMap,TileLayer,Popup } from 'react-leaflet'
export default function App(text: any) {
const [lat,setLat] = useState(48.856614)
const [lng,setLng] = useState(2.3522219)
const [state,dispatch] = useEnderecoValue()
const icon = new Leaflet.DivIcon({
className: 'custom-div-icon',html:
"<div style='background-color:#c30b82;' class='marker-pin'></div><i class='material-icons'><img src='img/marker-icon.png'></i>",iconSize: [30,42],iconAnchor: [15,popupAnchor: [-3,-42]
})
useEffect(() => {
if (text.text) {
setLat(text.text.features[0].geometry.coordinates[1])
setLng(text.text.features[0].geometry.coordinates[0])
}
},[text])
function SetViewOnClick({ coords }: any) {
const map = useMap()
map.flyTo(coords,map.getZoom())
return null
}
我的标记是可拖动的,如果我在输入时搜索地址或标记被拖动,则会弹出显示地址和坐标:
const markerRef = useRef(null)
const eventHandlers = useMemo(
() => ({
dragend() {
const marker = markerRef.current
if (marker != null) {
const { lat,lng } = marker.getLatLng()
setLat(lat)
setLng(lng)
}
}
}),[]
)
const popup = () => {
if (text.text) {
return text.text.query + ' ' + `lat: ${lat},long: ${lng}`
}
return (
"Address by default" +
' ' +
`lat: ${lat},long: ${lng}`
)
}
return (
<MapContainer
center={[lat,lng]}
attributionControl={false}
zoomControl={false}
zoom={18}
style={{
height: '350px',position: 'relative',outline: 'none',maxWidth: '696px',display: 'block',margin: '15px auto',width: '100%'
}}
>
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
<Marker
position={[lat,lng]}
icon={icon}
draggable={true}
ref={markerRef}
eventHandlers={eventHandlers}
>
<Popup>
<span>{popup()}</span>
</Popup>
<SetViewOnClick coords={[lat,lng]} />
</Marker>
</MapContainer>
)
}
如何在搜索地址和拖动标记时放置返回坐标的调度函数? (就在值改变时)
dispatch({
type: 'SET_COORDS',latitude: lat,longitude: lng
})
解决方法
在 searchLocation
内的 Search comp place dispatch 可以更改经纬度。
const searchLocation = async () => {
fetch(
"https://api-adresse.data.gouv.fr/search?" +
new URLSearchParams({
q: state.location,})
)
.then((data) => data.json())
.then((text) => {
setResp({ text });
dispatch({
type: "SET_COORDS",latitude: text.features[0].geometry.coordinates[1],longitude: text.features[0].geometry.coordinates[0],});
})
.catch(function (error) {
console.log("request failed",error);
});
};
将 <Map {...resp} />
替换为 <Map text={resp} />
,因为它会导致多次重新呈现并且页面变得无响应。不确定你想做什么。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。