Skip to main content

Command Palette

Search for a command to run...

Building a Simple Hospital Finder with Python and Google Maps API

Updated
4 min read
Building a Simple Hospital Finder with Python and Google Maps API

By Tracy Ouma
Still learning, still building, still breaking stuff!


Ever found yourself Googling “hospital near me” during an emergency?

Yeah, same here. It’s something we take for granted—until we actually need it. So one day, while learning how to work with APIs and Python, I thought:
“Why not build a script that helps people find hospitals in Nairobi?”

I had just started experimenting with APIs, and Google Maps felt like a good place to start. Fast forward a few hours of coding (and a few hours of debugging ), and boom—I had a working hospital locator script running in my terminal!

And guess what? I later turned it into a full-blown website.
🚀 Check it out here!


What the Script Does

At its core, the script asks the user to enter a location in Nairobi, and it:

✅ Gets the GPS coordinates using Google Maps Geocoding API
✅ Checks if the location is actually in Nairobi
✅ Uses the Places API to search for hospitals within a 5 km radius
✅ Fetches detailed info like:

  • Name

  • Address

  • Phone number

  • Ratings

  • A few real user reviews

Then it prints all that nicely in your terminal.


A Bit of Code Talk (Don’t Worry, It's Chill)

The script is built in Python and uses the googlemaps package to access the API. I also used:

  • dotenv to store my API key safely in a .env file

  • .gitignore to avoid accidentally pushing secrets to GitHub (lesson learned early )

Here’s a snippet of what the code looks like under the hood:

gmaps = googlemaps.Client(key=API_KEY)
geocode_result = gmaps.geocode(f'{location_query}, Nairobi', components={"country":"KE"})
places_result = gmaps.places_nearby(location=loc_coords, radius=5000, keyword='hospital')

From there, I loop through each result, fetch details using the place ID, and store them in a cleaner format.


Adding Structure with a Hospital Class

Once I had the raw data coming in from the Google Maps API, it was kind of messy to just keep printing out dictionaries. So, I created a Hospital class to keep things clean and more object-oriented. This also made it easier to reuse and manage data.

Here’s what the class looks like:

class Hospital:
    def __init__(self, name, address, contact, rating=None, reviews=None, accepts_insurance=None):
        self.name = name
        self.address = address
        self.contact = contact
        self.rating = rating
        self.reviews = reviews or []
        self.accepts_insurance = accepts_insurance

    def __repr__(self):
        return f"Hospital(Name:{self.name}, Contact:{self.contact}, Rating:{self.rating})"

    def display_reviews(self):
        if not self.reviews:
            print("No reviews found!")
            return
        print("Recent reviews:")
        for review in self.reviews[:4]:  # Just show the latest 4
            print(f" - Rating: {review.get('rating')} stars")
            print(f"   Review: {review.get('text', 'N/A')}")
            print(f"   Author: {review.get('author_name', 'Anonymous')}")
            print("-" * 20)

So, what’s going on here?

  • The __init__ method sets up the hospital's basic info (name, address, contact, rating, etc.)

  • The __repr__ method gives a clean summary when you print the object.

  • The display_reviews() method prints up to 4 recent user reviews.


Why Use a Class?

Using a class made the code more organized and scalable. Instead of working with messy dictionaries from the API, each hospital is now its own object with clean properties and methods.

This came in super handy when I started looping through results and displaying them in the terminal — and later in the frontend.


Wrapping It Up with a Static Method

To tie it all together, I created a static method that turns the raw data into usable Hospital objects:

@staticmethod
def get_hospitals_as_objects(location):
    hospital_data = fetch_hospitals(location)
    hospitals_to_display = []

    for data in hospital_data:
        hospital_object = Hospital(
            name=data['name'], 
            address=data['address'], 
            contact=data['contact'],
            rating=data['rating'],  
            reviews=data['reviews']
        )
        hospitals_to_display.append(hospital_object)

    return hospitals_to_display

It basically:

  1. Takes a user’s input like "Kilimani"

  2. Calls fetch_hospitals() to get the data from Google Maps

  3. Converts that data into clean, easy-to-use Hospital objects

  4. Returns the list so I can do whatever I want with it (display in terminal, or send to frontend)


Security Basics: API Key in .env

One of the first things I learned the hard way was:
Never ever push your API keys to GitHub.

That’s why I used the dotenv package and created a .env file like:

GOOGLE_MAPS_API_KEY=your_actual_key_here

And then added .env to .gitignore so it doesn't get pushed to the repo.

Here's the GitHub repo if you want to see the full code.


What I Learned

  • Working with external APIs

  • Handling JSON responses in Python

  • Organizing code using classes and methods

  • Safely managing environment variables

  • Deploying a simple web app using Vercel


Future Plans

This is just a start! I’m thinking of adding:

  • Filter hospitals by insurance accepted

  • Show open/close status

  • Add maps view in the website

  • Make it work for other counties in Kenya too!


Final Thoughts

If you're also learning Python and looking for a fun mini-project that connects the real world to your code, this one’s totally worth trying. Not only do you practice working with APIs, but you also build something that actually helps people.

Let me know what you think or if you have ideas to improve it!

GitHub: @TracyOuma
Web App: medical-facilities.vercel.app

Happy coding!!