简体   繁体   English

如何在leaflet反应js中获取当前鼠标点击的坐标

[英]How to get coordinates of current mouse click in leaflet react js

I'm trying to get coordinates of where the mouse clicks on the map but.locate() only returns the center coordinates of the map.我正在尝试获取鼠标在 map 上单击的坐标,但.locate() 仅返回 map 的中心坐标。 Is there a way?有办法吗? ps.附言。 I am not using class based react.我没有使用基于 class 的反应。 Thanks谢谢

 <MapContainer
          center={[ 33.8735578, 35.86379]}
        zoom={9}
        scrollWheelZoom={true}
  
      >
        <TileLayer
          attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
</MapContainer>

Question and where is your code?问题,你的代码在哪里? You are not new to this site so you should know to show what you have done so far.您对这个网站并不陌生,所以您应该知道展示您到目前为止所做的事情。 Okay, I will be gracious today;) I don't want to cut and clean the code, so I paste as is.好的,我今天会很客气;)我不想剪切和清理代码,所以我按原样粘贴。

import { useEffect } from 'react';
import { MapContainer, useMap, TileLayer, } from 'react-leaflet';
import L from 'leaflet';
import tileLayer from '../util/tileLayer';

const center = [52.22977, 21.01178];

const GetCoordinates = () => {
  const map = useMap();

  useEffect(() => {
    if (!map) return;
    const info = L.DomUtil.create('div', 'legend');

    const positon = L.Control.extend({
      options: {
        position: 'bottomleft'
      },

      onAdd: function () {
        info.textContent = 'Click on map';
        return info;
      }
    })

    map.on('click', (e) => {
      info.textContent = e.latlng;
    })

    map.addControl(new positon());

  }, [map])


  return null

}

const MapWrapper = () => {
  return (
    <MapContainer center={center} zoom={18} scrollWheelZoom={false}>
      <TileLayer {...tileLayer} />

      <GetCoordinates />

    </MapContainer>
  )
}

export default MapWrapper;

you can get coordinates of mouse click by useMapEvents hook.您可以通过useMapEvents钩子获取鼠标点击的坐标。

try this one.试试这个。

const MapEvents = () => {
    useMapEvents({
      click(e) {
        // setState your coords here
        // coords exist in "e.latlng.lat" and "e.latlng.lng"
        console.log(e.latlng.lat);
        console.log(e.latlng.lng);
      },
    });
    return false;
}

    return (
       <MapContainer
          center={[ 33.8735578, 35.86379]}
          zoom={9}
          scrollWheelZoom={true}
       >
          <TileLayer
          attribution='&copy; <a 
           href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
           url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
            <MapEvents />
    </MapContainer>
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM