在前面第四篇的時候,提到有一個項目是 photo,裡面通常有10個項目,我們可以透過這 10 個項目取得該地點的圖片,這一篇就來看看如何透過這個項目取得圖片。
首先我們來看看,photo 裡面的 10 個項目長怎樣。
photo 裡面會有一個項目是 photo_reference,它的value大概是長這樣:CmRaAAAAMRw3rMQekkw1vt8BISl4OdOzt4Hl-9bNqpAL8XRA9iPlY5zzTptLIty32cIcNnCh0GXK8-gLZx0cjG9Xa1l8tzVNiZRLr0DXWyuAjBzztWKzrlYpaWWTHVnjcpoBotr3EhC553Dy95yqdZ2qhyeMRhmSGhSHXqw_4Wsl8V9V4fYH3hwqanK95A
所以當我們拿到 photo_reference 之後,就可以用這個 value 取得該地點的照片。
先看看程式碼吧:
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
import googlemaps | |
import os | |
google_key = "AIzaSyCLfZQjoR4uuH3-gikZOf01XLltl_bSlxx" | |
gmaps = googlemaps.Client(key = google_key) | |
#前面一樣要先取得google key,還有設定client | |
#下面這邊,我假設妳已經取得了10個photo_reference,並且將他們存在list裡面 | |
n = 0 | |
for storePhoto_reference in storePhoto_references: | |
try: | |
photo = gmaps.places_photo(photo_reference = storePhoto_reference, max_width=800, max_height=800) | |
#這邊參數一個當然是傳如photo_reference,另外也可以設定最大高度和寬度,最大都為1600,依照你的需求設定。 | |
f = open(str(n) + ".png", "wb") | |
#這邊我設定了我的檔案名稱還有存取的方式,因為圖片檔案是二進位檔案,所以用"wb" | |
for chunk in photo: | |
if chunk: | |
f.write(chunk) | |
f.close() | |
n = n+1 | |
except: | |
print(fileName + "failed") | |
continue | |
print(storeName + "結束") |
在你取得 photo_reference 之後,透過以上程式碼,就可以成功取得地點照片。
如果伺服器無法理解您的要求,它會傳回 HTTP 400 狀態,指出無效的要求。 您可能遇到無效的要求最常見的原因包括:
- 提交的相片參考資料指定錯誤。
- 您的要求未包括
maxwidth
或maxheight
參數。
根據 Google官方說明:在大部分情況中,地點相片不需要資料引用標示就能使用,或是將必要資料引用標示包括為影像的一部分。
在怎樣的情況下會需要標示呢?
在你取得 photo 項目時,除了 photo_reference 之外,還有 html_attributions 欄位中的value,如果這裡面有註明的話,就必須要標記,請見這邊說明。
最後再提供給大家官方的 python說明網頁。