繁体   English   中英

react-leaflet v4 在点击时设置和更改标记

[英]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='&copy; <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='&copy; <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='&copy; <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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM