Distance matrix api python

olliefr / gdmpydemo.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

# Google Distance Matrix Python Demo
# ==================================
#
# How to set up (Local part)
# —————————
#
# Must have Python (>= 3.4) installed with ‘requests’ library. On Windows, maybe try
# Anaconda Python? It has a ‘conda’ package manager, make sure ‘requests’ is installed.
#
# How to set up (Internet part)
# ——————————
#
# Go to https://developers.google.com and sign in using a personal (not university)
# Google account. Search for ‘Distance Matrix’, its API will be the only choice
# in the list. Get an API key by creating a new project. Copy the API key to
# the clipboard.
#
# How to run the program
# ———————-
#
# > python3 distances.py
#
# Debug tips
# ———-
#
# Ask Python not to quit after having run the script, so all variables can be
# inspected interactively. The script will also load pprint function for your
# convenience.
#
# > python3 -i distances.py
#
import json
import requests
import sys
if __name__ == ‘__main__’ :
# The API key must be provided on the command line, abort otherwise.
api_key = »
if len ( sys . argv ) != 2 :
print ( ‘Usage: distances.py ‘ )
exit ( 1 )
else :
api_key = sys . argv [ 1 ]
# Google Distance Matrix base URL to which all other parameters are attached
base_url = ‘https://maps.googleapis.com/maps/api/distancematrix/json?’
# Google Distance Matrix domain-specific terms: origins and destinations
origins = [ ‘Vancouver, BC’ , ‘Seattle’ ]
destinations = [ ‘San Francisco’ , ‘Victoria, BC’ ]
# Prepare the request details for the assembly into a request URL
payload =
‘origins’ : ‘|’ . join ( origins ),
‘destinations’ : ‘|’ . join ( destinations ),
‘mode’ : ‘driving’ ,
‘api_key’ : api_key
>
# Assemble the URL and query the web service
r = requests . get ( base_url , params = payload )
# Check the HTTP status code returned by the server. Only process the response,
# if the status code is 200 (OK in HTTP terms).
if r . status_code != 200 :
print ( ‘HTTP status code <> received, program terminated.’ . format ( r . status_code ))
else :
try :
# Try/catch block should capture the problems when loading JSON data,
# such as when JSON is broken. It won’t, however, help much if JSON format
# for this service has changed — in that case, the dictionaries json.loads() produces
# may not have some of the fields queried later. In a production system, some sort
# of verification of JSON file structure is required before processing it. In XML
# this role is performed by XML Schema.
x = json . loads ( r . text )
# Now you can do as you please with the data structure stored in x.
# Here, we print it as a Cartesian product.
for isrc , src in enumerate ( x [ ‘origin_addresses’ ]):
for idst , dst in enumerate ( x [ ‘destination_addresses’ ]):
row = x [ ‘rows’ ][ isrc ]
cell = row [ ‘elements’ ][ idst ]
if cell [ ‘status’ ] == ‘OK’ :
print ( ‘<> to <>: <>, <>.’ . format ( src , dst , cell [ ‘distance’ ][ ‘text’ ], cell [ ‘duration’ ][ ‘text’ ]))
else :
print ( ‘<> to <>: status = <>‘ . format ( src , dst , cell [ ‘status’ ]))
# Of course, we could have also saved the results in a file,
with open ( ‘gdmpydemo.json’ , ‘w’ ) as f :
f . write ( r . text )
# TODO Or in a database,
# Or whatever.
# .
# Profit!
except ValueError :
print ( ‘Error while parsing JSON response, program terminated.’ )
# Prepare for debugging, but only if interactive. Now you can pprint(x), for example.
if sys . flags . interactive :
from pprint import pprint

Источник

Distance Matrix API application

You’ve got no time to deal with coding, or you just need to calculate the travel distances and route time for a large number of similar locations quickly at one time.

Use this Python script or Windows application with little or no code handling.

You can download the app on GitHub.

Unzip it (extract all) and you should see the following files:

Distance Matrix API application

Above all to make the application work, you need an active access token.

You need to insert your active DM token into the file named token.
‍You can get the token for free here.

You will also need a data.csv file with the set of addresses to run an application or script. If you just want to try how the API works you can leave this file as it is, some addresses are already listed there as an example.

You can always change and add your locations in this file. The number of lines is not limited but we recommend running not more than 10k pairs at a time.

The file can be opened in Excel:

distance between coordinates

Or any text editor, i.e. Notepad. In this case, it is important that the delimiter between the 5 variables must be a semicolon «;» , as in this example:

distance between addresses

It is important to fill in all the fields correctly:

  • Into the origin/destination fields you can insert specific addresses, just city names or postcodes/postal indexes/zip as well as geographic coordinates (lat/long)
  • In the mode field add the mode you need: driving, walking, bicycling or transit_mode=bus, transit_mode=train|tram|subway
  • In the traffic_model field: either leave best_guess, or change to pessimistic or optimistic
  • Leave now in the departure_time field, or specify the time converting it to the Unix Timestamp format firstly (it should look like, 1627557223). https://www.unixtimestamp.com/ service is convenient to convert time to the required format

You can also find and add more features from our documentation.

Note: If the parameters in the data file are specified incorrectly, then the line with the fault request will be skipped and not written to the document.

When the file is ready, choose what is more convenient for you:

distance matrix api python

Launch by double clicking and the API will start calculating.
Execution speed is about 1 second per line.

distance matrix application

distance matrix python

