【開發筆記】採用谷歌地圖 AdvancedMarkerElement 的幾個細節
google.maps.marker 在 2024 年 2 月份的時候宣布將要終止。對於開發者來說,Google 建議大家改用 google.maps.marker.AdvancedMarkerElement 來取代先前的 google.maps.marker。說是很容易,不過採用上還是有些細節需要注意。
marker 與 AdvancedMarkerElement 的方法不同
[Warning] As of February 21st, 2024, google.maps.Marker is deprecated. Please use google.maps.marker.AdvancedMarkerElement instead. At this time, google.maps.Marker is not scheduled to be discontinued, but google.maps.marker.AdvancedMarkerElement is recommended over google.maps.Marker. While google.maps.Marker will continue to receive bug fixes for any major regressions, existing bugs in google.maps.Marker will not be addressed. At least 12 months notice will be given before support is discontinued. Please see https://developers.google.com/maps/deprecations for additional details and https://developers.google.com/maps/documentation/javascript/advanced-markers/migration for the migration guide. (js, line 1511)
相對於 google.maps.marker,AdvancedMarkerElement 少了很多可以設置屬性的方法,例如 clickable,opacity 和 visible。因此本來直接可以匹配設置的方法名稱在採用 AdvancedMarkerElement 後無法使用。以 vue-google-maps 為例,個人建議在能夠檢測得到設置方法的情況下才做 binding,維持 marker 和 AdvancedMarkerElement 兩者同時兼容。
...
if (typeof googleMapsInst[setMethodName] === 'undefined') {
googleMapsInst[setMethodName](attributeValue)
}
...
調用參數也不同
[Warning] Google Maps JavaScript API has been loaded directly without loading=async. This can result in suboptimal performance. For best-practice loading patterns please see https://goo.gle/js-api-loading (js, line 1596)
Libraries 在使用 AdvancedMarkerElement 時要記得加上 marker。另外新版的 API 支持非同步載入,可以透過 loading=async 來開啟。因此 vue-google-maps 的 loading 參數可以參考如下去修改。
Vue.use(VueGoogleMaps, {
load: {
key: 'YOUR_API_TOKEN',
libraries: 'places, marker',
loading: 'async', // This is required to prevent Google Maps JavaScript API has been loaded directly
})