繁体   English   中英

如何将 onClick 添加到 map `传单`

[英]How to add onClick to the map `leaflet`

我正在使用Leaflet我想显示一个警报,显示单击位置的纬度 我按照此处的文档步骤latlng ://leafletjs.com/examples/quick-start/

我试过这个

    var mymap = L.map('mapid').setView([51.505, -0.09], 13);

    function onMapClick(e) { //THE FUNCTION
      alert("You clicked the map at " + e.latlng);
      }

  mymap.on('click', onMapClick);

<MapContainer>我将它定义为

<MapContainer id="mapid" onClick={onMapClick}/>

但它什么也没显示

这是整个代码

import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'

import React, { Component } from 'react';
import L from 'leaflet'

class UserMap extends Component {

  render() {
    var mymap = L.map('mapid').setView([51.505, -0.09], 13);
    function onMapClick(e) {
      alert("You clicked the map at " + e.latlng);
  }
  mymap.on('click', onMapClick);
    return (
      <div
       id="mapid" style={{ height: '100%', width: '100%' }}>
        <MapContainer
       
          id="mapid"
          center={[30.794900, 50.564580]}
          zoom={13}
          zoomOffset={1}
          boxZoom={false}
          scrollWheelZoom={true}
          style={{ height: '500px', width: '100%' }}>
          <TileLayer
            attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
          />
          <Marker 
          position={[30.794900, 50.564580]}>
            <Popup>
              A pretty CSS3 popup. <br /> Easily customizable.
    </Popup>
          </Marker>
        </MapContainer></div>


    );
  }
}

export default UserMap;

onClick不再工作,您应该使用useMapEvents挂钩( https://react-leaflet.js.org/docs/api-map/#usemapevents )。

基本上,您必须使用useMapEvents挂钩创建一个组件,该挂钩将监听点击并在您的MapContainer中调用该组件。

MapContainer中添加以下代码以解决您的问题:

function MyComponent() {
    useMapEvents({
        click(e){
            alert(e.latlng)
        }
    })
}

暂无
暂无

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

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