Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

286
Visualizações
React-Leaflet: Set marker when clicking on the map

I am developing a React app on my Ubuntu 20.4 VM machine in a chrome Version 100.0.4896.127 (Official Build) (64-bit) browser.

I have created the following app:

https://codesandbox.io/s/react-leaflet-map-with-marker-forked-vtq00e?file=/Map.js

I am trying to set a marker when clicking on the map using the following:

In my Map.js I set the click event:

  return (
    <div id="map" style={style}>
      <MapContainer
        // center={[40.0151, -105.2921]}
        center={[40.7579747, -73.9877313]}
        // @ts-ignore
        onClick={addMarker}
        zoom={15}
        style={{ height: "90%" }}
        // @ts-ignore
        onZoomEnd={console.log}
      >

The following function should then set the marker:

function addMarker(e) {
  console.log("marker \n");

  const { markers } = this.state;
  markers.pop();
  markers.push(e.latlng);
  this.setState({ markers });
}

However, when I click on the map nothing is happening. I also do not get a console output.

Any suggestions what I am doing wrong?

I appreciate your replies!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There is a reason why TypeScript tells you that onClick and onZoomEnd props are not available on <MapContainer> component from React Leaflet: the latter was introduced in React Leaflet version 3, and map events should now be used through the useMapEvents hook, as you already have tried in some of your attempts as can be seen in your CodeSandbox.

What may not be obvious with the useMapEvents hook, is that it must be used in a custom component that will be a child (descendant) of your MapContainer. See e.g. Trying to apply zoom on click with react-leaflet

Furthermore, this.setState is typical of class-based React components, whereas in your CodeSandbox you use functional components. Note that hooks can only be used in functional React components.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda