我正在尝试新的 API 来动态导入库。 我无法通过使用链接或按钮的 onclick 事件调用函数来加载标记。有人可以给我建议吗?
我尝试了这个,但显然没有找到 AddM() 函数。 这是我的代码:
<!DOCTYPE html>
<html>
<head>
<title>Add marker</title>
<style>
#map {
height: 100%;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<a id="myLink" href="#" onclick="AddM();return false;">Add marker</a>
<div id="map"></div>
<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: "AIzaSyAHV7XH7sby4qi5puiQTydpULtYC83-fWk", v: "beta" });
</script>
<script>
let map;
async function initMap() {
const position = { lat: 45.4305250, lng: 11.0475757 };
const { Map } = await google.maps.importLibrary("maps");
const { AdvancedMarkerElement, PinElement } = await google.maps.importLibrary("marker");
map = new Map(document.getElementById("map"), {
zoom: 14,
center: position,
mapId: "2c13cd549ac1790d",
});
//AddM();
function AddM() {
var impianto45956;
const pin45956 = new PinElement({ borderColor: '#ff0000', background: '#ff0000', glyph: 'LZ', glyphColor: 'white', });
impianto45956 = { lat: 45.4305250, lng: 11.0475757 };
marker45956 = new AdvancedMarkerElement({ map: map, id: 45956, position: impianto45956, content: pin45956.element, title: "45956", });
}
}
initMap();
</script>
</body>
</html>
问题是您的 AddM() 函数是在 initMap() 函数内部定义的,因此无法从外部访问它。
要解决此问题,请将 AddM() 函数移到 initMap() 之外,例如:
async function initMap() {
// map initialization
}
function AddM() {
// add marker code
}
现在 AddM() 将可以全局访问。
其他一些注意事项:
这是更新的片段:
let map;
async function initMap() {
// map initialization
}
function AddM() {
// add marker
}
initMap().then(() => {
// can now safely call AddM
AddM();
});
总结一下:
这应该可以解决 AddM() 未定义的问题。