\'Hello World\' 比较:
标记(遗留)
google.maps.Marker 已弃用(2024 年 2 月 21 日(v3.56))。
文档: https://developers.google.com/maps/documentation/javascript/markers
// Initialize and add the map
let map;
function initMap() {
const myLatLng = { lat: -25.363, lng: 131.044 };
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 4,
disableDefaultUI: true, // a way to quickly hide all controls
});
new google.maps.Marker({
position: myLatLng,
map,
});
}
initMap();
AdvancedMarkerElement(新)
文档: https://developers.google.com/maps/documentation/javascript/advanced-markers/overview
额外的步骤 AdvancedMarkerElement
是 创建地图ID .
// Initialize and add the map
let map;
async function initMap_AdvancedMarkerElement() {
const myLatLng = { lat: -25.363, lng: 131.044 };
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
// The map, centered at Uluru
map = new Map(document.getElementById("AdvancedMarker_MAP"), {
zoom: 4,
center: myLatLng,
disableDefaultUI: true, // a way to quickly hide all controls
mapId: "DEMO_MAP_ID",
});
// The marker, positioned at Uluru
const marker = new AdvancedMarkerElement({
map: map,
position: myLatLng,
title: "Uluru",
});
}
initMap_AdvancedMarkerElement();
相关: 异步 JavaScript
重要 - 许多代码想法(例如更改标记图标、标记样式等) - 彻底改变了 VS Legacy(遵循文档)。
PRE 步骤(传统和高级):
-
p6
-
p7
<script async
src="https://maps.googleapis.com/maps/api/js?your-key=&loading=async&callback=initMap">
</script>
加载地图 JavaScript API 的更多方法: https://developers.google.com/maps/documentation/javascript/load-maps-js-api
-
CSS:为地图 div 添加 高度 。例如:
#map {height: 400px;}