-
Notifications
You must be signed in to change notification settings - Fork 0
Home
Santiago Casas Rey edited this page Mar 26, 2023
·
2 revisions
User location button library for Google maps
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.
npm install --save react-google-maps-user-location
or:
yarn add react-google-maps-user-location
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>
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>
React 16.8 or above is required because we use hooks.
Creative Commons