2024-06-30|閱讀時間 ‧ 約 31 分鐘

學習筆記-1 使用Google Maps API在網頁上顯示地圖與搜尋店家名稱

本篇是一個初學轉職工程師撰寫的,內容都是以原生JS無使用框架的方式達到想要達成的目標,如有刺眼之處還請多見諒

由於參與的專案需要使用到地點以及撈取店家資訊,所以使用了Google Maps api地圖資料來處理。

首先,先至Google Cloud Platform(GCP)申請 api key

google提供各式各樣的 api給客戶使用,只要有了這組金鑰就可以使用他們家的api服務,但要注意的是google api不是免費提供的,每個月有200美金的免費額度,後續用完的計價方式可以去GCP上看相關的說明。

有了這組金鑰之後就可以去js上引用了

    <script>    (g => {      var h, a, k, p = "The Google Maps JavaScript API",
        c = "google",        l = "importLibrary",        q = "__ib__",       
m = document,        b = window;      b = b[c] || (b[c] = {});     
var d = b.maps || (b.maps = {}),        r = new Set,       
e = new URLSearchParams,       
u = () => h || (h = new Promise(async (f, n) => {         
await (a = m.createElement("script"));         
e.set("libraries", [...r] + "");         
for (k in g) e.set(k.replace(/[A-Z]/g, t => "_" + t[0].toLowerCase()), g[k]); 
        e.set("callback", c + ".maps." + q);         
a.src = `https://maps.${c}apis.com/maps/api/js?` + e;          d[q] = f; 
        a.onerror = () => h = n(Error(p + " could not load."));         
a.nonce = m.querySelector("script[nonce]")?.nonce || "";       
  m.head.append(a)        }));     
d[l] ? console.warn(p + " only loads once. Ignoring:", g) : d[l] = (f, ...n)
=> r.add(f) && u().then(() => d[l](f, ...n))    })    ({     
key: "YOUR_KEY",      v: "weekly"    }); 
</script>

在YOUR_KEY上填入你申請的金鑰 就可以引入GOOGLEMAP API的內容了。

接下來來做初始化地圖

<div class="container">      
<div id="map"></div>     
</div>
let map;      
let center;
async function initMap() {       
const { Map } = await google.maps.importLibrary("maps");
  center = {         
lat: 25.0374865,         
lng: 121.5647688,       
};       
map = new Map(document.getElementById("map"), {         
center: center,         
zoom: 14,         
mapId: "4504f8b37365c3d0",       
});     
}

initMap();

這個部分就可以把一張沒有任何標記點的地圖呈現在網頁上

center可以改成你想要搜索以及初始化頁面的位置

zoom的數字可以填入1-20 數字愈大,地圖愈細:1是世界地圖,20就會到街道

接下來就可以使用input來搜尋想搜尋的店家名稱

<form action="" method="get">          
<input type="text" name="search" />         
<button>送出</button>       
</form>
let input = document.querySelector("input[name=search]");
let search = document.querySelector("form");

因為搜尋會是使用剛剛初始化過的地圖作呈現,所以這邊的話會在剛剛初始化地圖的function內加入

search.addEventListener("submit", (e) => {          
e.preventDefault();         
findPlaces();       
});

之後開始處理findPlaces()搜尋的部分

let markers = [];
async function findPlaces() {       
const { Place } = await google.maps.importLibrary("places");       
const { AdvancedMarkerElement } = await google.maps.importLibrary(         
"marker"        );
markers.forEach((marker) => marker.setMap(null));       
markers = [];       
const request = {         
textQuery: `${input.value}`,         
fields: [           
"displayName",           
"location",           
"formattedAddress",           
"businessStatus",         
],         
locationBias: {            //可以自行設定想要搜尋的中心點,沒有特定點的話這句刪掉就會是該台裝置目前的定位位置           
center: {             
lat: center.lat,             
lng: center.lng,           
},           
radius: 500,         // 預計搜尋的範圍 最大50000(公尺)         
},         
isOpenNow: true,         
language: "zh-tw",         
maxResultCount: 10,    
//預計搜尋的店家數量  至多20         
minRating: 0,          
//預計搜尋的評價星數         
region: "tw",         
useStrictTypeFiltering: true,       
};       
const { places } = await Place.searchByText(request);
if (places.length) {         
console.log(places);
const { LatLngBounds } = await google.maps.importLibrary("core");         
const bounds = new LatLngBounds();
places.forEach((place) => {           
const markerView = new AdvancedMarkerElement({             
map,             
position:
place.location,             
title: place.displayName,           
});           
markers.push(markerView);           
bounds.extend(place.location);         
});map.setCenter(bounds.getCenter());       
} else {         
alert("No results");         
console.log("No results");       
}       
input.value = "";      }



以上code所呈現的會如上圖所示,接著在搜尋地點內打想要查閱的地點關鍵字,地圖就會以你所設定的中心點向外搜尋

如果想要更精確的搜尋,可以在request內輸入"includedTypes",以便增加搜尋條件,想知道實際有甚麼type可以使用可以上google map api的說明文件上搜尋

分享至
成為作者繼續創作的動力吧!
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言
© 2024 vocus All rights reserved.