react-leaflet get current latlng onClick

M.Alish picture M.Alish · Feb 3, 2019 · Viewed 10.1k times · Source

I would be realy happy if some one could help me... I've installed react-leaflet on my react project and the map component is loaded successfully, i need to get current latlng and show it in the Popup when i click on map but I don't know how to :(

please... please... help me...

this is my code

import React from 'react'
import { Map as LeafletMap, TileLayer, Marker, Popup } from 'react-leaflet';

class Mapp extends React.Component {
    componentDidMount() {

    }

    render() {
        return (
            <LeafletMap
                center={[35.755229,51.304470]}
                zoom={16}
                maxZoom={20}
                attributionControl={true}
                zoomControl={true}
                doubleClickZoom={true}
                scrollWheelZoom={true}
                dragging={true}
                animate={true}
                easeLinearity={0.35}
            >
                <TileLayer
                    url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
                />
                <Marker position={[35.755229,51.304470]}
                draggable={true}
                >
                    <Popup >
                        Popup for any custom information.
                    </Popup>

                </Marker>
            </LeafletMap>
        );
    }
}

export default Mapp;

Answer

Vadim Gremyachev picture Vadim Gremyachev · Feb 3, 2019

Here is an example on how to display maker position in popup once map is clicked:

class MapExample extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPos: null
    };
    this.handleClick = this.handleClick.bind(this);
  }


  handleClick(e){
    this.setState({ currentPos: e.latlng });
  }

  render() {
    return (
      <div>
        <Map center={this.props.center} zoom={this.props.zoom} onClick={this.handleClick}>
          <TileLayer
              url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
          />
          { this.state.currentPos && <Marker position={this.state.currentPos} draggable={true}>
            <Popup position={this.state.currentPos}>
              Current location: <pre>{JSON.stringify(this.state.currentPos, null, 2)}</pre>
            </Popup>
          </Marker>}
        </Map>
      </div>
    )
  }
}

Explanation:

  • currentPos state is used to keep marker position
  • event.latLng property of Map.onClick event handler returns mouse event location

Here is a demo for your reference