I am using @react-google-maps/api to use google map inside Next JS app.
Based on their documents, they mentioned that the parent HTML element could determine the size of the map.
My return function from my component looks like this:
return (
<div
style={{
display: "flex",
flexDirection: "column",
height: "100vh",
width: "100%",
}}
>
<GoogleMap
options={mapOptions}
zoom={mapOption.zoom}
center={mapCenter}
mapTypeId={google.maps.MapTypeId.ROADMAP}
mapContainerStyle={{width: "300px",height: "300px"}}
onLoad={() => console.log("Map Component Loaded...")}
/>
</div>
)
So basically I need to determine the width and height of the map and via parent, it would be overridden if I want to make it fill the entire screen. The problem is that the above return still shows the map with 300 to 300 px. Does anyone have any solution so that the initial map fills the entire screen?
It's because the <GoogleMap />
attribute mapContainerStyle
is also a seperate container and is only a child of the <div>
container outside it, where you put the style
attribute.
So although you set the <div>
container with 100% width and height or 100vh/vw, if it's child component got a lower width and height, most especially because what you're using here is pixels, ofcourse it would show as only 300px in width and also in height.
return (
<div
style={{
backgroundColor: "green",
display: "flex",
flexDirection: "column",
height: "500px",
width: "500px"
}}
>
<GoogleMap
mapContainerStyle={{
margin: "auto",
width: "50%",
height: "50%"
}}
center={center}
zoom={3}
></GoogleMap>
</div>
)
Notice that the <div>
container having a green background and height/width of 500px, shows that it contains the mapContainerStyle
provided here that I set the width and height to 50%.
So if you want to fill the 500px square <div>
container, you should just set the height and width of mapContainerStyle
to 100%. It would look like this:
return (
<div
style={{
backgroundColor: "green",
display: "flex",
flexDirection: "column",
height: "500px",
width: "500px"
}}
>
<GoogleMap
mapContainerStyle={{
margin: "auto",
width: "100%",
height: "100%"
}}
center={center}
zoom={3}
></GoogleMap>
</div>
)
So to answer your question, you can just leave your <div>
container without any styling, then setting the mapContainerStyle
to 100% for it's width and height. Or you can set your <div>
container as you have on your sample, depending on your use case. But here's the sample for both.
<div>
styling:return (
<div>
<GoogleMap
mapContainerStyle={{
margin: "auto",
width: "100%",
height: "100%"
}}
center={center}
zoom={3}
/>
</div>
)
<div>
styling:return (
<div
style={{
height: "100vh",
width: "100%"
}}
>
<GoogleMap
mapContainerStyle={{
margin: "auto",
width: "100%",
height: "100%"
}}
center={center}
zoom={3}
></GoogleMap>
</div>
)
Hope this helps! Feel free to leave a comment if you need clarification or if I misunderstood your question somehow. But that's about it from me for now.