Friday, 14 December 2018

how to use the google elevation api








Below is a code written in python to send get requests to the google elevation api and then store
the results into an sqlite database.
Make appropriate changes to the code as mentioned in the comments before executing the code.


Go here to get your own api key




import requests
import sqlite3
import json

key = '<paste your google api key here>' #google api key
#sqlite connection
conn = sqlite3.connect('<path to your sqlite database>')
id = 1
#api end point
base_url = 'https://maps.googleapis.com/maps/api/elevation/json?'
number_of_coordinates = 4610
while (id < number_of_coordinates):    
   instanceOfRow = conn.execute("SELECT * from forlake WHERE Number=?",(id,))
   row = instanceOfRow.fetchall()
   latitude = row[0][2]
   longitude = row[0][3]
   url = base_url + 'locations=' + str(latitude) + ',' + str(longitude) + '&key=' + key #constructing api endpoint
   api_response = requests.get(url)
   data = api_response.json()
   conn.execute("UPDATE forlake SET elevation = ? WHERE Number = ?",(data["results"][0]['elevation'],id,))
   if id%100 == 0:
       conn.commit() #commit changes in the database after every 100 records
       print id
   id = id + 1

conn.commit()    
print 'done'



1 comment:

  1. Works perfect. Most useful for Ecosystem services research work. One can model the terrain with many parameters and simulate.

    ReplyDelete