DEV Community

Cover image for Locate users on Google map in React App!
Jaspreet kaur
Jaspreet kaur

Posted on

Locate users on Google map in React App!

While I was working on my project, which is like an online service providing platform, I had to show some user related details including user's location too (based on the address provided by the user while signing in to my website) to the service provider.

For this project I used React js for frontend and rails for backend.

My backend has a users table with address, state, & zip columns along with other columns about user details. While creating an account user will share these address details.
Image description
Now, we have the address but we can't locate address directly on the map , you need coordinates for that. Below steps will help converting the address into coordinates and eventually show it on the google map.

Getting started,

  1. Install google map react => npm install --save google-map-react

  2. Then, get the particular user details for whom you want to show the location. You can get it either by fetching the api ("users/:id") or through the props from other components. That depends on the way your application is designed and how you want to code.

  3. After that below code will help you get the coordinates. With this code you don't need to store the latitudes & longitudes in the database. It will dynamically convert the user address provided into coordinates. You just need to set the state for latitude, and longitude.
    And inside useEffect you need to pass dependency array with latitude & longitude state values. This will ensure that the fetch runs any time dependency value changes.
    Since we don't want to show only 1 user's location but for all whenever required. Hence, we need this dependency which ensures whenever the user details changes it will dynamically locate it on map.

Please note, here we are using google API key as well, make sure to secure/hide your API key before pushing your code to your GitHub.

import React, { useEffect, useState } from 'react'
import GoogleMapReact from 'google-map-react'

export default function SetCords ({user}) {
  const [lat, setLat] = useState()
  const [lon, setLon] = useState()
  const key = 'Your Google API key'
  let url = `https://maps.googleapis.com/maps/api/geocode/json?address=+${user.address},+${user.state},+${user.zip}&key=${key}`

useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(res => {
        if (res.status === 'OK') {
          console.log('Cordinates'+ JSON.stringify(res))
          setLat(res.results[0].geometry.location.lat)
          setLon(res.results[0].geometry.location.lng)
        } else if (res.status === 'ZERO_RESULTS') {
          alert(
            'Unable to process this location. Please revise location fields and try submitting again.'
          )
        }
      })
  },[lat, lon])
Enter fullscreen mode Exit fullscreen mode

Next, you need show the above coordinates on map. Follow below code to show the map and marker on the map.

const renderMarker = (map, maps) => {
    let marker = new maps.Marker({
      position: {lat: lat, lng: lon},
      map,
      title: 'User Location'
    })
    return marker;
  };

  return (
        <div style={{ height: '100vh', width: '100%' }}>
          <GoogleMapReact
            bootstrapURLKeys={{ key: key }}
            center={{lat: lat, lng: lon}}
            zoom={10}
            yesIWantToUseGoogleMapApiInternals= {true}
            onGoogleApiLoaded={({ map, maps }) => {
              renderMarker(map, maps)
            }}
          >
          </GoogleMapReact>
        </div>
    )

Enter fullscreen mode Exit fullscreen mode

Overall code looks like this:

import React, { useEffect, useState } from 'react'
import GoogleMapReact from 'google-map-react'


export default function SetCords ({ user }) {
  const [lat, setLat] = useState()
  const [lon, setLon] = useState()
  const key = 'Your Google API key'
  let url = `https://maps.googleapis.com/maps/api/geocode/json?address=+${user.address},+${user.state},+${user.zip}&key=${key}`
  useEffect(() => {
    fetch(url)
      .then(res => res.json())
      .then(res => {
        if (res.status === 'OK') {
          console.log('Cordinates' + JSON.stringify(res))
          setLat(res.results[0].geometry.location.lat)
          setLon(res.results[0].geometry.location.lng)
        } else if (res.status === 'ZERO_RESULTS') {
          alert(
            'Unable to process this location. Please revise location fields and try submitting again.'
          )
        }
      })
  },[lat, lon])

  const renderMarker = (map, maps) => {
    let marker = new maps.Marker({
      position: {lat: lat, lng: lon},
      map,
      title: 'User Location'
    })
    return marker;
  };

  return (
      <div>

        <div style={{ height: '100vh', width: '100%' }}>
          <GoogleMapReact
            bootstrapURLKeys={{ key: key }}
            center={{lat: lat, lng: lon}}
            zoom={10}
            yesIWantToUseGoogleMapApiInternals= {true}
            onGoogleApiLoaded={({ map, maps }) => {
              renderMarker(map, maps)
            }}
          >
          </GoogleMapReact>
        </div>
      </div>
    )
}

Enter fullscreen mode Exit fullscreen mode

Hope, this helps anyone who is new to google maps and want to convert address stored in the database into coordinates to locate it on the map.

Top comments (0)