如何在传单 ReactJS 中的 Marker PopUP 上显示更多数据

How to display more data on Marker PopUP in leaflet ReactJS

有两个数组 coordspopUPs 使用 Leaflet 并显示第一个数组中的数据。

我想知道如何显示来自第一个和第二个数组的数据?

在console.log上,我看到了第二个数组的数据,但我不知道如何在另一个地图函数中输入。

代码:

import React from "react";
import { Map as LeafletMap, TileLayer, Marker, Popup } from "react-leaflet";
import L from "leaflet";

const customMarker = new L.Icon({
  iconUrl: "https://unpkg.com/browse/leaflet@1.5.1/dist/images/marker-shadow.png",
  iconSize: [25, 41],
  iconAnchor: [10, 41],
  popupAnchor: [2, -40]
});

class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
 coords: [
        { lat: 41.19197, lng: 25.33719 },
        { lat: 41.26352, lng: 25.1471 },
        { lat: 41.26365, lng: 25.24215 },
        { lat: 41.26369, lng: 25.33719 },
], 
 popUPs: [
        { station: 1010, city: 'Ново село' },
        { station: 1020, city: 'Видин' },
        { station: 1030, city: 'Грамада' },
        { station: 1040, city: 'Белоградчик' },
],
      zoom: 7
    };
  }
 render() {

    const { coords, zoom, popUPs } = this.state;
    return (
      <LeafletMap
        center={[42.733883, 25.48583]}
        zoom={zoom}
        style={{ height: "100vh" }}
      >
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
        />

        {this.state.popUPs.map(({ station, city }, index) => (

          console.log(station, city)
        ))}

        {coords.map(({ lat, lng }, index) => (
          <Marker position={[lat, lng]} icon={customMarker} key={index}>
            <Popup>
              {index + 1} is for popup with lat: {lat} and lon {lng}
            </Popup>
          </Marker>
        ))}
      </LeafletMap>
    );
  }
}

export default Map;

如果我们考虑到您的 coords 数组项对应于 popups 数组中的每个项,那么您可以像这样合并两个数组的项:

const { coords, popUPs, zoom } = this.state;
    const mergedArrays = coords.map((coord, i) => ({
      ...coord,
      station: popUPs[i].station,
      city: popUPs[i].city
    }));

然后遍历新数组 mergedArrays 而不是坐标,它将包含您要显示的所有项目:

 {mergedArrays.map(({ lat, lng, station, city }, index) => (
      <Marker position={[lat, lng]} icon={customMarker} key={index}>
        <Popup>
          {index + 1} is for popup with lat <b>{lat}</b> and lon{" "}
          <b>{lng}</b> with station <b>{station}</b> at city <b>{city}</b>
        </Popup>
      </Marker>
    ))}

Demo