Smlok
Smlok

Reputation: 658

How can I get the current map center coordinates using getCenter in @react-google-maps/api?

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?

Upvotes: 2

Views: 6353

Answers (1)

Pagemag
Pagemag

Reputation: 2977

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;

Upvotes: 5

Related Questions