使用Ajax加载GoogleMaps脚本

时间:2014-02-20 12:36:03

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

我正在尝试使用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);

1 个答案:

答案 0 :(得分:0)

来自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;