Using Geolocation to a Locate a User on Google Maps in React-Redux
This blog will teach you how to obtain a user’s approximate coordinates and mark them on a GoogleMapReact Map.
Step Overview:
- Obtain a Google API Key.
- Obtain the user’s coordinates. This blog will show you two different ways of achieving this. Option 1 is using built-in Google Chrome geolocation and option 2 is utilizing Google’s Geocoding API (for browsers that may not support the first approach or users who elect not to process their location through the browser.)
- Add the Geocoding API to you project’s list of APIs. This API will allow you to obtain user coordinates by converting a an address or City & State (at the bare minimum) into approximate Latitude & Longitude coordinates.
- Install ‘google-map-react’
- Render map with a user’s location marker.
The tutorial will have code snippets and the copy-paste-friendly code is located at the end. 🔥

Option 1. Using Google Chrome Geolocation Method:
The first thing you need to know is that location can only be gathered by the browser after a user event. This means that you need to fire this function after a user has allowed the browser to do so. For this example, we will be doing that with the onClick of a button on a simple form.
The “Current Location” button has the following event listener
onClick={() => getPosition()}
The first function is the chain of events is the following:

This function uses navigator.geolocation.getCurrentPosition to process your location. It accepts a success callback function, and error callback function, and an options parameter (which I have elected not to use). The success and error callbacks are below.

The function convertToAddress is optional and it has been included below. This function will use the google API key to convert your latitude and longitude coordinates to a City, State, and Zip Code. It uses the Google API key and the Google Geocoding API. I have fetched for the API key from the back-end for this example.



At this point you should have access to the Lat/Long coordinates through Google Chrome.



What if you don’t have access to the latitude and longitude coordinates due to a user electing not to share their location with the browser or the browser not supporting geolocation processing? Option 2.
Option 2. Using Google’s Geocoding API:
We will use the City and State entered by the user in the form below to convert them into latitude and longitude coordinates on the form submission.

The “Submit Location” button has the following event listener
onClick={() => processManualLocation()}
The first function is the chain of events is the following:

This function uses the city and state manual entries along with the Google API key stored in the .env file in the front-end. You could include a full street address in the fetch url and the location of the Google Geocoding response would be more accurate. For this specific use case, the city and state will suffice. If the google geocoding API response status is “OK”, this function calls the next function in the chain:

After the last function in the chain runs, you should have access to the user’s approximate latitude and longitude coordinates.

Now that we have the users coordinates, let’s map them on Google Maps within your React-Redux application. I have elected to use ‘google-map-react’.
Creating a ‘google-map-react’ Map with a User Marker:
After you have installed ‘google-map-react’ and have access to a user’s coordinates, you will need to write the following code (or similar):

I have not commented this portion of code as the knowledge required to understand it is basic React-Redux.
Here’s what the map should look like:

I hope you have enjoyed this tutorial. Let me know if you have any questions!
Copy-paste-friendly code along with comments:
Obtaining lat/long, city, state, and postal code from Google Chrome Geolocation:
// If browser supports navigator.geolocation, generate Lat/Long else let user know there is an errorconst getPosition = () => {if (navigator.geolocation) {navigator.geolocation.getCurrentPosition(showPosition, posError); // Passing in a success callback and an error callback fn} else {alert("Sorry, Geolocation is not supported by this browser."); // Alert is browser does not support geolocation}}// Geolocation error callback fn. Query permissions to check if the error occured due to user not allowing location to be sharedconst posError = () => {if (navigator.permissions) {navigator.permissions.query({ name: 'geolocation' }).then(res => {if (res.state === 'denied') {alert('Enable location permissions for this website in your browser settings.')}})} else {alert('Unable to access your location. You can continue by submitting location manually.') // Obtaining Lat/long from address necessary}}// Geolocation success callback fnconst showPosition = (position) => {let lat = position.coords.latitude // You have obtained latitude coordinate!let long = position.coords.longitude // You have obtained longitude coordinate!props.set_lat(lat) // Using dispatch to modify lat store stateprops.set_long(long) // Using dispatch to modify long store stateconvertToAddress(lat, long) // Will convert lat/long to City, State, & Zip code}// Fetching for google API key from back-end (Optional, you can store it in .env file in front-end)const convertToAddress = (lat, long) => {fetch('http://localhost:3000/googlemaps').then(res => res.json()).then(obj => getAddress(lat, long, obj.api_key))}// Converting lat/long from browser geolocation into city, state, and zip code using Google Geocoding APIconst getAddress = (lat, long, googleKey) => {fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${googleKey}`).then(res => res.json()).then(address => setZip(address))}// Dispatching city, state, and zip code to store stateconst setZip = (address) => {let city = address.results[5].address_components[2].short_namelet state = address.results[5].address_components[4].short_namelet postal = address.results[5].address_components[0].short_nameprops.set_city(city)props.set_state(state)props.set_postal_code(postal)}
Converting city and state manual entries to lat/long:
// Function that will convert city & state to approximate user lat/long coordinates from manual entryconst processManualLocation = () => {if (props.userState !== "" && props.userCity !== "") {let city = props.userCity // manual lat entry is already in store statelet state = props.userPostalCode // manual long entry is already in store state// This fetch uses the API key stored in your fron-end .env file "process.env.REACT_APP_googleKey"let url = `https://maps.googleapis.com/maps/api/geocode/json?address=+${city},+${state}&key=${process.env.REACT_APP_googleKey}`fetch(url).then(res => res.json()).then(res => {if (res.status === "OK") {getUserCoords(res.results)} else if (res.status === "ZERO_RESULTS") {alert('Unable to process this location. Please revise location fields and try submitting again.')}})} else {alert('Please ensure State and City are provided.')}}// Obtaining and dispatching lat and long coords from google geocoding API responseconst getUserCoords = (googleRes) => {let lat = googleRes[0].geometry.location.lat // You have obtained latitude coordinate!let long = googleRes[0].geometry.location.lng // You have obtained longitude coordinate!props.set_lat(lat) // dispatching to store stateprops.set_long(long) //dispatching to store state}
Full ‘google-map-react’ code:
import React from 'react';import { connect } from "react-redux";import GoogleMapReact from 'google-map-react';const UserMap = (props) => {let userInfo = {center: {lat: props.userLat,lng: props.userLong},zoom: 10};const renderMarker = (map, maps) => {let marker = new maps.Marker({position: userInfo.center,map,title: "User Location"});return marker;};return (<div className="user-map" style={{ height: '600px', width: '600px' }}><GoogleMapReactbootstrapURLKeys={{ key: process.env.REACT_APP_googleKey }} // My Google API is stored in the .env file in front-enddefaultCenter={userInfo.center}defaultZoom={userInfo.zoom}yesIWantToUseGoogleMapApiInternals={true}onGoogleApiLoaded={({ map, maps }) => {renderMarker(map, maps)}}></GoogleMapReact></div>);}const mapStateToProps = (state) => {return {userLat: state.userState.userLat,userLong: state.userState.userLong,}}export default connect(mapStateToProps)(UserMap);