gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:27:55 24 4
gpt4 key购买 nike

有两个数组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/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

关于javascript - 如何在传单ReactJS中的Marker PopUP上显示更多数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58998453/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com