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:
Let’s navigate through maps!!!
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.
These APIs can be used to create and display static or interactive maps as per the needs of the application.
Places APIs enable applications to fetch detailed information about points of interest (POIs), such as landmarks, businesses, or public facilities.
Routes APIs are designed to provide navigation capabilities and distance calculations.
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,
This will be helpful to secure the API key and prevent misuse of it. which eventually prevents unwanted high billing.
We’ll now explore how to use the Geocoding API in both Frontend and Backend(Web server API) environments.
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.
<!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
.
geocoding.ts
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.
<body>
<script type="module" src="geocoding.js"></script>
</body>
Latitude: 37.4225018
Longitude: -122.0847402
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.
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),
};
};
console.error(
"Address: " + JSON.stringify(extractLocation(results[0].address_components))
);
Address: {"area":"Mountain View","city":"Mountain View","state":"California","pincode":"94043"}
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 });
}
});
const GEOCODING_API_URL = 'https://maps.googleapis.com/maps/api/geocode/json';
const apiKey = process.env.GOOGLE_MAPS_API_KEY;
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,
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,
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 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.