Skip to content
Santiago Casas Rey edited this page Mar 26, 2023 · 2 revisions

react-google-maps-user-location

User location button library for Google maps

user_location_button user_location

Description

Add a user location button to google maps on React. Click on the button and navigator will ask for location permission to the user. If the user accepts the map will pan and zoom to center the user location. Button and user location image look like google maps ones.

Installation

npm install --save react-google-maps-user-location

or:

yarn add react-google-maps-user-location

Usage

Tested with google-map-react

import GoogleMap from 'google-map-react';
import { UserLocatorButton } from 'react-google-maps-user-location';
...

const mapRef = useRef();
...

<GoogleMap
    bootstrapURLKeys={{ key:YOUR_GOOGLE_MAPS_API_KEY }}
    defaultCenter={DEFAULT_CENTER}
    defaultZoom={DEFAULT_ZOOM}
    yesIWantToUseGoogleMapApiInternals
    onGoogleApiLoaded={({ map, maps }) => {
        mapRef.current = map;
        const controlPosition = document.createElement("div");
        ReactDOM.render(<UserLocatorButton mapRef={mapRef} maps={maps}/>, controlPosition)
        map.controls[maps.ControlPosition.RIGHT_TOP].push(controlPosition)
    }}>
</GoogleMap>

Manage Errors

import GoogleMap from 'google-map-react';
import { UserLocatorButton } from 'react-google-maps-user-location';
...

const mapRef = useRef();
...
const manageErrors = (errorCode) => {
  if (errorCode === 1)
  {
    console.log("permission denied")
  }
  else if (errorCode === 2)
  {
    console.log("position unavailable")
  }
  else if (errorCode === 3)
  {
    console.log("timeout")
  }
}

<GoogleMap
    bootstrapURLKeys={{ key:YOUR_GOOGLE_MAPS_API_KEY }}
    defaultCenter={DEFAULT_CENTER}
    defaultZoom={DEFAULT_ZOOM}
    yesIWantToUseGoogleMapApiInternals
    onGoogleApiLoaded={({ map, maps }) => {
        mapRef.current = map;
        const controlPosition = document.createElement("div");
        ReactDOM.render(<UserLocatorButton mapRef={mapRef} maps={maps} onError={manageErrors}/>, controlPosition)
        map.controls[maps.ControlPosition.RIGHT_TOP].push(controlPosition)
    }}>
</GoogleMap>

Caveats

Required React Version

React 16.8 or above is required because we use hooks.

License

Creative Commons