Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 400
user614778 Avatar asked Feb 13 '15 00:02

user614778


2 Answers

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/

like image 199
Dr.Molle Avatar answered Sep 27 '22 21:09

Dr.Molle


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

like image 45
David John Smith Avatar answered Sep 27 '22 21:09

David John Smith