[英]Use google-map-react fitbounds useRef -> mapRef.current.fitBounds is not a function
I use google-map-react and I want to have the correct zoom and center to the map.我使用google-map-react ,我希望地图具有正确的缩放和中心。 To center the map I use the props center on GoogleMapReact component that I can calculate.为了使地图居中,我使用可以计算的 GoogleMapReact 组件上的道具中心。 But for the zoom it is more complex.但是对于缩放,它更复杂。
I could see the use of fitBounds but that is not available on "google-map-react"我可以看到 fitBounds 的使用,但这在“google-map-react”上不可用
Is there a way to calculate the zoom so that it contains the markers that I have defined.有没有办法计算缩放,以便它包含我定义的标记。 Or a function that does it by itself like fitbounds ?还是像 fitbounds 一样自行完成的功能?
Be careful not to confuse " google-map-react " (used here) with "react-google-map" (not used)注意不要将“ 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
does exist in google-map-react , but it's a separate utility function rather than a function on the instance. fitBounds
确实存在于google-map-react中,但它是一个单独的实用程序函数,而不是实例上的函数。 There are examples of how to use it in the api .在api中有如何使用它的示例。 According to the source code , fitBounds
is defined to take corner boundaries as the first parameter, and a height/width dictionary as the second:根据源码, fitBounds
定义为以角边界为第一个参数,高度/宽度字典为第二个参数:
export function fitBounds({ nw, se, ne, sw }, { width, height }) {
and it returns a new object with newBounds
, presumably to be destructured and used to set the new center
and zoom
.它返回一个带有newBounds
的新对象,可能会被解构并用于设置新的center
和zoom
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.