Javascript – How to use google-maps-api-v3 without add script tag on html

bowerfrontendgoogle-maps-api-3gulpjavascript

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.com/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 ?

Best Solution

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.com/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.net/doktormolle/cr1w32qn/