【问题标题】:How can I get the current Leaflet map zoom level?如何获取当前的 Leaflet 地图缩放级别?
【发布时间】:2021-12-08 18:53:04
【问题描述】:

我正在尝试实时获取地图的缩放级别,以制作一个使用当前值锁定缩放的按钮。我曾尝试使用 getMapZoom 和 getZoom 但都给了我一个未定义的值。我想我没有使用正确的参考,但我找不到太多关于它的文档。代码如下:

<Map className="map-layer" 
          center={center} 
          onoverlayadd={this.overlayadd} 
          onoverlayremove={this.overlayremove}
          ondragend={this.zoomChange}
          onzoomend={console.log('Zoom: ' + this.mapRef.leafletElement.getMapZoom())}
          zoom={this.state.zoom}
          ref={this.mapRef}
          preferCanvas={false}
          animate={true}
          scrollWheelZoom={this.state.zoomLock ? false : true}
          doubleClickZoom={this.state.zoomLock ? false : true}
          touchZoom={this.state.zoomLock ? false : true}
          maxZoom={7}
          minZoom={7}

                    >

【问题讨论】:

    标签: javascript reactjs leaflet react-leaflet


    【解决方案1】:

    在纯传单中,如果您将地图定义为const map = L.map("map", options),那么您只需调用map.getZoom()

    在构造函数this.mapRef = React.createRef() 在地图元素中:

        ref={this.mapRef}
        onzoomend={() => console.log(this.mapRef.current.leafletElement.getZoom()}
    

    【讨论】:

    • 我已经尝试过了,抛出一个错误。 Cannot read property 'getZoom' of undefined
    • 试试ref={(ref) =&gt; { this.mapRef = ref }} 而不是ref={this.mapRef}
    • 我没有注意到您没有将函数传递给onzoomend。我更新了答案。您也应该将函数传递给其他 onevent 处理程序。
    【解决方案2】:

    在 react 中可以通过 getZoom method() 和 useRef 获取 zoomLevel。

    1) const mapRef = useRef(null) 
    
    2) const getMapZoom = () => {
     return mapRef && console.log("object", mapRef.current.getZoom());
     };
    
     3) <MapContainer
        className="markercluster-map"
        center={center}
        zoom={ZOOM_LEVEL}
        maxZoom={MAX_ZOOM}
        ref={mapRef}
        whenCreated={(mapInstance) => (mapRef.current = mapInstance)}
        whenReady={() => {}}
        >
    

    【讨论】:

      猜你喜欢
      • 2016-10-11
      • 2013-12-31
      • 1970-01-01
      • 2010-11-29
      • 2016-02-09
      • 1970-01-01
      • 2016-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多