Python client library for Google Maps API Web Services

Overview

Python Client for Google Maps Services

Build Status codecov PyPI version PyPI - Downloads GitHub contributors

Description

Use Python? Want to geocode something? Looking for directions? Maybe matrices of directions? This library brings the Google Maps Platform Web Services to your Python application.

The Python Client for Google Maps Services is a Python Client library for the following Google Maps APIs:

  • Directions API
  • Distance Matrix API
  • Elevation API
  • Geocoding API
  • Geolocation API
  • Time Zone API
  • Roads API
  • Places API
  • Maps Static API

Keep in mind that the same terms and conditions apply to usage of the APIs when they're accessed through this library.

Support

This library is community supported. We're comfortable enough with the stability and features of the library that we want you to build real production applications on it. We will try to support, through Stack Overflow, the public and protected surface of the library and maintain backwards compatibility in the future; however, while the library is in version 0.x, we reserve the right to make backwards-incompatible changes. If we do remove some functionality (typically because better functionality exists or if the feature proved infeasible), our intention is to deprecate and give developers a year to update their code.

If you find a bug, or have a feature suggestion, please log an issue. If you'd like to contribute, please read contribute.

Requirements

  • Python 3.5 or later.
  • A Google Maps API key.

API Keys

Each Google Maps Web Service request requires an API key or client ID. API keys are generated in the 'Credentials' page of the 'APIs & Services' tab of Google Cloud console.

For even more information on getting started with Google Maps Platform and generating/restricting an API key, see Get Started with Google Maps Platform in our docs.

Important: This key should be kept secret on your server.

Installation

$ pip install -U googlemaps

Note that you will need requests 2.4.0 or higher if you want to specify connect/read timeouts.

Usage

This example uses the Geocoding API and the Directions API with an API key:

import googlemaps
from datetime import datetime

gmaps = googlemaps.Client(key='Add Your Key here')

# Geocoding an address
geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')

# Look up an address with reverse geocoding
reverse_geocode_result = gmaps.reverse_geocode((40.714224, -73.961452))

# Request directions via public transit
now = datetime.now()
directions_result = gmaps.directions("Sydney Town Hall",
                                     "Parramatta, NSW",
                                     mode="transit",
                                     departure_time=now)

For more usage examples, check out the tests.

Features

Retry on Failure

Automatically retry when intermittent failures occur. That is, when any of the retriable 5xx errors are returned from the API.

Building the Project

# Installing nox
$ pip install nox

# Running tests
$ nox

# Generating documentation
$ nox -e docs

# Copy docs to gh-pages
$ nox -e docs && mv docs/_build/html generated_docs && git clean -Xdi && git checkout gh-pages

Documentation & resources

Documentation for the google-maps-services-python library

Getting started

API docs

Support

