How to avoid runtime loading of googlemap api Javascript- phonegap?

孤者浪人 提交于 2019-12-25 05:23:12

问题


I am creating a phonegap app which uses google maps to show directions and user location. I have used the default google api by adding

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

I have observed this causes the app initialization to slow down, and sometimes even crash if connectivity is slow on the mobile device. I understand that the app will not start unless all the scripts are loaded.

I tried downloading the JavaScript from the url http://maps.google.com/maps/api/js?sensor=false and storing locally, but that makes the map loading fail at times.

Is there an equivalent script which can be stored in the app itself? or can we delay the loading of script after the app is loaded?


回答1:


You can load the API asynchronously, as it is done on this example. Like that you can decide, within your javascript, when to load it, (call to loadScript()), and initialize the map after that.

Note that the example uses a callback parameter, which is the name of a function to call when loading of the API is complete.




回答2:


You can use java script asynchronous process. This method based on callback response.

Google maps javascript api provide for asynchronous loading link

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 = 'http://maps.google.com/maps/api/js?sensor=true&callback=initialize';
  document.body.appendChild(script);
}

window.onload = loadScript;


来源:https://stackoverflow.com/questions/12216382/how-to-avoid-runtime-loading-of-googlemap-api-javascript-phonegap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!