React-leaflet: Getting center of map after drag end

Created on 10 Nov 2015  路  8Comments  路  Source: PaulLeCam/react-leaflet

So right now I using Redux to store the state, and I am storing the center of the map in the state tree. I am having trouble with updating that value after the user moves the map, since even though I pass it an initial center prop, after the user moves the map the prop doesn't change, but the center of the map does. Also since onDragEnd doesn't expose the current lat long center. How would I go about getting the new center value?

question

Most helpful comment

For those who struggles to have a complete code example:

import React from 'react';
import { Map } from 'react-leaflet';

class MyComponent extends React.Component {
  onMove(event) {
    console.log(event.target.getCenter());
  }

  render() {
    return (
      <Map
        center={[45.75866, 4.85403]}
        zoom={12}
        style={{ height: '300px', width: '300px' }}
        onMoveEnd={this.onMove.bind(this)}
      >
        {/* ... */}
      </Map>
    );
  }
}

export default MyComponent;

All 8 comments

Hi,

You can use Leaflet's getCenter() to get the LatLng of the center of the map, accessing its instance on the Map component using its getLeafletElement() method.

I'm trying to do something similar -- every time the map moves I'd like to display the coordinates on screen. I understand how to listen for drags (e.g. <Map onDragend={this.handleDrag} />), but I'm not sure how to get a reference to the Leaflet object to call getCenter() on. My drag callback gets passed what appears to be an event object, but I'm not seeing any obvious references to the map.

Scratch that -- the map is e.target :)

@rbrtmrtn would you mind sharing how you did this? I'm trying to render the current map centre also, but having no success. Thanks

Hi @austere-rm, to be honest I can't really remember getting this to work but I think it involved listening to the onDragend event on the Map instance -- your callback will be passed an event object which has an attribute target. That's the Leaflet map object, and from there you should be able to call the native LeafletgetCenter` method to get the coords. Hope that helps!

Ok thanks @rbrtmrtn, I'll run with that and see how I go

For those who struggles to have a complete code example:

import React from 'react';
import { Map } from 'react-leaflet';

class MyComponent extends React.Component {
  onMove(event) {
    console.log(event.target.getCenter());
  }

  render() {
    return (
      <Map
        center={[45.75866, 4.85403]}
        zoom={12}
        style={{ height: '300px', width: '300px' }}
        onMoveEnd={this.onMove.bind(this)}
      >
        {/* ... */}
      </Map>
    );
  }
}

export default MyComponent;

For anyone looking for a complete solution on how to keep state of the map position, here is my solution:

type ViewPosition = Record<"lat" | "lon" | "zoom", number>

export const DashboardPage: React.FC = () => {
  const [loadingLocation, setLoadingLocation] = React.useState(true)
  const [userPosition, setUserPosition] = React.useState<Partial<ViewPosition>>({})
  const [viewPosition, setViewPosition] = React.useState<Partial<ViewPosition>>({})

  const setInitialUserLocation = ({ lat, lon }: Point) => {
    const zoom = 16
    setViewPosition({ lat, lon, zoom })
    setUserPosition({ lat, lon, zoom })
    setMapLink(`https://www.openstreetmap.org/#map=18/${lat}/${lon}`)
  }

  const onMove = (e: LeafletEvent) => {
    // magic happens here
    const { lat, lng: lon } = e.target.getCenter()
    // and here
    const zoom = e.target.getZoom()
    const updatedViewPosition = { lat, lon, zoom }
    return setViewPosition(updatedViewPosition)
  }

  const mapCenter = [viewPosition.lat, viewPosition.lon]  as LatLngExpression
  const userMarker = [userPosition.lat, userPosition.lon] as LatLngExpression

  <L.Map
    style={{ height: 500, width: "100%" }}
    center={mapCenter}
    // and here
    onmoveend={onMove}
    zoom={viewPosition.zoom}
    animate
  >
     {/* ... */}
  </L.Map>

The onMove function keeps the center of the map locked to your drag location, so it doesn't keep resetting every time the component rerenders.

Was this page helpful?
0 / 5 - 0 ratings