Get Longitude and Latitude from Address using Google Maps API

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

app = FastAPI()

# The builder needs to provide the Google Maps API key via the Env Secrets tab.
# The environment variable name should be GOOGLE_MAPS_API_KEY.
@app.post("/get_address_coordinates", summary="Get Address Coordinates", description="Fetches latitude and longitude based on address using Google Maps API.")
async def get_address_coordinates(address: str = Form(...)):
    google_maps_api_key = os.environ.get('GOOGLE_MAPS_API_KEY')
    if not google_maps_api_key:
        raise HTTPException(status_code=500, detail="Google Maps API key is not set.")
    try:
        # The Google Maps Geocoding API endpoint
        url = f"https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={google_maps_api_key}"
        response = requests.get(url)
        response.raise_for_status()
        geocode_data = response.json()
        if geocode_data['status'] == 'OK':
            # Extracting latitude and longitude from the first result
            latitude = geocode_data['results'][0]['geometry']['location']['lat']

About this template

This application is a FastAPI web server that provides an endpoint to fetch the geographical coordinates (latitude and longitude) of a given address. The endpoint /get_address_coordinates accepts an address as input and uses the Google Maps Geocoding API to fetch the corresponding coordinates. The application requires a Google Maps API key to function. This key should be provided via the environment variable GOOGLE_MAPS_API_KEY

Introduction to the Template

Welcome to the "Get Longitude and Latitude from Address using Google Maps API" template. This template is designed to help you quickly set up a FastAPI web server that provides an endpoint to fetch geographical coordinates based on a given address. It's a straightforward and efficient way to integrate location-based services into your applications.

Clicking Start with this Template

To begin using this template, simply click on the "Start with this Template" button. This will initialize the template in the Lazy Builder interface, pre-populating the code for you.

Initial Setup

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

  • Visit the Google Cloud Platform Console.
  • Create a new project or select an existing one.
  • Go to the "APIs & Services" dashboard, and enable the Geocoding API for your project.
  • Go to the "Credentials" page and click on "Create credentials" to generate a new API key.
  • Copy the generated API key.
  • In the Lazy Builder interface, navigate to the Environment Secrets tab.
  • Create a new secret with the name GOOGLE_MAPS_API_KEY and paste your copied API key as the value.

Test: Pressing the Test Button

Once you have set up your Google Maps API key in the Environment Secrets, you can test the application by pressing the "Test" button. This will deploy your app and launch the Lazy CLI.

Entering Input

After pressing the "Test" button, the Lazy App's CLI interface will appear. You will be prompted to provide the address for which you want to fetch the coordinates. Enter the address as instructed by the CLI.

Using the App

After entering the address, the application will process your request and return the latitude and longitude of the specified address. You will receive a server link through the Lazy builder CLI to interact with the API. Additionally, since this template uses FastAPI, you will also be provided with a link to the API documentation, which can be used to explore other available endpoints and their usage.

Integrating the App

If you wish to integrate this API into an external service or frontend, you can use the server link provided by Lazy. Here's a sample request you might make to the API:


POST /get_address_coordinates
Content-Type: application/x-www-form-urlencoded

address=1600+Amphitheatre+Parkway,+Mountain+View,+CA

And here's a sample response you might receive:


{
  "latitude": 37.4224764,
  "longitude": -122.0842499
}

Use the provided server link to send requests from your external service or frontend to fetch coordinates for different addresses. Ensure that you handle user input securely and validate it before sending it to the API.

By following these steps, you can seamlessly integrate the "Get Longitude and Latitude from Address using Google Maps API" template into your application, providing valuable location-based functionalities to your users.

Category
Technology
Last published
July 26, 2024

More templates like this

SecureUserAuthenticator

Develop a secure User Authentication system for users to register, log in, and manage their profiles, laying the foundation for user-specific data management and permissions in the CMS.

Laravel
Python
Flask
Javascript

Simple Multiplayer Telegram game

This app is a simple frontend for a game where users can upvote and downvote the most popular word in their country, learn about the flags of other countries, and view what other people voted for on a leaderboard.

Telegram
Python
Javascript

MP3ify: Youtube to MP3 Converter

A web application that allows users to download YouTube videos from URLs and provides the option to convert them to MP3 format.

Python
Flask
Home
/
Get Longitude and Latitude from Address using Google Maps API