Skip to content

Instantly share code, notes, and snippets.

@RodolfoFerro
Last active November 22, 2020 03:45
Show Gist options
  • Save RodolfoFerro/7d9ea7d48753035a7c723960477451ec to your computer and use it in GitHub Desktop.
Save RodolfoFerro/7d9ea7d48753035a7c723960477451ec to your computer and use it in GitHub Desktop.
Python/JS script to consume Google Maps API in order to transform a textual address into (lat, long) coordinates.
var coords = [];
async function convert_address(address, API_KEY) {
// Parse address
var city = "+Ciudad+de+México";
var state = "+CDMX";
var parsed_address = address.replace(', ', '+');
parsed_address = parsed_address.replace(' ', '+');
parsed_address = parsed_address.concat(city);
parsed_address = parsed_address.concat(state);
// Set API call params
var params = `key=${API_KEY}&address=${parsed_address}`;
var url = `https://maps.googleapis.com/maps/api/geocode/json?${params}`;
// Consume Maps API
const request = await fetch(url)
.then( res => res.json() )
.then( data => {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
coords = [lat, lng];
console.log(coords);
console.log([lat, lng]);
})
return coords;
}
import requests
import re
def convert_address(address, API_KEY):
"""Function to convert textual addresses into (lat, long) coordinates.
Parameters
----------
address : str
A string containing the raw textual address to be converted.
API_KEY : str
A Google Maps API Key.
Returns
-------
(lat, long) : tuple
A tuple containing the latitude and longitude of the address.
"""
# Parse address
city = "+Ciudad+de+México"
state = "+CDMX"
parsed_address = re.sub(', ', '+', address)
parsed_address = re.sub(' ', '+', parsed_address)
parsed_address += city
parsed_address += state
# Consume Maps API
GMAPS_API_URL = 'https://maps.googleapis.com/maps/api/geocode/json'
params = {
'address': parsed_address,
'sensor': 'false',
'region': 'mx',
'key': API_KEY
}
# Do the request and get the response data
req = requests.get(GMAPS_API_URL, params=params)
res = req.json()
# Use the first result
result = res['results'][0]
lat = result['geometry']['location']['lat']
lng = result['geometry']['location']['lng']
return (lat, lng)
if __name__ == "__main__":
API_KEY = ""
print("Ingresa una dirección.")
print("Por favor, asegúrate de que sea calle, número y colonia.")
address = input("> ")
lat, lng = convert_address(address, API_KEY)
print(lat, lng)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment