如何在react-google-maps中获取地图[getZoom()]的当前缩放?

use*_*818 4 google-maps reactjs react-google-maps

我想在react-google-maps 中获取地图的当前缩放级别,就像我们使用 getZoom() 函数在简单的谷歌地图 API 中所做的那样。如何在react-google-maps中做到这一点?

我看过很少的答案,但没有一个对我有用。

import React from "react"
import {
  GoogleMap,
  Marker,
  withGoogleMap,
  withScriptjs,
} from "react-google-maps"


const Map = () => {
  return (
    <GoogleMap
      defaultZoom={15}
      defaultCenter={{ lat: lat, lng: lng }}
    >
      <Marker position={{ lat: lat, lng: lng }} />
    </GoogleMap>
  )
}

const WrappedMap = withScriptjs(withGoogleMap(Map))

const Index = () => {
  return (
    <Layout>
      <WrappedMap
        googleMapURL={`https://maps.googleapis.com/maps/api/js? 
        key=my_key&v=3.exp&libraries=geometry,drawing,places`}
        loadingElement={<Loading />}
        containerElement={<div style={{ height: `400px` }} />}
        mapElement={<div style={{ height: `100%` }} />}
      />
    </Layout>
  )
}

export default Index

Run Code Online (Sandbox Code Playgroud)

我怎样才能获得上面显示的示例的Zoom。

use*_*818 5

反应谷歌地图/api

从下面复制基本模板,确保为latlngapiKey指定值

来自“@react-google-maps/api”的GoogleMap组件采用一个函数类型的prop onLoad 。onLoad函数采用默认参数,即地图的当前实例

我在这里使用反应钩子来设置我的功能组件中的状态,您也可以使用基于类的组件。只需 setState 地图的当前实例即可。

import React from "react"
import { GoogleMap, LoadScript } from "@react-google-maps/api"

const apikey = "YOUR_API_KEY_HERE"

// lat and lng are float numbers not string
const lat = lat_value
const lng = lng_value

const Map = props => {
  const [map, setMap] = React.useState(null)
  return (
    <LoadScript id="script-loader" googleMapsApiKey={apikey}>
      <GoogleMap
        // set the state with the current instance of map.
        onLoad={map => {
          setMap(map)
        }}
        mapContainerStyle={{
          height: "400px",
          width: "800px",
        }}
        zoom={16}
        center={{
          lat: lat,
          lng: lng,
        }}
        id="example-map"
        // here onZoomChanged we are accessing the current zoom value from our map
        //instance which is stored in the state
        onZoomChanged={() => {
          console.log(map.getZoom())
        }}
      >
        ...Your map components
      </GoogleMap>
    </LoadScript>
  )
}

export default Map
Run Code Online (Sandbox Code Playgroud)

一旦您更改地图的缩放,就应该在控制台中记录当前的缩放值。