MsU*_*ems 6 mapbox reactjs mapbox-gl
我正在创建一个 React Mapbox 应用程序,但我遇到了弹出窗口问题。当我渲染地图时,所有标记都正确显示在地图上。然后我单击标记,该标记上会打开一个弹出窗口,其中包含正确的数据和所有内容。
但是,一旦我关闭该弹出窗口,我就无法打开新的弹出窗口。甚至不是同一个弹出窗口。我尝试 console.log() 单击时获得的数据,它是正确的(引脚数据对象:纬度、经度、id ...)
这是我的代码:
import { useState, useEffect } from "react";
import Map, { Marker, Popup } from "react-map-gl";
import axios from "axios";
import "mapbox-gl/dist/mapbox-gl.css";
import "./App.css";
import { Room } from "@material-ui/icons";
import { format } from "timeago.js";
function App() {
const [pins, setPins] = useState([]);
//Contains selected pin
const [selectedPin, setSelectedPin] = useState(null);
const [showPopup, setShowPopup] = useState(false);
//Get all pins from the database
useEffect(() => {
const getPins = async () => {
try {
const response = await axios.get("/pins");
setPins(response.data);
} catch (error) {
console.log(error);
}
};
getPins();
//console.log(pins);
}, []);
useEffect(() => {
const listener = (e) => {
if (e.key === "Escape") {
setSelectedPin(null);
}
};
window.addEventListener("keydown", listener);
return () => {
window.removeEventListener("keydown", listener);
};
}, []);
const handlePinClick = (pin) => {
console.log("here");
setSelectedPin(pin);
console.log(pin);
};
return (
<div className="App">
<Map
initialViewState={{
longitude: 31.1656,
latitude: 48.3794,
zoom: 5,
}}
style={{ width: "100vw", height: "100vh" }}
mapStyle="mapbox://styles/msude/cl0b56qxj000215qj1qgx7faq"
mapboxAccessToken={process.env.REACT_APP_MAPBOX}
>
{pins.map((pin) => (
<>
<Marker longitude={pin.long} latitude={pin.lat} anchor="bottom">
<Room
style={{ color: "red", cursor: "pointer" }}
onClick={() => {
handlePinClick(pin);
}}
/>
</Marker>
{selectedPin && (
<Popup
key={selectedPin._id}
longitude={selectedPin.long}
latitude={selectedPin.lat}
anchor="bottom"
onClose={() => setSelectedPin(null)}
>
<div className="popup">
<label>Title</label>
<h2>{selectedPin.title}</h2>
<label>Description</label>
<h2>{selectedPin.description}</h2>
<label>Type of forces</label>
<label>Est. number of forces</label>
<h2>{selectedPin.number}</h2>
<label>Added on</label>
<h2>{format(selectedPin.createdAt)}</h2>
</div>
</Popup>
)}
</>
))}
</Map>
</div>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud)
我肯定错过了一些东西,但过去两天我一直在为这个问题苦苦挣扎,似乎找不到解决方案。
小智 14
显然,你必须在 Popup 组件中设置 closeOnClick={false} ,closeOnClick 默认设置为 true,closeOnClick 用于在单击地图中的某个位置时关闭弹出窗口,但是,由于某种原因,使用 closeOnClick 似乎不会破坏弹出窗口但仅“隐藏它”,那么您将无法再次显示它,我没有通过将 closeOnClick 保持为 true 找到任何解决方法
小智 0
地图框标记具有“getPopup().isOpen()”来控制标记弹出窗口是否打开,以及“togglePopup()”来切换标记弹出功能。也许你可以用它们来解决你的问题。
例如,当您单击标记时,您会触发单击事件:
onMarkerClick = (marker) => {
marker.togglePopup();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2258 次 |
| 最近记录: |