如何将我的调度功能与React和React Leaflet放在一起,用于返回coords 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, 42],
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中,以便能够更改lat-long。

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} />,因为这会导致多个重发器,并且页面没有响应。不确定你想做什么。

演示

最新更新