1

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ccy
  • 27
  • 4

1 Answers1

0

You should not modify the defaultCenter prop and set a center prop instead

I can see that you are using the google-map-react library. And what you were trying to do is modify the defaultCenter prop of the <GoogleMapReact /> component. Which is something you should not do.

As per this Library's documentation, defaultCenter is the,

Default lat/lng at which to center the map - changing this prop throws a warning

So what you should use instead is the center prop which is described as a,

Lat/lng at which to center the map

In your case, you can just create an object variable for the defaultCenter instead of separating the latitude and longitude like you did:

const defaultCenter = { lat: 60, lng: 30 };

Then create another object for the center props with useState so that you can modify the center of your map whenever you like:

const [center, setCenter] = useState("Center has not bee updated yet");

Notice that I just put a string first that says: "Center has not bee updated yet" since this will be updated later by your fetch call to the Geocoding API.

Then in your fetch call, since the response.data.results[0].geometry.location is already a latLng object, you can just directly use the variable you saved it to called address and use it in your setCenter function to update the center state variable. Your fetch call should look like this:

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;
    setCenter(address);
  } catch (error) {
    console.error(error);
  }
};

You can optionally create another useEffect with center state as its depency to check whenever the center value changes when rendering your component:

  useEffect(() => {
    console.log("Default center is: ");
    console.log(defaultCenter);
    console.log("Center has now been updated by the fetch request");
    console.log(center);
  }, [center]);

Then lastly, your <GoogleMapReact /> component should have the center prop, and it should look like this:

<GoogleMapReact
    center={center}
    bootstrapURLKeys={{ key: apiKey }}
    defaultCenter={defaultCenter}
    defaultZoom={defaultProps.zoom}
></GoogleMapReact>

With this, your map should update to the latLng that your fetch call 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!

Yrll
  • 1,619
  • 2
  • 5
  • 19