章節連結
Alpha Camp 的第二學期課程,讓大家試試水溫串接 API。在心血來潮下,想說串接個 Google Map 的 API 來玩玩看。不過要做的準備工作還真不少,以下是試驗不少次後所得到的心得。
串接前的準備工作
1. Google Cloud
請進入 Google Cloud 網站,並點選免費試用(Free Trial),完成註冊手續(選取地點和輸入信用卡資訊)。完成後,請創建一個專案,並進入”API 和服務” 設定頁面,尋找要開啟的API並啟用。(這裡以 Google Place API 為例)
完畢後,點選”API 和服務” 設定頁面裡的”憑證”,然後建立一組憑證,讓你的程式可以呼叫。
2.存取方式
Google 若在本機端直接用方才申請的憑證呼叫,其回傳資料都會有 CORS error 問題。目前唯一解法是載入 Google Library API 的Script 來存取。
1 2 |
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDunXykyoL8RJ97753IG7xoE305iQzXkoU&libraries=places&callback=initMap"> </script> |
實作步驟
Nearby Search
於 HTML 頁面時,請注意會有 Google Library 的程式碼要寫在自己的JavaScript前面,這樣才可以避免掉非同步處理的問題。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
//產生Google地圖取得餐廳資料,記得要載入Google API Library //latitude(緯度)和longtitude(經度)為數字, radius(半徑)的單位為公尺 function initMap(latitude, longitude, radius) { // Initial position 初始化位置 let initialPosition = new google.maps.LatLng(latitude, longitude) // to create the map 創建地圖 let map = new google.maps.Map(document.getElementById('map'), { center: initialPosition, zoom: 13 //(縮放比例,越大代表越近) }); // the request for nearbySearch() let request = { location: initialPosition, radius: radius, types: ['bakery', 'cafe', 'supermarket', 'restaurant'] //類型可以自己看說明文件內有 }; // to do the nearbySearch() request to found types around the initial position let service = new google.maps.places.PlacesService(map) service.nearbySearch(request, NearbySearchCallback) //建立一組回傳函式NearbySearchCallback } // This function is called when nearbySearch() has done function NearbySearchCallback(results, status, pagination) { getTotalPages(results) getPageData(1, results) //search 監聽器 search.addEventListener('click', event => { event.preventDefault() let input = searchInput.value let chosenPlaces = [] //console.log(input) const regex = new RegExp(input, 'i') chosenPlaces = results.filter(place => place.name.match(regex)) //console.log(chosenPlaces) getTotalPages(chosenPlaces) getPageData(1, chosenPlaces) //有時間差問題,所以按下後不清空輸入值 }) if (status == google.maps.places.PlacesServiceStatus.OK) { //more 監聽器 more.addEventListener('click', event => { event.preventDefault() if (pagination.hasNextPage) { //最多可以取60筆資料,每次20筆 sleep: 2; //規定要間隔2秒 pagination.nextPage() //呼叫下一頁的函式 } else { more.disabled = true } }) } } |
參考資料
1. Google Nearby Search Demo
2. Google Nearby Search Document
延伸閱讀
- [筆記] Master The Coding Interview – 16
- [指南] Vue TestCafe + TypeScript 導入 E2E 測試
- [筆記] Master The Coding Interview – 15
- [筆記] AlphaCamp 不只是刷題的 Leetcode 訓練營 – 3
- [指南] Vue 結合 Jest + TypeScript 導入單元測試 – 2
GA瀏覽人氣:1,769