Googlemaps 侦听器在 firefox 中加载正常,但在其他浏览器中加载不正常

Googlemaps listener loading fine in firefox but not in other browsers

我正在加载 googlemaps api

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=oxD34DBEEF_KbuMvCv3koum4ntaRia8GdIUwE&callback=initMap">
</script>

绘制地图

<script type="text/javascript">
var map;
    function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        ...
        });
    }
</script>

然后我定义了一个侦听器来注册地图上任何点击的 latitude/longitude。

function getLatLon() {
            listener1 = google.maps.event.addListener(map, 'click', function (event) {...})
}
...
getLatLon();

这在 Firefox 上运行良好,但在 Chromium 和 IE 上我收到错误 "google is not defined"。我尝试重新定位加载 api 的脚本,但没有成功。使其同步加载会导致地图不显示。

感谢您的帮助。

google API 只能在调用回调之前使用,因此您需要将 getLatLon() 方法放在 initmap() 中以避免 "google is not defined" 错误。

它必须类似于下面的代码

<script type="text/javascript">
var map;
    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          ....
        });

        getLatLon();
    }
</script>