[Python] Google Maps API Get SIZE of Image

Discussão em 'Python' iniciado por Stack, Setembro 11, 2024.

  1. Stack

    Stack Membro Participativo

    Hi I am new to the Google Maps API but have made some good progress and currently have an web page that can retrieve an Earth image based on an address input. My webpage allows the user to draw area on the picture and a square footage is returned along with some other features. This involves getting the square footage of the image itself. As far as I know this isn't something the API returns in my research but I am not 100% certain. I need a way that when I gather the map it return the exact square footage(L*W) that the image is displaying. I have the following code and as you can see I tried using an equation to calculate the square footage but it is a few thousand too large and I cannot get it to work. Any help is much appreciated.

    import requests
    import math


    def get_satellite_image(address, zoom, api_key='AIzaSyABaIDoWhLWCpZlDNRTGTilkpzCO9EhvQE', size="650x650", map_type="satellite"):
    # takes the address and gets the lat and long of it
    geocode_url = f"https://maps.googleapis.com/maps/api/geocode/json?address={address}&key={api_key}"
    geocode_response = requests.get(geocode_url).json()
    formatted_address = geocode_response['results'][0]['formatted_address']

    if geocode_response['status'] != 'OK':
    print('Lat and Long of address not found')
    else:
    location = geocode_response['results'][0]['geometry']['location']
    lat, lng = location['lat'], location['lng']
    # retrieve the map image from the api
    static_map_url = f"https://maps.googleapis.com/maps/api/staticmap?center={lat},{lng}&zoom={zoom}&size={size}&maptype={map_type}&key={api_key}"
    # save image to location specified
    response = requests.get(static_map_url)
    if response.status_code == 200:
    square_feet = ((156543.03392 * abs(math.cos(math.radians(lat))) / (2 ** int(zoom))) ** 2) * int(size.split('x')[0]) * int(size.split('x')[1]) * 10.7639
    print('squarefeet:', square_feet)
    # 'geocode_response['results'][0]['formatted_address']' uses formatted address for uniformity
    with open('media/' + geocode_response['results'][0]['formatted_address'].replace(' ', '_') + str(zoom) + '.png', 'wb') as file:
    file.write(response.content)
    return {'square_feet': square_feet, 'formatted_address': formatted_address}
    else:
    raise Exception(f"Error fetching satellite image: {response.status_code}")

    Continue reading...

Compartilhe esta Página