This component passes in the address then uses another API to get the latitude and longitude. The latitude and longitude are then passed into the google-map-react API to be converted into a map.
But I'm unable to set custom center coordinates for the map. I have set up the fetchAddress function to retrieve the latitude and longitude coordinates for a specific address using the Google Geocoding API. However, when I log the defaultProps.center object, it shows two objects, one with default values (lat: 60, lng: 30) and another with the correct values (e.g., lat: -33.9325244, lng: 151.1787937).
And I want to use the correct latitude and longitude values from the Geocoding API response to set the center of the map. But when I pass in latitude and longitude values into it, it only handles the default values: lat: 60, lng: 30.
Here is my code:
import { AppContainer, Title, Image } from './styledMapApp';
import { useEffect, useState } from 'react';
import GoogleMapReact from 'google-map-react';
import axios from 'axios';
const MapApp = ({ location }: { location?: string }) => {
const apiKey = 'mykey';
const [latitude, setLatitude] = useState<number>(60);
const [longitude, setLongitude] = useState<number>(30);
const testingAddress = 'Arrivals Hall, Sydney International Airport, NSW 2020'; const encodedAddress = encodeURIComponent(testingAddress);
const fetchAddress = async () => {
try {
const response = await axios.get(
`https://maps.googleapis.com/maps/api/geocode/json?address={${encodedAddress}&key=${apiKey}`
);
const address = response.data.results[0].geometry.location;
const currentLatitude = address.lat;
const currentLongitude = address.lng;
setLatitude(currentLatitude);
setLongitude(currentLongitude);
} catch (error) {
console.error(error);
} };
useEffect(() => {
fetchAddress(); }, []);
const defaultProps = {
zoom: 11, };
console.log(latitude);
console.log(longitude);
return (
<AppContainer>
<Title>MapApp</Title>
<div style={{ height: '30vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: apiKey }}
defaultCenter={{ lat: latitude, lng: longitude }}
defaultZoom={defaultProps.zoom}
></GoogleMapReact>
</div>
</AppContainer> ); }; export default MapApp;
When I do: console.log(latitude); console.log(longitude);
I can see on the console that my object
60. MapApp.tsx:36
30. MapApp.tsx:37
-33.9325244. MapApp.tsx:36
151.1793765. MapApp.tsx:37
Any help is appreciated
You should not modify the
defaultCenterprop and set acenterprop insteadI can see that you are using the
google-map-reactlibrary. And what you were trying to do is modify thedefaultCenterprop of the<GoogleMapReact />component. Which is something you should not do.As per this Library's documentation,
defaultCenteris the,So what you should use instead is the
centerprop which is described as a,In your case, you can just create an object variable for the
defaultCenterinstead of separating thelatitudeandlongitudelike you did:Then create another object for the
centerprops withuseStateso that you can modify the center of your map whenever you like:Notice that I just put a string first that says: "Center has not bee updated yet" since this will be updated later by your
fetchcall to the Geocoding API.Then in your
fetchcall, since theresponse.data.results[0].geometry.locationis already alatLngobject, you can just directly use the variable you saved it to calledaddressand use it in yoursetCenterfunction to update thecenterstate variable. Yourfetchcall should look like this:You can optionally create another
useEffectwithcenterstate as its depency to check whenever the center value changes when rendering your component:Then lastly, your
<GoogleMapReact />component should have thecenterprop, and it should look like this:With this, your map should update to the
latLngthat yourfetchcall obtained through Geocoding.Here's a proof of concept sandbox that you can play around with and check (Just use your own API key and make sure it is restricted to avoid compromise. :>): https://codesandbox.io/s/issue-with-google-map-react-package-unable-to-set-custom-center-coordinates-vp5n7t?file=/src/App.tsx
I hope this helps!