【开发笔记】采用谷歌地图 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
})