如何使用 Python 和 Requests 函式庫查詢 Google Maps Directions API?

DDD
發布: 2024-11-14 15:07:02
原創
701 人瀏覽過

How to Query Google Maps Directions API using Python and the Requests Library?

HTTP Requests and JSON Parsing in Python Using the Requests Library

If you wish to perform dynamic queries on Google Maps via the Google Directions API, the Python programming language provides an efficient solution. To initiate an HTTP request, receive the JSON response, and parse its contents, follow these steps:

  1. Install the Requests Library: Begin by obtaining the Requests library using the following command:

    pip install requests
    登入後複製
  2. Craft the Request: Formulate an HTTP GET request specifying the URL endpoint along with the desired request parameters:

    url = 'http://maps.googleapis.com/maps/api/directions/json'
    
    params = {
     'origin': 'Chicago,IL',
     'destination': 'Los+Angeles,CA',
     'waypoints': 'Joplin,MO|Oklahoma+City,OK',
     'sensor': 'false'
     }
    登入後複製

In this instance, the query is configured to retrieve the optimal route between Chicago and Los Angeles, incorporating two intermediary waypoints.

  1. Send the Request: Dispatch the request by invoking the get() method of the Requests library, specifying the URL and parameters:

    resp = requests.get(url=url, params=params)
    登入後複製
  2. Extract JSON Response: Retrieve the JSON content from the response object:

    data = resp.json()
    登入後複製
  3. Parse JSON Data: Utilize the parsed data to access specific elements or perform further processing as required.

By embracing the Requests library, you gain a comprehensive toolkit for handling HTTP requests and parsing JSON responses in Python. This empowers you to seamlessly interact with various web services, such as Google Maps, and retrieve valuable information.

以上是如何使用 Python 和 Requests 函式庫查詢 Google Maps Directions API?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板