The requests are performed sequentially one by one. Which means that the next request will not be sent until the previous one is completed and completely recorded.

The forced termination of the script is performed by the command CTRL + C.

A file with the results named result.csv will be automatically created when you start the script or application. As a result you should get lines with all the incoming parameters, the results of the API calculations and the time when the request has been made.

Using this script you can easily get the API’s results in Excel.

Источник

Distance matrix api python

В этом примере запрашиваются данные матрицы расстояний между Вашингтоном, округ Колумбия, и Нью-Йорком, штат Нью-Йорк, в формате JSON:

URL-адрес

https://maps.googleapis.com/maps/api/distancematrix/json ?destinations=New%20York%20City%2C%20NY &origins=Washington%2C%20DC &units=imperial &key=YOUR_API_KEY

CURL

curl -L -X GET 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Washington%2C%20DC&destinations=New%20York%20City%2C%20NY&units=imperial&key=YOUR_API_KEY'

JavaScript

var axios = require('axios'); var config = < method: 'get', url: 'https://maps.googleapis.com/maps/api/distancematrix/json?origins=Washington%2C%20DC&destinations=New%20York%20City%2C%20NY&units=imperial&key=YOUR_API_KEY', headers: < >>; axios(config) .then(function (response) < console.log(JSON.stringify(response.data)); >) .catch(function (error) < console.log(error); >);

Питон

import requests url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=Washington%2C%20DC&destinations=New%20York%20City%2C%20NY&units=imperial&key=YOUR_API_KEY" payload=<> headers = <> response = requests.request("GET", url, headers=headers, data=payload) print(response.text)

Джава

OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("text/plain"); RequestBody body = RequestBody.create(mediaType, ""); Request request = new Request.Builder() .url("https://maps.googleapis.com/maps/api/distancematrix/json?origins=Washington%2C%20DC&destinations=New%20York%20City%2C%20NY&units=imperial&key=YOUR_API_KEY") .method("GET", body) .build(); Response response = client.newCall(request).execute();

Рубин

require "uri" require "net/http" url = URI("https://maps.googleapis.com/maps/api/distancematrix/json?origins=Washington%2C%20DC&destinations=New%20York%20City%2C%20NY&units=imperial&key=YOUR_API_KEY") https = Net::HTTP.new(url.host, url.port) https.use_ssl = true request = Net::HTTP::Get.new(url) response = https.request(request) puts response.read_body

Идти

package main import ( "fmt" "net/http" "io/ioutil" ) func main() < url := "https://maps.googleapis.com/maps/api/distancematrix/json?origins=Washington,%20DC&destinations=New%20York%20City,%20NY&units=imperial&key=YOUR_API_KEY" method := "GET" client := &http.Client < >req, err := http.NewRequest(method, url, nil) if err != nil < fmt.Println(err) return >res, err := client.Do(req) if err != nil < fmt.Println(err) return >defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil < fmt.Println(err) return >fmt.Println(string(body)) >

Почтальон

Спецификация OpenAPI также доступна в виде коллекции Postman .

Попробуй это! Протестируйте этот запрос, введя URL-адрес в адресную строку веб-браузера. Обязательно замените YOUR_API_KEY своим фактическим ключом API . Ответ показывает расстояние и продолжительность между указанными источниками и пунктами назначения.

Узнайте, как создавать URL-адреса запросов , включая все доступные параметры.

Этот пример кода представлен в форматах JSON и XML:

JSON

< "destination_addresses": ["New York, NY, USA"], "origin_addresses": ["Washington, DC, USA"], "rows": [ < "elements": [ < "distance": < "text": "228 mi", "value": 367654 >, "duration": < "text": "3 hours 55 mins", "value": 14078 >, "status": "OK", >, ], >, ], "status": "OK", >

XML

 OK Washington, DC, USA New York, NY, USA  OK 14078 3 hours 55 mins  367654 228 mi    

Спецификация OpenAPI

Спецификация OpenAPI опубликована для этого API и доступна на GitHub .

Коллекция почтальона

Спецификация OpenAPI также доступна в виде коллекции Postman .

Обратитесь к руководству разработчика, чтобы понять ответ .

Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons «С указанием авторства 4.0», а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.

Последнее обновление: 2023-07-18 UTC.

Источник

Calculate distance and duration between two places using google distance matrix API in Python?

We almost all use google maps to check distance between source and destination and check the travel time. For developers and enthusiasts, google provide ‘google distance matrix API’ to calculate the distance and duration between two places.

To use google distance matrix api, we need google maps API keys, which you can get from below link:

Required libraries

We can accomplish this by using different python library, like:

I am using very basic requests and json library. Using pandas you can fill multiple source and destination places at a time and get the result in csv file.

Below is the program to implement the same:

# Import required library import requests import json #Enter your source and destination city originPoint = input("Please enter your origin city: ") destinationPoint= input("Please enter your destination city: ") #Place your google map API_KEY to a variable apiKey = 'YOUR_API_KEY' #Store google maps api url in a variable url = 'https://maps.googleapis.com/maps/api/distancematrix/json?' # call get method of request module and store respose object r = requests.get(url + 'origins = ' + originPoint + '&destinations = ' + destinationPoint + '&key = ' + apiKey) #Get json format result from the above response object res = r.json() #print the value of res print(res)

Output

Please enter your origin city: Delhi Please enter your destination city: Karnataka , 'duration': , 'status': 'OK'>]>], 'status': 'OK'>

Источник

Читайте также:  Html div float left width
Оцените статью