Comments
  • get current location with geolocate

    get current location with geolocate

    Hi, I want to get the current location based on this link but I can't find any python example to do that. I want to create a general code to get the current location. I used this part of code but it didn't work.

    import googlemaps
    gmaps = googlemaps.Client(key='my_key')
    loc = gmaps.geolocate()
    print(loc)
    

    Thanks.

    opened by masoudr 12
  • Library does not detect SSL certificates

    Library does not detect SSL certificates

    I tried the basic example code... but I'm stuck with this:

    /usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:79: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
      InsecurePlatformWarning
    Traceback (most recent call last):
      File "get_times.py", line 6, in <module>
        geocode_result = gmaps.geocode('1600 Amphitheatre Parkway, Mountain View, CA')
      File "/usr/local/lib/python2.7/dist-packages/googlemaps/geocoding.py", line 68, in geocode
        return client._get("/maps/api/geocode/json", params)["results"]
      File "/usr/local/lib/python2.7/dist-packages/googlemaps/client.py", line 205, in _get
        raise googlemaps.exceptions.TransportError(e)
    googlemaps.exceptions.TransportError: [Errno 1] _ssl.c:510: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
    

    I can't see any way in the library API to point to the certificate. Where should I get this certificate and how to make the library see it?

    opened by macwis 9
  • Traffic model bug?

    Traffic model bug? "optimistic" slower than "best-guess"

    Hello, I found that traffic_model="optimistic" sometimes takes longer than traffic_model="best guess". I don't know if this is because of the library or because of Google Maps, but I thought I'd ask, because it makes me question the results using "optimistic" more generally. That is, maybe the results using "optimistic" are not reliable in general.

    The graph plots the travel time using the three traffic_model options, for all departure times on a particular day (in the future). Note how during the night the "optimisitic" is slower than the other two. image

    Also, here is code that generates this for a particular leaving time.

    Code output:

    ['Travel time from: 12.979572,80.25271 to 12.921726,80.230478']
    ['Departure time (local): 16 Dec 2015 03:42:02']
    ['Time, no traffic, minutes: 12.566666666666666']
    ['Time in traffic, minutes: 9.45']
    ['Time in traffic (optimistic), minutes: 10.45']
    

    Code:

    __author__ = 'Gabriel Kreindler, [email protected]'
    
    '''
    This code shows that the traffic_model option sometimes generates counter-intuitive results.
    The option traffic_model="optimistic" sometimes generates longer travel times compared to "best_guess" or "pessimistic".
    (The latter is not shown here.)
    '''
    
    import googlemaps
    import time
    import calendar
    
    # client
    client = googlemaps.Client(key='KEY HERE')
    
    # origin and destination
    orig="12.979572,80.25271"
    dest="12.921726,80.230478"
    
    # query time
    t1 = time.strptime("15 Dec 2015 22:12:02", "%d %b %Y %H:%M:%S")
    nsec1 = calendar.timegm(t1)
    
    # get offset
    timezone_offset = client.timezone(orig, timestamp=nsec1)
    timezone_offset_sec = timezone_offset['rawOffset']
    
    # nice local time
    t1_loc = time.gmtime(nsec1 + timezone_offset_sec) # local time
    dep_time_local = time.strftime("%d %b %Y %H:%M:%S", t1_loc)
    
    
    # get duration in traffic
    dist = client.distance_matrix(orig, dest, departure_time=nsec1, mode="driving")
    
    # parse
    temp = dist["rows"][0]["elements"][0]
    assert temp["status"]=="OK"
    dist_output = temp["distance"]["value"]
    dur_output = temp["duration"]["value"]  # duration
    dur_intraffic_output = temp["duration_in_traffic"]["value"]
    
    # get duration in traffic
    dist = client.distance_matrix(orig, dest, departure_time=nsec1, mode="driving", traffic_model="optimistic")
    
    # parse
    temp = dist["rows"][0]["elements"][0]
    assert temp["status"]=="OK"
    dur_intraffic_opt_output = temp["duration_in_traffic"]["value"]
    
    print(['Travel time from: ' + orig + ' to ' + dest])
    print(['Departure time (local): ' + dep_time_local])
    print(['Time, no traffic, minutes: ' + str(dur_output/60)])
    print(['Time in traffic, minutes: ' + str(dur_intraffic_output/60)])
    print(['Time in traffic (optimistic), minutes: ' + str(dur_intraffic_opt_output/60)])
    
    opened by Gkreindler 9
  • How to prefix via: to waypoints for directions API?

    How to prefix via: to waypoints for directions API?

    I read the following doc

    The duration in traffic is returned only if all of the following are true:
    
    1. The request includes a valid API key, or a valid Google Maps APIs Premium Plan client ID and signature.
    2. The request does not include stopover waypoints. If the request includes waypoints, they must be prefixed with via: to avoid stopovers.
    3. The request is specifically for driving directions—the mode parameter is set to driving.
    4. The request includes a departure_time parameter.
    5. Traffic conditions are available for the requested route.
    

    For condition 2, how do I prefix via: to the waypoints. I have a list of coordinates.

    type: docs priority: p3 released 
    opened by debugger22 8
  • Hello Sir, Can I use googleearthengine data on gmaps ?

    Hello Sir, Can I use googleearthengine data on gmaps ?

    Thanks for stopping by to let us know something could be better!


    PLEASE READ

    If you have a support contract with Google, please create an issue in the support console. This will ensure a timely response.

    Discover additional support services for the Google Maps Platform, including developer communities, technical guidance, and expert support at the Google Maps Platform support resources page.

    If your bug or feature request is not related to this particular library, please visit the Google Maps Platform issue trackers.

    Check for answers on StackOverflow with the google-maps tag.


    Is your feature request related to a problem? Please describe. A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

    Describe the solution you'd like A clear and concise description of what you want to happen.

    Describe alternatives you've considered A clear and concise description of any alternative solutions or features you've considered.

    Additional context Add any other context or screenshots about the feature request here.

    type: feature request triage me 
    opened by vijaygrg27 7
  • Road snap some points not returned

    Road snap some points not returned

    Some of the paths that I send to the road snap API do not come back as I would expect.

    If for instance I pass in X number of coordinate pairs (interpolate is on, btw), and I receive Y pairs back, where Y > X, I may not receive all of my originalIndex pairs back.

    So, I may have on the return: [{originalIndex: 0}, new_0, new_1, new_2, {originalIndex: 3}, ...]

    What does this behavior mean? And what should I do with the pair(s) that are not returned from the API?

    needs more info type: question priority: p3 stale 
    opened by jheld 7
  • Support reverse_geocode by place_id

    Support reverse_geocode by place_id

    Add support for reverse geocoding by place_id in addition to existing lat/lng. Doesn't change interface, just checks for a string that begins with something other than a digit or a +/- sign. Treats such strings as place_ids, otherwise behaves like current code.

    opened by wilkens 7
  • out of daily quota requests must not be retried, they must be immediately failed instead

    out of daily quota requests must not be retried, they must be immediately failed instead

    The library keeps retrying requests that are rejected by the REST API with the following. I think this is not correct behavior. It masks what exactly is happening from the the python API developer and it does not matter how long you retry it will keep failing until the next day.

    {u'status': u'OVER_QUERY_LIMIT', u'rows': [], u'error_message': u'You have exceeded your daily request quota for this API.', u'destination_addresses': [], u'origin_addresses': []}

    image

    opened by gae123 7
  • feat: Geocode by place id

    feat: Geocode by place id

    Geocode endpoint accepts a place_id param as an alternative to geocode Google docs: https://developers.google.com/maps/documentation/geocoding/requests-places-geocoding

    Thank you for opening a Pull Request!


    Before submitting your PR, there are a few things you can do to make sure it goes smoothly:

    • [ ] Make sure to open a GitHub issue as a bug/feature request before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea
    • [ ] Ensure the tests and linter pass
    • [ ] Code coverage does not decrease (if any source code was changed)
    • [ ] Appropriate docs were updated (if necessary)

    Fixes #<issue_number_goes_here> 🦕

    released 
    opened by andyklimczak 6
  • feat: place_details in places.py for phone number and many other details

    feat: place_details in places.py for phone number and many other details

    Thank you for opening a Pull Request!


    Before submitting your PR, there are a few things you can do to make sure it goes smoothly:

    • [ ] Make sure to open a GitHub issue as a bug/feature request before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea
    • [ ] Ensure the tests and linter pass
    • [ ] Code coverage does not decrease (if any source code was changed)
    • [ ] Appropriate docs were updated (if necessary)

    Fixes #<issue_number_goes_here> 🦕

    cla: yes 
    opened by badrivamsi 6
  • Set base_url default value inside _request() instead of in signature

    Set base_url default value inside _request() instead of in signature

    If an end-user of the library wants to override _DEFAULT_BASE_URL (e.g. in order to use a proxy), this makes it easier. The user can simply run

    googlemaps.client._DEFAULT_BASE_URL = 'http://my_proxy_dns'
    

    in their server/script's startup code.

    Without this change, the default value for the parameter gets "baked" into the function definition and is harder to change.

    (Obviously a module's internal implementation details are subject to change, and this PR doesn't construe a guarantee that overriding _DEFAULT_BASE_URL will continue to work in the future).

    opened by kerrick-lyft 6
  • feat: add the ability to filter place reviews by newest.

    feat: add the ability to filter place reviews by newest.

    Thank you for opening a Pull Request!


    Before submitting your PR, there are a few things you can do to make sure it goes smoothly:

    • [x] Make sure to open a GitHub issue as a bug/feature request before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea
    • [x] Ensure the tests and linter pass
    • [x] Code coverage does not decrease (if any source code was changed)
    • [x] Appropriate docs were updated (if necessary)

    Fixes #467 🦕

    opened by nnolan 0
  • Add the ability to filter place reviews by newest.

    Add the ability to filter place reviews by newest.

    Thanks for stopping by to let us know something could be better!


    PLEASE READ

    If you have a support contract with Google, please create an issue in the support console. This will ensure a timely response.

    Discover additional support services for the Google Maps Platform, including developer communities, technical guidance, and expert support at the Google Maps Platform support resources page.

    If your bug or feature request is not related to this particular library, please visit the Google Maps Platform issue trackers.

    Check for answers on StackOverflow with the google-maps tag.


    Is your feature request related to a problem? Please describe. I would like to be able to filter place reviews by newest, rather than just the default.

    Describe the solution you'd like I would like to be able to pass a simple parameter to filter for the newest reviews for a place.

    Describe alternatives you've considered There is no alternative, other than using the default filter.

    Additional context Add any other context or screenshots about the feature request here.

    type: feature request triage me 
    opened by nnolan 1
  • feat: find_place: Add location_restriction parameter

    feat: find_place: Add location_restriction parameter

    Google Maps API Find Place requests now support a location restriction parameter which limit results to a specified area. This is unlike the location bias parameter which prefers results in a specified area. The location restriction parameter can be set by specifying either a radius plus lat/lng, or two lat/lng pairs representing the points of a rectangle.


    Before submitting your PR, there are a few things you can do to make sure it goes smoothly:

    • [x] Make sure to open a GitHub issue as a bug/feature request before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea
    • [x] Ensure the tests and linter pass
    • [x] Code coverage does not decrease (if any source code was changed)
    • [ ] Appropriate docs were updated (if necessary)

    Fixes https://github.com/googlemaps/google-maps-services-python/issues/464 🦕

    opened by FinnWoelm 3
  • find_place: location_restriction parameter is not supported

    find_place: location_restriction parameter is not supported

    The Google Maps API now supports a locationrestriction parameter for Find Place requests, which can restrict results to a certain area. This is unlike the locationbias parameter, which prefers results in a certain area.

    image

    See: https://developers.google.com/maps/documentation/places/web-service/search-find-place#locationrestriction

    type: bug triage me 
    opened by FinnWoelm 2
  • FeatReq: support all params of the core addressvalidation API

    FeatReq: support all params of the core addressvalidation API

    https://github.com/googlemaps/google-maps-services-python/blob/5b952d73f8374baac876b4d845fd46cebec6ed7e/googlemaps/addressvalidation.py#L47 currently only accepts a limited number of arguments - see https://developers.google.com/maps/documentation/address-validation/reference/rest/v1/TopLevel/validateAddress#postaladdress

    Our use case is that we know the US state, and want to pass that to the API as hint (in administrativeArea)

    Can easily be solved by adding **kwargs

    opened by yan-hic 1
  • Trigger retry mechanism on invalid requests status

    Trigger retry mechanism on invalid requests status

    Triggering the retry mechanism on invalid requests due to inconsistent behavior in Google Maps API, which is described in issue #366.

    The side effect is that if wrong parameters are provided request won't fail on the first try but will go through a retry mechanism.


    Before submitting your PR, there are a few things you can do to make sure it goes smoothly:

    • [x] Make sure to open a GitHub issue as a bug/feature request before writing your code! That way we can discuss the change, evaluate designs, and agree on the general idea
    • [x] Ensure the tests and linter pass
    • [x] Code coverage does not decrease (if any source code was changed)
    • [x] Appropriate docs were updated (if necessary)

    Fixes #366 🦕

    opened by zkne 1
