简体   繁体   English

React-Leaflet:点击 map 时设置标记

[英]React-Leaflet: Set marker when clicking on the map

I am developing a React app on my Ubuntu 20.4 VM machine in a chrome Version 100.0.4896.127 (Official Build) (64-bit) browser.我正在使用 chrome 版本 100.0.4896.127(官方构建)(64 位)浏览器在我的 Ubuntu 20.4 VM 机器上开发 React 应用程序。

I have created the following app:我创建了以下应用程序:

https://codesandbox.io/s/react-leaflet-map-with-marker-forked-vtq00e?file=/Map.js https://codesandbox.io/s/react-leaflet-map-with-marker-forked-vtq00e?file=/Map.js

I am trying to set a marker when clicking on the map using the following:我正在尝试使用以下方法在点击 map 时设置一个标记:

In my Map.js I set the click event:在我的Map.js我设置了点击事件:

  return (
    <div id="map" style={style}>
      <MapContainer
        // center={[40.0151, -105.2921]}
        center={[40.7579747, -73.9877313]}
        // @ts-ignore
        onClick={addMarker}
        zoom={15}
        style={{ height: "90%" }}
        // @ts-ignore
        onZoomEnd={console.log}
      >

The following function should then set the marker:下面的 function 应该设置标记:

function addMarker(e) {
  console.log("marker \n");

  const { markers } = this.state;
  markers.pop();
  markers.push(e.latlng);
  this.setState({ markers });
}

However, when I click on the map nothing is happening.但是,当我点击 map 时,什么也没有发生。 I also do not get a console output.我也没有得到控制台 output。

Any suggestions what I am doing wrong?有什么建议我做错了吗?

I appreciate your replies!感谢您的回复!

There is a reason why TypeScript tells you that onClick and onZoomEnd props are not available on <MapContainer> component from React Leaflet: the latter was introduced in React Leaflet version 3, and map events should now be used through the useMapEvents hook, as you already have tried in some of your attempts as can be seen in your CodeSandbox. TypeScript 告诉您onClickonZoomEnd道具在 React Leaflet 的<MapContainer>组件上不可用是有原因的:后者是在 React Leaflet 版本 3 中引入的,现在应该已经通过useMapEvents钩子使用了 map 事件在您的 CodeSandbox 中可以看到,您已经尝试了一些尝试。

What may not be obvious with the useMapEvents hook, is that it must be used in a custom component that will be a child (descendant) of your MapContainer. useMapEvents挂钩可能不明显的是,它必须在将成为 MapContainer 的(后代)的自定义组件中使用。 See eg Trying to apply zoom on click with react-leaflet请参阅例如尝试使用 react-leaflet 对单击应用缩放

Furthermore, this.setState is typical of class-based React components, whereas in your CodeSandbox you use functional components.此外, this.setState是典型的基于类的React 组件,而在您的 CodeSandbox 中,您使用的是功能组件。 Note that hooks can only be used in functional React components.请注意,钩子只能在功能性 React 组件中使用。

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

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