1

I am working with GoogleMap component from @react-google-maps/api, but can't seem to find how can I get the currently centered map coordinates (lat & lng) after I have moved it?

By searching around I found this article, which asks a similar question, but none of the answers work for me. Below is a code I'm testing.

import { GoogleMap, useLoadScript } from "@react-google-maps/api";

const { isLoaded, loadError } = useLoadScript({
    googleMapsApiKey: process.env.REACT_APP_GOOGLE_MAPS_API_KEY,
});

export default function Test() {
    return (
        <>
            <GoogleMap
                zoom={8}
                center={{lat: 35.6676095, lng: 139.334863}}
                // onCenterChanged={getCenter} - doesn't work
                // onCenterChanged={getCenter()} - doesn't work
                // onCenterChanged={this.getCenter} - doesn't work
                // onCenterChanged={ (e)=> this.getCenter(e)}  - doesn't work
            >
            </GoogleMap>
        </>
    );
}

The map loads fine, but once I add the onCenterChanged= prop, everything breaks because the getCenter function is obviously not declared.

I'd like to get a variable or state with the center coordinates after I have moved the map. Where do I declare it and how do I use it?

Smlok
  • 598
  • 6
  • 19

1 Answers1

4

You need to get the instance of the map during onLoad then use a state that will save this instance with initial value of null. In your onCenterChanged function, check if the value of your map's instance is not null then get its new center. This is achieved using the following sample code and code snippet:

import React, { useState } from 'react';
import { GoogleMap } from '@react-google-maps/api';
const defaultLocation = { lat: 11.174036305817275, lng: 76.3754534171875 };

function Map() {
  const [mapref, setMapRef] = React.useState(null);
  const handleOnLoad = map => {
    setMapRef(map);
  };
  const handleCenterChanged = () => {
    if (mapref) {
      const newCenter = mapref.getCenter();
      console.log(newCenter);
    }
  };

  return (
    <GoogleMap
      center={defaultLocation}
      zoom={8}
      onLoad={handleOnLoad}
      onCenterChanged={handleCenterChanged}
      mapContainerStyle={{ width: '100%', height: '88vh' }}
    />
  );
}

export default Map;
Pagemag
  • 2,779
  • 1
  • 7
  • 17
  • 2
    This worked like a charm. Only thing is, my development environment returned some `_.zf` objects instead of lat long coordinates like in your example, but if I update the `console.log(newCenter)` to `console.log(newCenter.lat(), newCenter.lng())` I get the desired result. Thank you! – Smlok Jul 21 '21 at 07:20