Find Distance Between Two Points with Google Maps API

 import os
import requests
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel, Field

app = FastAPI()

GOOGLE_MAPS_API_KEY = os.environ['GOOGLE_MAPS_API_KEY']

class DistanceParams(BaseModel):
    starting_latitude: float = Field(..., description="Latitude of the starting point")
    starting_longitude: float = Field(..., description="Longitude of the starting point")
    destination_latitude: float = Field(..., description="Latitude of the destination point")
    destination_longitude: float = Field(..., description="Longitude of the destination point")

def get_google_maps_distance(starting_latitude: float, starting_longitude: float, destination_latitude: float, destination_longitude: float) -> str:
    endpoint = f"https://maps.googleapis.com/maps/api/distancematrix/json?origins={starting_latitude},{starting_longitude}&destinations={destination_latitude},{destination_longitude}&key={GOOGLE_MAPS_API_KEY}"
    response = requests.get(endpoint)
    distance_info = response.json()
    try:
        distance = distance_info['rows'][0]['elements'][0]['distance']['text']
        return distance
    except (IndexError, KeyError) as e:
        raise HTTPException(status_code=400, detail="Could not calculate distance with the provided information.") from e

About this template

This is a FastAPI application that calculates the distance between two geographical points using the Google Maps API. Users input latitude and longitude of both points, and the app returns the distance. It requires a Google Maps API key stored in an environment variable ‘GOOGLE_MAPS_API_KEY’.

Introduction to the Find Distance Between Two Points with Google Maps API Template

Welcome to the Lazy template guide for calculating the distance between two geographical points using the Google Maps API. This template is designed to help you quickly set up a FastAPI application that takes latitude and longitude inputs for two locations and returns the distance between them. This is an ideal solution for builders looking to integrate distance calculations into their applications without delving into the complexities of API integrations and server setups.

Clicking Start with this Template

To begin using this template, simply click on the "Start with this Template" button. This will pre-populate the code in the Lazy Builder interface, so you won't need to copy, paste, or delete any code manually.

Initial setup: Adding Environment Secrets

Before you can use the template, you need to set up an environment secret for the Google Maps API key. Here's how to do it:

  • Visit the Google Cloud Platform Console to obtain your API key.
  • Once you have your API key, go to the Environment Secrets tab within the Lazy Builder.
  • Create a new secret with the key `GOOGLE_MAPS_API_KEY` and paste your Google Maps API key as the value.

Test: Pressing the Test Button

With the environment secret set, you're ready to test the application. Press the "Test" button to begin the deployment of the app. The Lazy CLI will handle the deployment process, and you won't need to install any libraries or set up your environment.

Entering Input

After pressing the "Test" button, if the application requires any user input, the Lazy App's CLI interface will prompt you to provide it. For this template, you will need to input the latitude and longitude for both the starting point and the destination point when you interact with the API.

Using the App

Once the app is deployed, Lazy will provide you with a dedicated server link to use the API. Additionally, since this template uses FastAPI, you will also receive a link to the API documentation, which will guide you on how to interact with the API endpoints.

To calculate the distance between two points, you will make a POST request to the `/get_distance` endpoint with a JSON payload containing the starting and destination latitude and longitude. Here's a sample request:


{
  "starting_latitude": 34.052235,
  "starting_longitude": -118.243683,
  "destination_latitude": 40.712776,
  "destination_longitude": -74.005974
}

And here's what a sample response might look like:


{
  "distance": "2,448 miles"
}

Integrating the App

If you wish to integrate this distance calculation feature into another service or frontend, you can use the server link provided by Lazy to make API requests from your application. Ensure that you handle the API responses appropriately and display the distance information to your users as needed.

Remember, this template is designed to simplify the process of integrating Google Maps distance calculations into your application. By following these steps, you can quickly set up and deploy your distance calculation feature using the Lazy platform.

Category
Technology
Last published
July 26, 2024

More templates like this

Backend Server

This skeleton is streamlined for creating backend services using FastAPI. It's an excellent choice for building microservices or APIs with minimal frontend requirements.

Fast API
Python

Login and Registration

This powerful app skeleton is a good starting place for apps that require login and registration

Laravel
Fast API
Flask

GET LAZY APP APPLICATION LAUNCHER - Paid Subscriptions

The Get Lazy application Launcher is used to launch and monitor your apps in a production environment - For paid subscriptions only.

Fast API
Python
Home
/
Find Distance Between Two Points with Google Maps API