Google's Geocoding APIs: Frontend and Backend Implementation

Transform addresses to coordinates and back using Google Maps APIs
Dec 30 2024 · 6 min read

Introduction

Nowadays, we can’t imagine our life without a Location Map. We are exploring so many things using maps. From finding the fastest route to a destination, discovering nearby restaurants, or even tracking deliveries in real time, these services rely on location and mapping APIs.

Whenever we are building any application, there may be requirements for working with user location like finding addresses or integrating maps. Among the many solutions available, Google Maps APIs are the most powerful and widely used tools for developers.

In this blog, we will explore Google’s various location-based APIs, with a major focus on the Geocoding API.

You’ll learn:

  • The different APIs offered by Google Maps and how they work.
  • How to use the Geocoding API on a web server for converting addresses to coordinates (and vice versa).
  • How to build a Typescript-powered frontend to display the results interactively.

Let’s navigate through maps!!!


Type of Google Maps API

When I started exploring Google Maps, I was overwhelmed by its huge set of APIs. It was difficult for me to identify the right API for my use case. I explored all the APIs and here is a breakdown of it.

Google Maps APIs help developers to integrate advanced mapping and location-based features into their applications. These APIs allow a range of functionalities, from embedding interactive maps to fetching detailed location data, calculating distances, and managing real-time routing.

Below, we’ll break down some of these most useful APIs, explaining their purpose and how they work.

Mapping APIs

These APIs can be used to create and display static or interactive maps as per the needs of the application.

Google Maps API

  • This API allows embedding interactive, customizable maps directly into applications. 
  • Users can pan, zoom, and switch between map types (satellite, terrain, hybrid, etc.). 
  • Developers can add markers, polygons, and custom overlays to enrich the map.
  • Use cases:
    • Real-time location tracking applications.
    • Interactive trip planners.

Static Maps API

  • When any application needs static, non-interactive maps, this API will be useful. 
  • API is ideal for embedding maps in static websites, reports, and emails and is easy to use with URL-based parameters.
  • Use Cases:
    • Visualising data points in reports.
    • Adding maps to non-dynamic web pages.

Street View API

  • It enables developers to display 360° panoramic views of streets and landmarks.
  • This API allows virtual exploration of locations through street-level imagery.
  • Use Cases:
    • Real estate applications for property viewing.
    • Travel & tourism apps

Places APIs

Places APIs enable applications to fetch detailed information about points of interest (POIs), such as landmarks, businesses, or public facilities.

Geocoding & Reverse Geocoding API

  • These APIs are essential for translating between human-readable addresses and geographic coordinates like latitude and longitude (e.g., 37.422, -122.084).
  • Geocoding(address -> coordinates)
    One of the use cases for this API is a food delivery app, which converts user-inputted addresses to Geo coordinates and loads Google Maps based on them.
  • Reverse geocoding (coordinates -> address)
    This API can be used in tracking applications like Vehicle or user tracking. It will display the nearest address of the given coordinates.

Autocomplete API

  • This API will be useful for search-based location applications like form-filling.
  • It suggests relevant location predictions as users type into a search field.
  • Use Cases:
    • Search bars in maps or location selection forms.
    • Reducing user efforts and errors in typing addresses.

Time Zones API

  • It provides time zone information for any given location.
  • It takes Geographic coordinates and a timestamp as input and returns the name of the time zone, UTC offset, and Daylight Saving Time (DST) information.
  • Use Cases:
    • Applications displaying local times for events or activities.
    • Travel apps adapt schedules to different time zones.

Routes APIs

Routes APIs are designed to provide navigation capabilities and distance calculations.

Directions API

  • This is widely used in Google Maps. 
  • It offers detailed routes between two or more locations, including step-by-step navigation.
  • You just need to add start and end locations and it outputs directions, time, and distance with various travel modes (driving, walking, cycling, etc.).
  • Use Cases:
    • Ride-hailing services optimising routes for drivers.
    • Apps provide directions for users navigating cities like Google Maps.

Distance Matrix API

  • This API calculates travel distance and time between multiple origins and destinations.
  • Use Cases:
    • Delivery logistics calculate the most efficient routes.
    • Multi-location trip planning.

Enable Google Maps services 

To use the above services(APIs), we need an API key generated from the Google Cloud console. 

Note: Before starting with any of the google map services, I recommend you to go through its security and billing documents.

Below are the prerequisites to get and restrict API keys,

Prerequisites

API key restrictions

This will be helpful to secure the API key and prevent misuse of it. which eventually prevents unwanted high billing.

  • For running API in the Browser(Frontend) environment, use Websites restriction.
  • For running API in the backend environment, use IP addresses restriction.
  • Allow only the required API for the key.

Implementing Geocoding and Reverse Geocoding

We’ll now explore how to use the Geocoding API in both Frontend and Backend(Web server API) environments.

Frontend Implementation

Using Geocoding API directly in frontend, there are some drawbacks like API key exposure and performance issues. However, we can address these issues by adding API key restrictions and implementing caching.

  • Create an index.html file and add a script in the head,
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Google Places API</title>
  <script src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_MAPS_API_KEY&libraries=places"></script>
</head>
<body></body>
</html>

By adding this script, the browser will able to access Google objects from this script using window.google .

  • Add the Geocoding logic in geocoding.ts

GeoCoding

In this, we will pass a human-readable address and get the coordinates of that location.

