devwiki:google_api

Google API

  • Google cloud api provides access to google map data
    • you need to create a google cloud project
    • link to a credit card (it is free for under free tier, and it also have some credit for testing)
    • create a key, which use to access google api from your app or program

Google Map API

Google has many access point for different map data,

  • 3d tile: allow access google 3d map data
  • geocode: allow convert your location name to gps
    import requests
    g_api = "YOURKEYTEXT"
     
    def geocode(address, api_key="", info= 0):
        headers = {'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246"}
        if api_key == "":
            api_key = g_api
        geocoding_endpoint = 'https://maps.googleapis.com/maps/api/geocode/json'
        elevation_endpoint = 'https://maps.googleapis.com/maps/api/elevation/json'
        params = {
            'address': address,
            'key': api_key
        }
     
        geocoding_response = requests.get(geocoding_endpoint, params=params, headers=headers)
        geocoding_data = geocoding_response.json()
     
        # Extract the GPS coordinates
        if geocoding_data['status'] == 'OK':
            location = geocoding_data['results'][0]['geometry']['location']
            if info:
                print('''
    #=======================================
    #  {0}
    #======================================='''.format(address))
                pprint.pprint(geocoding_data['results'][0])
            latitude = location['lat']
            longitude = location['lng']
     
            elevation_params = {
                'locations': f'{latitude},{longitude}',
                'key': api_key
            }
            elevation_response = requests.get(elevation_endpoint, params=elevation_params, headers=headers)
            elevation_data = elevation_response.json()
            if elevation_data['status'] == 'OK':
                elevation = elevation_data['results'][0]['elevation']
                if info:
                    pprint.pprint(elevation_data['results'][0])
                return latitude, longitude, elevation
            else:
                return latitude, longitude, None
        else:
            return None
  • devwiki/google_api.txt
  • Last modified: 2023/07/24 08:36
  • by ying