Releases(v4.7.3)
Owner
Google Maps
Google Maps
ALIEN: idA Local varIables rEcogNizer

ALIEN: idA Local varIables rEcogNizer ALIEN is an IDA Pro plugin that allows the user to get more information about ida local variables with the help

16 Nov 26, 2022
A casino discord bot written in Python

Casino Bot Casino bot is a gambling discord bot I made for my friends. It is able to play blackjack, slots, flip a coin, and roll dice. It stores ever

Connor Swislow 27 Dec 30, 2022
Predict the Site EUI, given the characteristics of the building and the weather data for the location of the building.

wids_datathon_2022 Description: Contains a data pipeline used to predict energy EUI Goals: Dataset exploration Automating the parameter fitting, gener

1 Mar 25, 2022
Sielzz Music adalah proyek bot musik telegram, memungkinkan Anda memutar musik di telegram grup obrolan suara.

Hi, I am: Requirements 📝 FFmpeg NodeJS nodesource.com Python 3.8 or higher PyTgCalls MongoDB Get STRING_SESSION from below: 🎖 History Features 🔮 Th

1 Nov 29, 2021
A discord http interactions framework built on top of Sanic

snowfin An async discord http interactions framework built on top of Sanic Installing for now just install the package through pip via github # Unix b

kaj 13 Dec 15, 2022
A FORKED AND Modded version of TL:GD for 🅱️3R0K🧲support

