Google Mpas Javascript API 加载标记 onclick

问题描述 投票:0回答:1

我正在尝试新的 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>
javascript google-maps onclick
1个回答
0
投票

问题是您的 AddM() 函数是在 initMap() 函数内部定义的,因此无法从外部访问它。

要解决此问题,请将 AddM() 函数移到 initMap() 之外,例如:

async function initMap() {
  // map initialization
}

function AddM() {
  // add marker code
}

现在 AddM() 将可以全局访问。

其他一些注意事项:

  • 在尝试访问地图和标记类之前,请确保等待地图和导入调用
  • 在尝试调用 AddM() 之前先调用 initMap()

这是更新的片段:

let map;

async function initMap() {
  // map initialization  
}

function AddM() {
  // add marker 
}

initMap().then(() => {
  // can now safely call AddM
  AddM(); 
});

总结一下:

  1. 将 AddM() 移到 initMap() 之外
  2. 等待导入和地图初始化
  3. 先调用initMap(),然后调用AddM()

这应该可以解决 AddM() 未定义的问题。

© www.soinside.com 2019 - 2024. All rights reserved.