簡體   English   中英

使用 google-map-react fitbounds useRef -> mapRef.current.fitBounds 不是函數

[英]Use google-map-react fitbounds useRef -> mapRef.current.fitBounds is not a function

我使用google-map-react ,我希望地圖具有正確的縮放和中心。 為了使地圖居中,我使用可以計算的 GoogleMapReact 組件上的道具中心。 但是對於縮放,它更復雜。

我可以看到 fitBounds 的使用,但這在“google-map-react”上不可用

有沒有辦法計算縮放,以便它包含我定義的標記。 還是像 fitbounds 一樣自行完成的功能?

注意不要將“ google-map-react ”(此處使用)與“react-google-map”(未使用)混淆

import GoogleMapReact from "google-map-react";
import {Place} from "@material-ui/icons";
import {useRef} from "react";


const Page = () => {

    const mapRef = useRef(null);

    const MarkerPlace = (props) => {
        return (
            <div>
                <Place fontSize={"large"}></Place>
                <p>{props.name}</p>
            </div>
        )
    }

    const FitBounds = () => {
        let bounds = new google.maps.LatLngBounds();
        let lat = 38.103;
        let lng = -121.572;
        bounds.extend(new google.maps.LatLng(lat, lng));

        console.log(mapRef.current) //o {props: {…}, context: {…}, refs: {…}, updater: {…}, _getMinZoom: ƒ, …}

        //The error occurs at the line below
        mapRef.current.fitBounds(bounds) //TypeError: mapRef.current.fitBounds is not a function
        //The error occurs at the line above
    }

    return (
        <div>
            <GoogleMapReact ref={mapRef} bootstrapURLKeys={{key: ""}} center={defaultCenter} defaultZoom={13}
                {view === "recherche" && currentSearchData.map((activity, index) => (
                    <MarkerPlace key={index} lat={activity.latitude} lng={activity.longitude} name={activity.name}/>
                 ))}
            </GoogleMapReact>
            <button onclick={FitBounds}>FitBounds</button>
        </div>
    )
}

export default Page;

fitBounds確實存在於google-map-react中,但它是一個單獨的實用程序函數,而不是實例上的函數。 api中有如何使用它的示例。 根據源碼fitBounds定義為以角邊界為第一個參數,高度/寬度字典為第二個參數:

export function fitBounds({ nw, se, ne, sw }, { width, height }) {

它返回一個帶有newBounds的新對象,可能會被解構並用於設置新的centerzoom

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM