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
Monitoring plugin for MikroTik devices

check_routeros - Monitoring MikroTik devices This is a monitoring plugin for Icinga, Nagios and other compatible monitoring solutions to check MikroTi

DinoTools 6 Dec 24, 2022
Azure free vpn for students only! (Self hosted/No sketchy services/Fast and free)

Azpn-Azure-Free-VPN Azure free vpn for students only! (Self hosted/No sketchy services/Fast and free) This is an alternative secure way of accessing f

Harishankar Kumar 6 Mar 19, 2022
A Telegram Bot to manage your music channel with some cool features.

Music Channel Manager V2 A Telegram Bot to manage your music channel with some cool features like appending your predefined username to the musics tag

11 Oct 21, 2022
Python API for working with RESQML models

resqpy: Python API for working with RESQML models Introduction resqpy is a pure python package which provides a programming interface (API) for readin

BP 44 Dec 14, 2022
Simple Self-Bot for Discord

KeunoBot 🐼 -Simple Self-Bot for Discord KEUNOBOT 🐼 - Run KeunoBot : /* - Install KeunoBot - Extract it - Run setup.bat - Set token and prefi

Bidouffe 2 Mar 10, 2022
Check your accounts/tokens fast with our checker!

Discord_Account_Checker How to use? Installing library's pip install -r reqs.txt Loading accounts Load your accounts to accounts.txt file. Launch pyth

1 Jan 11, 2022
See trending stock tickers on Reddit and check Stock perfomance

See trending stock tickers on Reddit and check Stock perfomance

Abbas 1.5k Jan 06, 2023
Let your friends know when you are online and offline xD

Twitter Last Seen Activity Let your friends know when you are online and offline Laser-light eyes when online Last seen is mentioned in user bio Also

Kush Choudhary 12 Aug 16, 2021
Powerful and Advance Telegram Bot with soo many features😋🔥❤

Chat-Bot Reach this bot on Telegram Chat Bot New Features 🔥 ✨ Improved Chat Experience ✨ Removed Some Unnecessary Commands ✨ Added Facility to downlo

Sanila Ranatunga 10 Oct 21, 2022
List of twitch bots n bigots

This is a collection of bot account names NamelistMASTER contains all the names we reccomend you ban in your channel Sometimes people get on that list

62 Sep 05, 2021
칼만 필터는 어렵지 않아(저자 김성필) 파이썬 코드(Unofficial)

KalmanFilter_Python 칼만 필터는 어렵지 않아(저자 김성필) 책을 공부하면서, Matlab 코드를 Python으로 변환한 것입니다. Contents Part01. Recursive Filter Chapter01. Average Filter Chapter0

Donghun Park 20 Oct 28, 2022
Create CDK projects with projen

The Projenator: I'll be back! Description This is a CDKv2 project that takes the grind out of setting up new cdk projects/implementations by using aut

Andrew 2 Dec 11, 2021
Zaid Vc Player Allows u to steam Songs/music on vc chat

ᴢᴀɪᴅ ᴠᴄ ᴘʟᴀʏᴇʀ 🔥 SORRY FOR OUR PROJECTS DELETED BY GITHUB FLAGGED ᴢᴀɪᴅ ᴠᴄ ᴘʟᴀᴇʀ ɪꜱ ᴀ ᴛᴇʟᴇɢʀᴀᴍ ᴘʀᴏᴊᴇᴄᴛ ʙᴀꜱᴇᴅ ᴏɴ ᴘʏʀᴏɢʀᴀᴍ ꜰᴏʀ ᴘʟᴀʏ ᴍᴜꜱɪᴄꜱ ɪɴ ᴠᴄ ᴄʜᴀᴛꜱ..

Zaid 117 Dec 29, 2022
The best (and now open source) Discord selfbot.

React Selfbot Yes, for real Why am I making this open source? Because can't stop calling my product a rat, tokenlogger and what else not. But there is

30 Nov 13, 2022
Telegram File to Link Fastest Bot , also used for movies streaming

Telegram File Stream Bot ! A Telegram bot to stream files to web. Report a Bug | Request Feature About This Bot This bot will give you stream links fo

Avishkar Patil 194 Jan 07, 2023
A simpler way to make forms, surveys, and reaction input using discord.py.

discord-ext-forms An easier way to make forms and surveys in discord.py. This module is a very simple way to ask questions and create complete forms i

thrizzle 16 Nov 06, 2022
Python based league of legends orbwalker

League of Legends Orbwalker Usage Install python3 Create a python3 venv Install the requirements pip install -r requirements.txt Get in game and run m

Inusha 43 Dec 12, 2022
Send embeds using your discord personal account

Welcome to Embed Sender 👋 Send embeds using your discord personal account Install pip install -r requirements.txt Usage Put your discord token in ./

SkydenFly 11 Sep 07, 2022
Python client and module for BGP Ranking

Python client and module for BGP Ranking THis project will make querying BGP Ranking easier. Installation pip install pybgpranking Usage Command line

D4 project 3 Dec 16, 2021
Most Simple & Powefull web3 Trade Bot (WINDOWS LINUX) Suport BSC ETH

Most Simple & Powefull Trade Bot (WINDOWS LINUX) What Are Some Pros And Cons Of Owning A Sniper Bot? While having a sniper bot is typically an advanta

GUI BOT 4 Jan 25, 2022