使用 Python 和 Google 靜態地圖 API 獲取指定位置的 Google 地圖影像


Google 提供了一個靜態地圖 API,它根據我們的 HTTP 請求返回地圖影像。我們可以根據需要直接請求具有不同引數的地圖影像。

我們必須在 Google 上建立一個計費帳戶才能使用此 API。您可以訪問該網站了解更多詳細資訊。

讓我們看看獲取位置影像的步驟。

  • 匯入 requests 模組。

  • 初始化您的 API 金鑰和基本 URL("https://maps.googleapis.com/maps/api/staticmap?")。

  • 初始化城市和縮放值。

  • 使用 API 金鑰、城市和縮放值更新 URL。

  • 傳送 HTTP 請求。並將響應寫入檔案以儲存影像。使用 API 金鑰、城市和縮放值更新 URL。

示例

讓我們將上述步驟轉換為程式碼。

# importing the module import requests
# base URL BASE_URL = "https://maps.googleapis.com/maps/api/staticmap?"
# API key API_KEY = "Your API Key"
# city CITY = "Hyderabad"
# zoom value
ZOOM = 14
# updating the URL
URL = BASE_URL + "center=" + CITY + "&zoom=" + str(ZOOM) + "&size = 500x500&key=" + API_KEY
# HTTP request
response = requests.get(URL)
# storing the response in a file (image)
with open('hyderabad.png', 'wb') as file:
   # writing data into the file
   file.write(response.content)
# make sure you have a valid API Key
# You will get 403 as status_code if your API Key is invalid

輸出

如果 HTTP 請求成功,我們將獲得如下所示的影像。


結論

如果您在本教程中有任何疑問,請在評論部分中提出。

更新於: 2020年2月12日

4K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告