function fetchCoordinates() {
    new window.google.maps.Geocoder().geocode(
        { address: '1600 Amphitheatre Parkway, Mountain View, CA' },
        (results: any, status: string) => {
          if (status === "OK" && results && results[0]) {
            console.log(
              'Latitude:', results[0].geometry.location.lat()
            );
            console.log(
              'Longitude:', results[0].geometry.location.lng()
            );
          } else {
            console.error(
              "Error fetching coordinates from geocoding: " + status
            );
          }
        }
      );
    }
 }

Note: We will use only geometry, review full response here

  • Build a typescript file and add a geocoding.js file inside index.html,
<body>
  <script type="module" src="geocoding.js"></script>
</body>
  • When you run index.html, the output will be,
Latitude: 37.4225018
Longitude: -122.0847402

Reverse GeoCoding

In this, we will pass the coordinates and get the human-readable address.

function fetchLocation() {

    const coordinates = {
      lat: 37.422,
      lng: -122.084,
    };

    new window.google.maps.Geocoder().geocode(
        { location: coordinates },
        (results: any, status: string) => {
          if (status === "OK" && results && results[0]) {
            console.log(
              "Address: " + results[0].address_components
            );
          } else {
            console.error(
              "Error fetching addressComponents from reverse geocoding: " + status
            );
          }
        }
      );
    }
 }

Note: We will use only address_components, review full response here
Also, You can find all the fields of address_components here and can use the required field for your use case.

  • Extract human-readable address from address_components,
const extractLocation = (addressComponents: any[]) => {
    
    const findAddressType = (types, addressComponents) => {
        const found = addressComponents.find((c) =>
          types.some((t) => c.types.includes(t)),
        );
        return found?.longText ?? found?.long_name ?? "";
    };
    
    return {
        area: findAddressType(['sublocality_level_1', 'locality'], addressComponents),
        city: findAddressType(['locality'], addressComponents),
        state: findAddressType(['administrative_area_level_1'], addressComponents),
        pincode: findAddressType(['postal_code'], addressComponents),
    };
};
  • Print the address as below,
console.error(
   "Address: " + JSON.stringify(extractLocation(results[0].address_components))
);
  • Build a typescript and run index.html. The output will be,
Address: {"area":"Mountain View","city":"Mountain View","state":"California","pincode":"94043"}

Backend (Web server API) Implementation

This is the most secure way to access any sensitive information using secret keys. 

Basically in the front end, we accessed Google’s geocode using <script>, and in the backend, we will use geocode API. We will do API requests, and get responses and the rest will be the same as the frontend. 

router.get('/geocode', async (req: Request, res: Response) => {
  try {
    const results = await getGeocodingData();
    res.json({ results });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});
  • Define geocoding API and API key,
const GEOCODING_API_URL = 'https://maps.googleapis.com/maps/api/geocode/json';

const apiKey = process.env.GOOGLE_MAPS_API_KEY;
  • Add getGeocodingData method like below, 

Geocoding

async function getGeocodingData() {

  const address = '1600 Amphitheatre Parkway, Mountain View, CA';

  try {
    const response = await axios.get(GEOCODING_API_URL, {
      params: { address, key: apiKey },
    });

    const results = response.data.results

    if (response.data.status === "OK" && results && results[0]) {
       return {"long": results[0].geometry.location.lng, "lat": results[0].geometry.location.lat}
    } else {
       console.error(
         "Error fetching coordinates from geocoding: " + response.data.status
       );
    }   
  } catch (error) {
    console.error('Error in geocoding service:', error);
    throw error;
  }
}

Start the server and run API in Postman. The result will be,

Screenshot from 2024-12-30 15-04-19.png

 

Reverse Geocoding

async function getGeocodingData() {

  const latlng = {
    lat: 37.422,
    lng: -122.084,
  };

  try {
    const response = await axios.get(GEOCODING_API_URL, {
      params: { latlng: `${latlng.lat},${latlng.lng}`, key: apiKey },
    });

    const results = response.data.results

    if (response.data.status === "OK" && results && results[0]) {
       return {"address": extractLocation(results[0].address_components)}
    } else {
       console.error(
         "Error fetching addressComponents from reverse geocoding: " + response.data.status
       );
    }   
  } catch (error) {
    console.error('Error in geocoding service:', error);
    throw error;
  }
}

Here is output,

Screenshot from 2024-12-30 15-20-24.png


 


Conclusion

Google Maps APIs provide a powerful suite of tools to enhance applications with location-based services. 

By implementing either frontend or backend solutions, developers can ensure secure and efficient usage of these APIs while securing sensitive information like API keys. 

The capabilities of Google Maps APIs go far beyond Geocoding, extending to routes, places, and time zones, making them indispensable for modern applications. By leveraging these APIs, developers can create innovative and impactful user experiences.


We’re Grateful to have you with us on this journey!

We hope you found this post helpful. If you have any questions or need further clarification, don't hesitate to reach out to us on X! We're always happy to chat and assist with anything you need.

Follow us @canopassoftware and drop us a message – we'd love to hear from you!

Until next time, take care and keep exploring.

And don't forget to subscribe to not miss our latest updates. 


Code, Build, Repeat.
Stay updated with the latest trends and tutorials in Android, iOS, and web development.
sumita-k image
Sumita Kevat
Sumita is an experienced software developer with 5+ years in web development. Proficient in front-end and back-end technologies for creating scalable and efficient web applications. Passionate about staying current with emerging technologies to deliver.
sumita-k image
Sumita Kevat
Sumita is an experienced software developer with 5+ years in web development. Proficient in front-end and back-end technologies for creating scalable and efficient web applications. Passionate about staying current with emerging technologies to deliver.
canopas-logo
We build products that customers can't help but love!
Get in touch
contact-footer
Say Hello!
footer
Follow us on
2025 Canopas Software LLP. All rights reserved.