簡體   English   中英

如何在 react-leaflet v.3.x 中使用 dbclick 顯示點列表?

[英]How to display a list of points using dbclick in react-leaflet v.3.x?

我對反應很陌生,我想做的基本上只是在 map 上顯示一組點。 我有一個名為 CovidPoints 的自定義組件,它基本上只是在 map 上呈現一個標記。 目前我有一個 function 組件,它檢測何時發生雙擊,然后在鼠標 position 上創建一個點。 現在發生的情況是該點僅在第一次雙擊后創建。 我希望能夠多次雙擊並每次創建點。 為此,我認為我需要 append 將位置標記 function 返回到點數組道具,但我不知道該怎么做。

位置標記.js:

import {useState} from 'react';
import {useMapEvents, Marker, Popup} from 'react-leaflet';
import CovidPoint from './CovidPoint';

function LocationMarker() {
    const [points, setPoints] = useState(null)
    const [position, setPosition] = useState(null)
    const map = useMapEvents({
        dblclick(ev) {
            console.log("double clicked");
            const coord = map.mouseEventToLatLng(ev.originalEvent);
            setPosition(coord);
        },
    })
    
    return position === null ? null : (
      <CovidPoint position={position}></CovidPoint>
    )
  }

  export default LocationMarker;

應用程序.js:

import './App.css';
import * as React from "react";
import { ChakraProvider } from "@chakra-ui/react";
import { MapContainer, TileLayer, Marker, Popup, useMapEvents, useMap } from 'react-leaflet'
import 'leaflet/dist/leaflet.css'
import * as L from 'leaflet';
import SearchBar from './SearchBar';
import CovidPoint from './CovidPoint';
import LocationMarker from './LocationMarker';

class App extends React.Component {
  constructor(props){
    super(props)
    this.state = {
      map: null,
      points: []
    }
  }

  changePos = (pos, zoom) => {
    const {map} = this.state;
    if (map) map.flyTo(pos, zoom);
  }

  render () {

    return (
      <ChakraProvider resetCSS = {false}>
        <div className = "App">
          <div id="title">
            <h1>
              CovidStopSpots
            </h1>
              <p>A responsive tracker for Covid-19.</p>          
          </div>
          <div id="map">
            <MapContainer id = "1" center={[43.653226, -79.3831843]} zoom={13} scrollWheelZoom={false} whenCreated={map => this.setState({ map })}>
              <TileLayer
                attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              />
             <CovidPoint position={[43.653226, -79.3831843]} name="point1" information="random point"></CovidPoint>
             <CovidPoint position={[50.653226, -79.3831843]} name="point2" information="random point"></CovidPoint>
             <LocationMarker></LocationMarker>
            </MapContainer>
            <div id="searchbar">
            <SearchBar changePos = {this.changePos}></SearchBar>
            </div>
          </div>
      </div>
      </ChakraProvider>
    )
  }
}

export default App;

CovidPoint.js:

import './SearchBar.css';
import * as React from "react";
import { MapContainer, Marker } from 'react-leaflet';
import * as L from 'leaflet';
import { Popup } from 'react-leaflet';

class CovidPoint extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      positon: this.props.position,
      name: this.props.name,
      information: this.props.information,
    }
  }
  

  render () {
    const covidIcon = L.icon({
      iconUrl: 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/e5/Redpoint.svg/768px-Redpoint.svg.png',
  
      iconSize:     [30, 30], // size of the icon
      iconAnchor:   [0, 0], // point of the icon which will correspond to marker's location
      popupAnchor:  [0, 0] // point from which the popup should open relative to the iconAnchor
  });

    return (
    <div>
      <Marker position={this.state.positon} icon={covidIcon}>
        <Popup>
          Name: {this.state.name} <br />
          Case Status: {this.state.information}
        </Popup>
      </Marker>
    </div>
    )
  }
}

export default CovidPoint;

使用您當前的實現,您不會通過LocationMarker在 CovidPoint 組合上傳遞名稱和信息道具。

要顯示點列表,您需要有一個latlngs數組,正如您在問題描述中所暗示的那樣。 因此,您的 LocationMarker 組合應如下所示:

function LocationMarker() {
  const [positions, setPositions] = useState([]);

  useMapEvents({
    dblclick(ev) {
      console.log("double clicked");
      const { lat, lng } = ev.latlng;
      const newPositions = [...positions];
      newPositions.push([lat, lng]);
      setPositions(newPositions);
    }
  });

  return <CovidPoint positions={positions}></CovidPoint>;
}

您獲取包含單擊位置坐標的 latlng object,然后將它們添加到您的位置數組中。 應該是復數,因為會有很多地方,而不是一個。

在 CovidPoint 上循環位置以渲染點。 您不需要將位置分配給 state 變量,除非您想將其作為本地變量進一步操作:

<div>
     {this.props.positions.length > 0 &&
       this.props.positions.map((position, index) => (
         <Marker position={position} icon={covidIcon} key={index}>
           {/* <Popup>
           Name: {this.state.name} <br />
           Case Status: {this.state.information}
         </Popup> */}
        </Marker>
     ))}
</div>

然后你需要改變這部分

 {/* <Popup>
      Name: {this.state.name} <br />
      Case Status: {this.state.information}
 </Popup> */}

因為它沒有從 LocationMarker comp 中獲取名稱和信息作為道具

演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM