gpt4 book ai didi

javascript - 在react中刷新传单 map

转载 作者:行者123 更新时间:2023-12-02 21:23:44 27 4
gpt4 key购买 nike

我想在缩放后刷新传单 map 的圆圈:

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

import MarkerClusterGroup from "react-leaflet-markercluster";
import data from "./data.json";

const TILE_LAYER_ATTRIBUTION =
"Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL";
const TILE_LAYER_URL =
"https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png";

export function Map() {
const position = [55.2854062,23.9327383];
const initialZoom = 8;
let showTooltip = false;
let mapRef = React.createRef();

const renderMarkers = () => {
showTooltip = mapRef && mapRef.viewport && mapRef.viewport.zoom > 8 ? true : false;
let circles = [];
circles = data.map(item => (
<Circle key={item.id}
center={[item.latitude, item.longitude]}
color="red"
fillColor="red"
radius={100}
>
<Tooltip className="circle-tooltip" permanent={true} direction={"center"}>
{showTooltip ? <span>1</span> : <span></span>
}
</Tooltip>
<Popup>
<p>
{item.address}, {item.city}
</p>
<p>{item.time}</p>
</Popup>
</Circle>
));

return circles;
};


return (
<LeafletMap ref={(ref) => { mapRef = ref }} center={position} zoom={initialZoom} onzoomend={() => renderMarkers() }>
<TileLayer attribution={TILE_LAYER_ATTRIBUTION} url={TILE_LAYER_URL} />
{
<MarkerClusterGroup showCoverageOnHover={false}>
{renderMarkers()}
</MarkerClusterGroup>
}
</LeafletMap>
);
}

但是,在调用函数 renderMarkers() 后,它们不会被重绘。这里可能出了什么问题?

最佳答案

showTooltip 应该是使用 useState 的状态变量,因此当它更改时组件将重新渲染。

此外,我认为如果你使用功能组件,它应该是 useRef 而不是 createRef() ,然后

<LeafletMap
ref={mapRef}
...

所以应该是这样的:

  let [showTooltip, setShowTooltip] = React.useState(false);
let mapRef = React.useRef();

const renderMarkers = () => {
const map = mapRef.current;

if (map) {
console.log(map.leafletElement.getZoom());
// change here the showTooltip flag
setShowTooltip(map.leafletElement.getZoom() > 13 ? true : false);
}
};



<MarkerClusterGroup showCoverageOnHover={false}>
{data.map(item => (
<Circle
....
<MarkerClusterGroup/>

我稍微更改了示例,使缩放大于 13 以显示 1,较小的缩放不显示,以便能够在演示中进行演示,因为在较小的缩放级别中会显示气泡,并且您将无法看到工具提示。

Demo

关于javascript - 在react中刷新传单 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60791418/

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