VersifiXion
VersifiXion

Reputation: 2282

Get latitude and longitude on click on Map

I'm doing a little app using React Leaflet, and I want to add a marker on the map every time I click somewhere,

I don't know how to do it, I tried something below but the console log doesn't return something,

function App() {
  const [position, setPosition] = useState([48.8534, 2.3488]);
  const [markers, setMarkers] = useState([]);

  function addMarker(e) {
    console.log("e", e);
    const newMarker = e;
    setMarkers([...markers, newMarker]);
  }

  return (
    <div className="App" style={{ width: "100%", height: "100vh" }}>
      <MapContainer
        center={position}
        zoom={6}
        scrollWheelZoom={true}
        style={{ width: "100%", height: "100vh" }}
        onClick={addMarker}
      >
        <MyComponent />
        <TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
        {markers &&
          markers.map((marker, index) => {
            <Marker key={`marker-${index}`} position={marker}>
              <Popup>
                <span>Popup</span>
              </Popup>
            </Marker>;
          })}
      </MapContainer>
    </div>
  );
}

export default App;

Upvotes: 1

Views: 3341

Answers (2)

user14663947
user14663947

Reputation: 1

import React, { memo, useEffect, useState } from 'react'

import { Map, TileLayer } from 'react-leaflet' import 'leaflet/dist/leaflet.css' import Markers from './Markers'

const initialState = ({ lat: '18.4942031', lng: '-69.8919176', zoom: '13' })

export const MapView = memo(({dataMap, searchHistory}) => {

const [ properties, setProperties ] = useState(initialState)

const setPropertiesOnMap = () =>{
    setTimeout(function(){
        setProperties({
            lat: dataMap[0]?.latitude || '18.4942031',
            lng: dataMap[0]?.longitude || '-69.8919176',
            zoom: '18',
        })
    },500)
}

useEffect(() =>{
    if(dataMap.length === 1){
        setPropertiesOnMap()
    }else{
        setProperties(initialState)
    }
//eslint-disable-next-line
},[dataMap])

return (
    <Map center={{lat: properties.lat, lng: properties.lng}} zoom={properties.zoom} minZoom={8}>
        <TileLayer 
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
        />
        {dataMap[0] && <Markers dataMap={dataMap} searchHistory={searchHistory} />}
    </Map>
)

})

I did something similar, I hope it can help you

Upvotes: 0

Seth Lutske
Seth Lutske

Reputation: 10676

react-leaflet just updated to version 3, which no longer support inline events like onClick. You need to use the useMapEvents hook. Example here.

import { MapContainer, useMapEvents } from 'react-leaflet'

function AddMarkerToClick() {

  const [markers, setMarkers] = useState([]);

  const map = useMapEvents({
    click(e) {
      const newMarker = e.latlng
      setMarkers([...markers, newMarker]);
    },
  })

  return (
    <>
      {markers.map(marker => 
        <Marker position={marker}>
          <Popup>Marker is at {marker}</Popup>
        </Marker>
      )}
    </>
  )
}

function App() {

  return (

    <div className="App" style={{ width: "100%", height: "100vh" }}>
      <MapContainer {...} > {/* omit onClick */}
        <AddMarkerToClick />
      </MapContainer>
    </div>

  );
}

export default App;

I didn't get a chance to test this yet, but this should give you an idea.

Upvotes: 4

Related Questions