Getting latitude and longitude of a marker in react-leaflet

3.3k views Asked by At

I'm trying to get the latitude and longitude of a marker in react-leaflet, but can't seem to figure out how. In Leaflet, there is a function for it but I can't figure out how to call that in react-leaflet.

My goal is to have a marker on the map (fixed location) and another draggable one. When you drag the marker, it will print the coordinates to console onDragEnd and then tell you the distance between the two. I've been reading the documentation and looking at the code, but can't seem to implement this in my React component.

Any help is greatly appreciated.

1

There are 1 answers

0
pilchard On BEST ANSWER

As per the react-leaflet component docs:

You can directly access the Leaflet element created by a component using this.leafletElement in the component. This leaflet element is usually created in componentWillMount() and therefore accessible in componentDidMount(), except for the Map component where it can only be created after the container is rendered.

Components


Here's a quick minimal example which assigns a ref to the marker and watches for the dragEnd event.

React-Leaflet example

.leaflet-container {
  height: 70vh;
  width: 100vw;
}
<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://unpkg.com/react-leaflet/dist/react-leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<script type="text/babel">
const { useState, useRef, useEffect } = React;
const { Map, TileLayer, Marker } = window.ReactLeaflet

function MapComp() {
  const [markerPos, setMarkerPos] = useState({
    lat: 55.702868,
    lng: 37.530865,
  })
  const [fixedMarkerPos, setFixedMarkerPos] = useState({
    lat: 55.7518300742972,
    lng: 37.71057128906251,
  })
  
  useEffect(() => {
    console.log(`lat diff: ${markerPos.lat - fixedMarkerPos.lat}, lng diff: ${markerPos.lng - fixedMarkerPos.lng}`);
  },[markerPos, fixedMarkerPos])

  const markerRef = useRef();
  const fixedMarkerRef = useRef();
  
  const updatePosition = () => {
    const marker = markerRef.current
    if (marker != null) {
      const newPos = {...marker.leafletElement.getLatLng()};
      setMarkerPos(newPos);
    }
  }

    return (
      <Map zoom={9} center={[55.74101998457737, 37.62268066406251]}>
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
        
        <Marker
          position={[markerPos.lat, markerPos.lng]}
          draggable={true}
          onDragend={updatePosition}
          ref={markerRef}
        />
        <Marker
          position={[fixedMarkerPos.lat, fixedMarkerPos.lng]}
          ref={fixedMarkerRef}
        />
      </Map>
    );
}

ReactDOM.render(<MapComp />, document.getElementById('root'));
</script>

<div id="root"></div>