'google map shows random location as center, even when center is specified
I'm using the package google-maps-react to show gmaps in my react app. Everything works fine, except for the fact that the map initially shows a random location as the center, even when I've specified co-ordinates for the center and initial center. How can I fix this so that the map centers on the co-ordinates I've specified initially?
const MapContainer = React.memo((props) => {
const [map, setMap] = useState();
const [center, setCenter] = useState({ lat: 59.913, lng: 10.752 });
var bounds = new props.google.maps.LatLngBounds();
const setMapObj = (mapProps, map) => {
setMap(map);
};
useDeepCompareEffect(() => {
if (props.markers.length === 1) {
setCenter(props.markers[0]);
}
for (var i = 0; i < props.markers.length; i++) {
bounds.extend(
new props.google.maps.LatLng(props.markers[i].lat, props.markers[i].lng)
);
}
if (map) {
map.fitBounds(bounds);
}
}, [props.markers, map]);
return (
<div className={props.className}>
{/* TODO -> Store api key in .env file */}
{console.log(center)}
<Map
google={props.google}
style={{ borderRadius: "10px" }}
center={center}
initialCenter={center}
onReady={setMapObj}
zoom={4}
bounds={bounds}
>
{props.markers.map((item, index) => {
if (item.lat && item.lng)
return (
<Marker key={index} position={{ lat: item.lat, lng: item.lng }} />
);
})}
</Map>
</div>
);
});
Solution 1:[1]
Your code is trying to set a center AND fit a particular bounds. The latter will cause the center to change in order to fit all of the markers in the viewport.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jpoehnelt |
