py4u blog

Python | Fetch Nearest Hospital Locations using Google Maps API

In today's digital age, having access to location-based information is crucial. Whether it's for emergency situations or general convenience, knowing the nearest hospital locations can be a lifesaver. Google Maps API provides a powerful set of tools to work with location data. In this blog, we'll explore how to use Python to fetch the nearest hospital locations using the Google Maps API.

2026-07

Table of Contents#

  1. Prerequisites
  2. Setting up the Google Maps API
  3. Python Libraries Required
  4. Code Implementation
  5. Common Practices and Best Practices
  6. Example Usage
  7. References

Prerequisites#

  • You need a Google Cloud Platform account. If you don't have one, you can sign up here.
  • Enable the Google Maps JavaScript API and the Places API in your Google Cloud Console. These APIs are used to interact with Google Maps and fetch place details respectively.
  • Obtain an API key. This key will be used to authenticate your requests to the Google Maps API.

Setting up the Google Maps API#

  1. Create a Project: Log in to the Google Cloud Console. Create a new project (if you haven't already) by clicking on the project dropdown at the top and selecting "New Project".
  2. Enable APIs: Navigate to the "APIs & Services" section. Search for "Google Maps JavaScript API" and "Places API" and enable them for your project.
  3. Create API Key: Go to the "Credentials" tab. Click on "Create Credentials" and select "API Key". Copy the generated API key. Keep it safe as it will be used in your Python code.

Python Libraries Required#

  • requests: This library is used to make HTTP requests to the Google Maps API. You can install it using pip install requests.
  • json: Python's built-in library for working with JSON data. The Google Maps API returns data in JSON format, so this library will be used to parse the response.

Code Implementation#

Here's a sample Python code to fetch the nearest hospital locations:

import requests
import json
 
# Replace this with your actual API key
API_KEY = "YOUR_API_KEY"
 
# Latitude and longitude of the center point (e.g., your current location)
latitude = 37.7749
longitude = -122.4194
 
# URL for the Google Maps Places API request
url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={latitude},{longitude}&radius=5000&type=hospital&key={API_KEY}"
 
# Make the request
response = requests.get(url)
 
# Parse the JSON response
data = json.loads(response.text)
 
# Check if the request was successful (status code 200)
if response.status_code == 200:
    # Iterate over the results (hospitals)
    for result in data['results']:
        print("Hospital Name:", result['name'])
        print("Address:", result['vicinity'])
        print("Rating:", result.get('rating', 'N/A'))
        print("-----------------------")
else:
    print("Error:", data['status'])

Explanation of the Code#

  • API Key: Replace "YOUR_API_KEY" with the actual API key you obtained from the Google Cloud Console.
  • Latitude and Longitude: You can change these values to the location from which you want to search for hospitals. You can get your current location's latitude and longitude using various methods (e.g., mobile device's location services or IP-based geolocation).
  • URL Construction: The URL is constructed using the base URL for the nearbysearch endpoint of the Places API. The location parameter is set to the latitude and longitude. The radius parameter (here set to 5000 meters) determines the search radius. The type parameter is set to hospital to filter the results.
  • Request and Parsing: The requests.get method is used to make the HTTP GET request to the API. The response is then parsed using json.loads to convert the JSON data into a Python dictionary. If the request is successful (status code 200), the code iterates over the results (each representing a hospital) and prints out relevant details like name, address, and rating (if available).

Common Practices and Best Practices#

Common Practices#

  • Error Handling: Always check the status code of the API response. As shown in the code above, if the status code is not 200, it indicates an error. You can handle different error statuses gracefully (e.g., ZERO_RESULTS if no hospitals are found in the area).
  • Rate Limiting: The Google Maps API has rate limits. Be aware of them and design your application to handle cases where you might exceed the limits (e.g., caching results for a short period if the data doesn't change frequently).

Best Practices#

  • Security: Keep your API key secure. Don't hardcode it in publicly accessible code repositories. You can use environment variables to store the API key. For example, in Python, you can use the os library:
import os
 
API_KEY = os.environ.get('GOOGLE_MAPS_API_KEY')

And set the environment variable in your system (e.g., export GOOGLE_MAPS_API_KEY="YOUR_API_KEY" in a Unix-like system).

  • User Experience: When displaying the hospital locations, consider using a mapping library (like folium in Python) to show the results on an interactive map. This provides a better user experience compared to just printing text.

Example Usage#

Suppose you are in San Francisco (latitude 37.7749, longitude -122.4194). Running the above code will search for hospitals within a 5000-meter radius. It will print out the names, addresses, and ratings (if available) of the nearby hospitals.

References#

By following this guide, you can easily integrate the functionality of fetching nearest hospital locations using the Google Maps API in your Python applications. You can further enhance it by adding more features like distance calculation between the user's location and each hospital or integrating it with a user interface.