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
Python module and command line script client for http://urbandictionary.com

py-urbandict py-urbandict is a client for urbandictionary.com. Project page on github: https://github.com/novel/py-urbandict PyPI: https://pypi.org/pr

Roman Bogorodskiy 32 Oct 01, 2022
Lib for create and show QRCode to PIX, you can show this code in another applications for payment by final consumer.

Biblioteca para a geração de codigos QR (BRCode como chamados na documentação do BACEN) a fins de facilitar a exibição para pagamentos ao consumidor.

João Camargo 13 Oct 05, 2022
Linkvertise-Bypass - Bypass Linkvertise advertisement

Linkvertise-Bypass Bypass Linkvertise advertisement 📕 instructions Copy And Pas

Flex Tools 4 Jun 10, 2022
A Discord Bot that tracks and displays cryptocurrencies using the CoinMarketCap API

PyBo - A Crypto Inspired Discord Bot Pybo (paɪ boʊ) is a Discord bot that utilizes the discord.py API wrapper to run the bot. Pybo also integrates the

0 Nov 17, 2022
An API wrapper for Discord written in Python.

discord.py A modern, easy to use, feature-rich, and async ready API wrapper for Discord written in Python. Key Features Modern Pythonic API using asyn

Danny 12k Jan 08, 2023
streamlit translator is used to detect and translate between languages created using gTTS, googletrans, pillow and streamlit python packages

Streamlit Translator Streamlit Translator is a simple translator app to detect and translate between languages. Streamlit Translator gets text and lan

Siva Prakash 5 Apr 05, 2022
QR login for pyrogram client

Generate Pyrogram session via QRlogin

ポキ 18 Oct 21, 2022
Template to create a telegram bot in python

Template for Telegram Bot Template to create a telegram bot in python. How to Run Set your telegram bot token as environment variable TELEGRAM_BOT_TOK

PyTopia 12 Aug 14, 2022
A discord bot that can detect Nitro Scam Links and delete them to protect other users

A discord bot that can detect Nitro Scam Links and delete them to protect other users. Add it to your server from here.

Kanak Mittal 9 Oct 20, 2022
Catinthebox - Awesome bot for Mastodon

Cat In The Box :3 Description Awesome bot for Mastodon Requirements python pip g

satanist 0 Jan 19, 2022
An enhanced discord.py, based off of the now-archived discord.py project

enhanced-discord.py A modern, maintained, easy to use, feature-rich, and async ready API wrapper for Discord written in Python. The Future of enhanced

Devision 2 Dec 21, 2022
Whatsapp-bot - Whatsapp chatbot build with python and twilio

Whatsapp-bot This is a Whatsapp Chatbot that responds with quotes, reply owners

arinzejustinng 1 Jan 14, 2022
Instagram Brute force attack helps you to find password of an instagram account from your list of provided password.

Instagram Brute force attack Instagram Brute force attack helps you to find password of an instagram account from your list of provided password. Inst

Naman Raj Singh 1 Dec 27, 2021
An incomplete add-on extension to Pyrogram, to create telegram bots a bit more easily

PyStark A star ⭐ from you means a lot An incomplete add-on extension to Pyrogram

Stark Bots 36 Dec 23, 2022
A Discord bot for viewing any currency you want comfortably.

Dost Dost is a Discord bot for viewing currencies. Getting Started These instructions will get you a copy of the project up and running on your local

Baran Gökalp 2 Jan 18, 2022
Information about the weather in a city written using Python

Information about the weather in a city Enter the desired city Climate information of the target city This program is written using Python programming

Amir Hussein Sharifnezhad 4 Nov 17, 2021
Group Chat Spammer For Discord

Group Chat Spammer For Discord Free and public gc spammer

Dreamy 20 Dec 27, 2022
WeChat SDK for Python

___ __ _______ ________ ___ ___ ________ _________ ________ ___ ___ |\ \ |\ \|\ ___ \ |\ ____\|\ \|\ \|\ __ \|\___

wechatpy 3.3k Dec 26, 2022
Ghostbuster - Eliminate dangling elastic IPs by performing analysis on your resources within all your AWS accounts

Table of Contents Table of Contents Ghostbuster The problem Project Features Ins

Assetnote 182 Dec 24, 2022
Python package for agilex robotics mobile base platform

This is Python API for Agilex Robotics Mobile base This is a python API for Can communication with Agilex Robotics Mobile base and controlling it. Sup

7 Sep 06, 2022