获取点击位置经纬度

Get clicked location latitude and longitude

我有这个 React 代码:

import React, { Component } from 'react';
import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import './Map.css';
import L from 'leaflet';
import { geolocated } from 'react-geolocated';

class Map extends Component {
    render() {
        const DEFAULT_LATITUDE = 32.313268;
        const DEFAULT_LONGITUDE = 35.022895;
        const latitude = this.props.coords ? this.props.coords.latitude : DEFAULT_LATITUDE;
        const longitude = this.props.coords ? this.props.coords.longitude : DEFAULT_LONGITUDE;

        return (
            <MapContainer className="leaflet-map" center={[latitude, longitude]} zoom={17} scrollWheelZoom={true}>
                <TileLayer
                    attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                    url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                />
                <Marker position={[latitude, longitude]}>
                    <Popup>
                        Here you are ^_^
                            </Popup>
                </Marker>
            </MapContainer>
        );
    }
}

export default Map;

如何添加事件来获取点击地图时所在位置的经纬度? 在传单文档中有类似的内容:

map.on('click', function(e) {
    alert("Lat, Lon : " + e.latlng.lat + ", " + e.latlng.lng)
});

但是我如何使用 ReactJS 做到这一点?

首先使用 MapContainer 上的 whenCreated 属性获取地图实例

<MapContainer
  className="leaflet-map"
  center={[latitude, longitude]}
  zoom={17}
  scrollWheelZoom={true}
  style={{ height: "100vh" }}
  whenCreated={(map) => this.setState({ map })}
 >

第二次在 componentDidUpdate 上使用它,当它被定义为监听地图点击事件时

componentDidUpdate(prevProps, prevState) {
    const { map } = this.state;
    if (prevState.map !== map && map) {
      map.on("click", function (e) {
        alert("Lat, Lon : " + e.latlng.lat + ", " + e.latlng.lng);
      });
    }
  }

Demo