admin管理员组

文章数量:1313733

i've automated my fronted development , using bower , gulp and browserify . I'm using a lib called Gmaps to handle api calls to google maps . The problem is that i must add on my html a script tag before import gmaps.

<script type="text/javascript" src=""></script>  

i've automated my fronted development , using bower , gulp and browserify . I'm using a lib called Gmaps to handle api calls to google maps . The problem is that i must add on my html a script tag before import gmaps.

<script type="text/javascript" src="https://maps.google./maps/api/js?sensor=true"></script>  

I tried ,without luck, to download the js code from the script link and concat to my other js files , hoping to create an all.min.js and avoid the need to have more than one script tag on my site .

I could only manage to make this work adding the script tag to html . Is there anyway to use google maps api inside concatenated files ?

Share Improve this question asked Feb 13, 2015 at 0:20 user614778user614778 5772 gold badges5 silver badges14 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

When you want use the maps-API without additionally <script>-elements in the document the answer is clearly: No The maps-API didn't only use the 1 script, it will inject more scripts into the document.

But when the question is related to the number of scripts that you must include "manually", the answer is yes.

It's possible to load the maps-API asynchronously with a callback, the workflow would be:

  1. load the maps-API asynchronously
  2. create a function(the function you've defined as callback in step#1)
  3. Inside the callback:
    1. initialize GMaps
    2. run the instructions that create the map via GMaps

window.addEventListener('load',function(){

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis./maps/api/js?v=3&callback=initGmaps';
  document.body.appendChild(script);
});


function initGmaps(){
   //paste here the contents of gmaps.js
   //........

   //then use GMaps
   new GMaps({
        div: '#map',
        lat: 0,
        lng: 0,
        zoom:1
       });
}

Demo: http://jsfiddle/doktormolle/cr1w32qn/

Although I can't find any specific mention in Google Maps documentation, I don't believe this would be a good idea.

The request to the javascript file is not a simple, static lib. If you visit https://maps.google./maps/api/js, you see that there is information contained about Google's internal API version to use, so if you concatenated this into your site js you may find that it will stop working if Google change their internal APIs and/or version number.

The sensor=true param is also important if you are asking for user's geolocation info in the browser, which would be lost if you concat'd the script.

本文标签: javascriptHow to use googlemapsapiv3 without add script tag on htmlStack Overflow