JustFly1984 / react-google-maps-api

React Google Maps API
MIT License
1.78k stars 438 forks source link

Geocoder not implemented ?! #2729

Open Bartaf83 opened 3 years ago

Bartaf83 commented 3 years ago

I need to make Reverse Geocoding (as in this example).

It seems not implemented yet.

s6091214 commented 3 years ago

I also need

JustFly1984 commented 3 years ago

PR is welcome

hkngoc commented 3 years ago

I was try something and find solution as below:

import { useState } from 'react';
import { GoogleMap, LoadScript, Marker } from '@react-google-maps/api';

const LIBRARIES = ["places"];

const containerStyle = {
  width: "100%",
  height: '600px'
};

const CENTER = {
  lat: -3.745,
  lng: -38.523
};

const Map = ({ mapApiKey, center,...props }) => {
  const [position, setPosition] = useState(center);

  const onClick = async (event) => {
    const { latLng: { lat, lng } } = event;
    const latlng = { lat: lat(), lng: lng() };

    setPosition(latlng);

    const geocoder = new window.google.maps.Geocoder();
    const response = await geocoder.geocode({ location: latlng });
  }

  return (
    <LoadScript
      googleMapsApiKey={mapApiKey}
      libraries={LIBRARIES}
    >
      <GoogleMap
        {...props}
        center={center}
        onClick={onClick}
      >
        <Marker
          position={position}
        />
      </GoogleMap>
    </LoadScript>
  );
};

const App = () => {
  return (
    <Map
      mapApiKey={""} //your API key, remember enable Geocoding API
      center={CENTER}
      mapContainerStyle={containerStyle}
      zoom={15}
      options={{ streetViewControl: false }}
    />
  );
};
JustFly1984 commented 3 years ago

in your case onClick will always re-render whole app. you need to chache it with useCallback hook, and also wrap Map in memo() before using it in App