for support join here working example group Leech Here For Any Issues/Imrovements or Discussions go here or here Please Leave A star And Fork this Rep

XcodersHub 165 Mar 12, 2022
API Wrapper for seedr.cc

Seedr Python Client Seedr API built with 💛 by Souvik Pratiher Hit that Star button if you like this kind of SDKs and wants more of similar SDKs for o

Souvik Pratiher 2 Oct 24, 2021
Apex lets you build, deploy, and manage AWS Lambda functions with ease.

No longer maintained This software is no longer being maintainted and should not be chosen for new projects. See this issue for more information Apex

Apex 25 Dec 23, 2022
Convenient script for trading with python.

Convenient script for trading with python.

VladKochetov007 66 Dec 07, 2022
Pdisk Link Converter Telegram Bot, Convert link in a single click

Pdisk Converter Bot Make short link by using Pdisk API key Installation The Easy Way Required Variables BOT_TOKEN: Create a bot using @BotFather, and

Ayush Kumar Jaiswal 6 Jul 28, 2022
Projeto Informações Conta do Instagram - Instagram Account Information Project

VESTA-tools A collection of simple tools that proved to be needed for handling large periodic calculations with the VASP software package. distTotCalc

Thiago Souza 1 Dec 02, 2021
Building and deploying AWS Lambda Shared Layers

