[英]react-leaflet v4 set and change marker on click
我無法在點擊時設置和更改標記。
我從瀏覽器中獲取用戶的位置,並使用這些坐標將 map 居中。 當我運行 console.log(coords) 我可以看到瀏覽器拾取的坐標,但是當我 go 使用 [formValues.coords[0], formValues.coords[1]] 將標記設置為 LatLngExpression 它沒有工作。 當我點擊 map 時,它也沒有改變坐標。 我做錯了什么,但我還沒弄清楚在哪里。
我看到的另一件事是 whenCreated 屬性已從 react-leaflet v4 中刪除:
“從 MapContainer 組件中刪除了 whenCreated 屬性(可以使用 ref 回調)。”
但我不知道如何在這種情況下使用這個 ref 回調。
誰能幫我? 這是map渲染部分中的代碼:
import {
Button,
ButtonContainer,
CategoryBox,
CategoryContainer,
CategoryImage,
Container,
Form,
FormTitle,
MapContainer,
Section,
} from "./styles";
import Input from "../../components/Input";
import { useState } from "react";
import { LatLngExpression, LeafletMouseEvent } from "leaflet";
import { TileLayer, Marker } from "react-leaflet";
import { categories } from "./categories";
import useGetLocation from "../../hooks/useGetLocation";
import { toast } from "react-toastify";
import { useNavigate } from "react-router-dom";
export default function New() {
const navigate = useNavigate();
const [formValues, setFormValues] = useState({
name: "",
description: "",
contact: "",
category: "",
coords: [0, 0],
});
const { coords } = useGetLocation();
console.log(coords);
async function onSubmit() {
const request = await fetch("http://localhost:5000/store", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
...formValues,
latitude: formValues.coords[0],
longitude: formValues.coords[1],
}),
});
if (request.ok) {
toast("Estabelecimento gravado com sucesso!", {
type: "success",
autoClose: 2000,
onClose: () => navigate("/"),
});
}
}
if (!coords) {
return <h1>Obtendo localização...</h1>;
}
return (
<Container>
<Form
onSubmit={(ev) => {
ev.preventDefault();
onSubmit();
}}
>
<FormTitle>Cadastro do comércio local</FormTitle>
<Section>Dados</Section>
<Input
label="Nome do local"
name="name"
value={formValues.name}
onChange={setFormValues}
/>
<Input
label="Descrição"
name="description"
value={formValues.description}
onChange={setFormValues}
/>
<Input
label="Contato"
name="contact"
value={formValues.contact}
onChange={setFormValues}
/>
<Section>Endereço</Section>
<MapContainer
center={
{
lat: coords[0],
lng: coords[1],
} as LatLngExpression
}
zoom={13}
whenCreated={(map) => {
map.addEventListener("click", (event: LeafletMouseEvent) => {
setFormValues((prev) => ({
...prev,
coords: [event.latlng.lat, event.latlng.lng],
}));
});
}}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker
position={
[formValues.coords[0], formValues.coords[1]] as LatLngExpression
}
/>
</MapContainer>
<Section>Categoria</Section>
<CategoryContainer>
{categories.map((category) => (
<CategoryBox
key={category.key}
onClick={() => {
setFormValues((prev) => ({ ...prev, category: category.key }));
}}
isActive={formValues.category === category.key}
>
<CategoryImage src={category.url} />
{category.label}
</CategoryBox>
))}
</CategoryContainer>
<ButtonContainer>
<Button type="submit">Salvar</Button>
</ButtonContainer>
</Form>
</Container>
);
}
是的,所以WhenCreated
不再是道具了。 而且我認為有一種更簡單的方法,它不涉及弄亂ref
。 您需要做的第一件事是移動您的 map 容器,使其成為包裝器,然后您可以使用類似這樣的方法將標記移動到您單擊的任何位置:
function MovingMarker() {
const [position, setPosition] = useState(center)
const markerRef = useRef(null)
const map = useMapEvent('click', (e) => {
console.log("click")
setPosition(e.latlng)
})
return (
<Marker
position={position}
ref={markerRef}>
</Marker>
)
}
render(
<MapContainer center={center} zoom={13} scrollWheelZoom={false}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MovingMarker />
</MapContainer>
)
如果您想在現場環境中使用它,可以在https://react-leaflet.js.org/docs/api-map/上運行此演示。 如果您需要將標記的坐標向上MapContainer
之外,那么我建議在MovingMarker
組件中添加一個類似onChange={(e)=>{setGlobalMarkerPos(e)}}
的道具。 這樣,任何更改都將向上傳播到組件堆棧。 或者您可以使用上下文管理器。
另一種解決方案是獲取對 map 的引用:
function RealMapContainer() {
const [position, setPosition] = useState(center)
const [listenerSetup, setListenerSetup] = useState(null)
const mapRef = useRef(null)
if(mapRef.current && !listenerSetup){
console.log(mapRef);
mapRef.current.on('click', (e)=>{
setPosition(e.latlng)
})
setListenerSetup(true)
}
//if we still haven't setup the listener,
//then setListenerSetup(false) is just a way to make this
//component keep rendering over and over until the reference
//is finally defined and the listener can be set up
else if(!listenerSetup){
setTimeout(()=>{
setListenerSetup(false)
}, 100)
}
return (
<MapContainer center={center} zoom={13} scrollWheelZoom={false} ref={mapRef}>
<TileLayer
attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}/>
</MapContainer>
)
}
然后,您將獲得對 MapObject 的實際引用,並以 vanilla leaflet 文檔指定的所有方式使用它。
我添加了一個用於移動標記 position 的點擊處理程序。 listenerSetup
的整個過程只是一種愚蠢的方法,可以讓事情繼續重新渲染,直到找到對 map object 的引用。 我幾乎只使用基於類的 React,所以我確信有更好的方法,但它有效。 如果有人閱讀本文知道更好的方法,請發表評論並讓我知道,以便我更新。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.