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 s*tatic 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
- Setup Google Cloud project & Enable billing (Require to use Google Maps API)
- Go to Google Onboard and Enable Required API (For this blog, it will be Geocoding API)
- Generate & Restrict an API key as needed.
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"}
To explore the Geocoding and Reverse Geocoding in Backend(Web server API) environments, Visit our full guide at Canopas Blog.
If you like what you read, be sure to hit 💖 button! — as a writer it means the world!
I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.
Happy coding!👋
Top comments (0)