I use google-map-react and I want to have the correct zoom and center to the map. To center the map I use the props center on GoogleMapReact component that I can calculate. But for the zoom it is more complex.
I could see the use of fitBounds but that is not available on "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 ?
Be careful not to confuse " google-map-react " (used here) with "react-google-map" (not used)
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. There are examples of how to use it in the 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:
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.