Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

284
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda