我想在缩放后刷新传单地图的圈子:



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

09-17 10:59