AWS Lambda Shared Layers This repository is hosting the code from the following blog post: AWS Lambda & Shared layers for Python. The goal of this rep

Flaneer 7 Dec 02, 2021
light wrapper for indeed.com api

Simple wrapper for indeed api. go to indeed.com - register for api publisher token example from indeed import IndeedApi token = 'your token' api =

16 Sep 21, 2022
twtxt is a decentralised, minimalist microblogging service for hackers.

twtxt twtxt is a decentralised, minimalist microblogging service for hackers. So you want to get some thoughts out on the internet in a convenient and

buckket 1.8k Jan 09, 2023
Attempting to create a framework for Discord Slash commands... yes

discord_slash.py Attempting to create a framework for Discord Slash commands... yes Installation pip install slashpy Documentation Coming soon™ Why is

AlexFlipnote 11 Mar 24, 2021
This solution helps you deploy Data Lake Infrastructure on AWS using CDK Pipelines.

CDK Pipelines for Data Lake Infrastructure Deployment This solution helps you deploy data lake infrastructure on AWS using CDK Pipelines. This is base

AWS Samples 66 Nov 23, 2022
veez music bot is a telegram music bot project, allow you to play music on voice chat group telegram.

🎶 Veez Music Bot Music bot for playing music on telegram voice chat group. Requirements 📝 FFmpeg NodeJS nodesource.com Python 3.7+ PyTgCalls 🧪 Get

levina 143 Jun 19, 2022
Python Client for MLflow Tracking Server

Python Client for MLflow Python client for MLflow REST API. Features: Unlike MLflow Tracking client all REST API methods are exposed to user. All clas

MTS 35 Dec 23, 2022
Asynchronous RDP/VNC client for Python (GUI)

🚩 This is the public repository of aardwolf, for latest version and updates please consider supporting us through https://porchetta.industries/ AARDW

29 Dec 15, 2022
A Python app to serve Conveyor room requests and run approvals through Slack

✨ CONVEYOR FOR SLACK ✨ This is a friendly little Python app that will allow you to integrate your instance of Conveyor with your Slack workspace. In o

Vivienne 4 Sep 27, 2021