Googlemaps监听器在Firefox中加载得很好,但在其他浏览器中却没有

时间:2015-12-29 00:26:28

标签: javascript google-maps asynchronous cross-browser listener

我正在加载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>

然后我定义一个监听器来记录地图上任何点击的纬度/经度。

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

这适用于Firefox,但在Chromium和IE上我收到错误&#34; google未定义&#34;。我尝试重新定位加载api但没有成功的脚本。使其同步加载会导致地图无法显示。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

google API只能在调用回调之前使用,因此您需要将getLatLon()方法放在initmap()中以避免&#34; google未定义&#34;错误。

它必须类似于下面的代码

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

        getLatLon();
    }
</script>