【问题标题】:Load GoogleMaps Script with Ajax使用 Ajax 加载 GoogleMaps 脚本
【发布时间】:2014-02-20 12:36:02
【问题描述】:

我正在尝试使用 AJAX 加载此视图,我知道初始化函数无法正常运行,因为窗口的加载事件在我使用 AJAX 加载视图之前开始,但我找不到这样做的方法:

google.maps.event.addDomListener(window, 'load', initialize);

对不起我的英语。

function initialize() {

    var myLatlng = new google.maps.LatLng(1000,1000);
    var mapOptions = {

        zoom: 16,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP

    }

    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    var marker = new google.maps.Marker({

        position: myLatlng,
        map: map,
        title: 'Aqui estamos!'

    });

}
initialize()//Don`t work
google.maps.event.addDomListener(window, 'load', initialize);

【问题讨论】:

  • 感谢史蒂夫的回答,很有效。但我不知道怎么做,谁能解释我为什么必须动态创建脚本元素?

标签: javascript ajax google-maps-api-3


【解决方案1】:

来自https://developers.google.com/maps/documentation/javascript/examples/map-simple-async

function initialize() {
  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };

  var map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
      'callback=initialize';
  document.body.appendChild(script);
}

window.onload = loadScript;

【讨论】:

    猜你喜欢
    • 2011-11-15
    • 1970-01-01
    • 2016-05-27
    • 2019-02-03
    • 2016-05-22
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多