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