DEV Community

Shimju David
Shimju David

Posted on

3 1

useGeoPosition Hook - A Custom React Hook to grab latitude and longitude from a given address.

You might have encountered this requirement commonly where you want to display a google map on a listing details page and show a marker on it based on the address of the listing or a location. Here we want to pass the address of a listing or a location and you want the latitude and longitude as a return. Using Google's Geocoding API, we can extract this logic as a custom hook called useGeoPosition.

useGeoPosition hook-

This hook accepts two parameters -

  1. key - that's your Google Geocoding API key
  2. address- that's the address of your location where you want its latitude and longitude in return
import React, { useState, useEffect} from 'react'
    import axios from 'axios';

    const useGeoPosition = (key, address) => {
      const [position, setPosition] = useState({ lat: null, lng: null });
      const [error, setError] = useState(false);
      const [loading, setLoading] = useState(false);

      const fetchLatandLng = async () => {
        try {
              setLoading(true);
              const res = await axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=${key}`);
              const result = res.data.results[0].geometry.location;

              if (result.lat !== null && result.lng !== null) {
                setPosition({lat: result.lat, lng: result.lng})
              }
              else {
                setError(true);
              }
              setLoading(false);
          }
        catch (error) {
           setLoading(false);
           setError(true);
        }
      }


      useEffect(() => {
        fetchLatandLng();
      }, [address])

      return [position, loading, error]
    }

    export default useGeoPosition;
Enter fullscreen mode Exit fullscreen mode

You can now call this hook in your React component as

 const [position, geoloading, geoerror] = useGeoPosition(<PassYourGoogleKey>,'Boyd St,Long Beach');
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series