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

问题描述 投票:0回答:1

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

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

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

代码:

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/[email protected]/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;
javascript reactjs leaflet react-leaflet
1个回答
0
投票

如果考虑到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

© www.soinside.com 2019 - 2024. All rights reserved.