title: How to initialize a google maps on pageinit without repeatingly loading the google map api script
body: <ul>
  <li>I would like to be able to load the Google.maps API only once for alle my pages.</li>
  <li>Then i would like to be able to use geolocation or loading a map into a page anywhere on my web  app.</li>
  <li>The problem is that I cant figure out to seperate API loading and map initialization.
  Which means i need to load the API each time I create a map.</li>
  </ul>
  
  <p>I have referenced most of my code further down in the post but i suppose the following code is the problem.That piece of code takes care of the API Loading but at the same time it takes care of setting the initialize() function as a callback function and calling it.</p>
  
  <pre><code>var script = document.createElement("script");
  script.type = "text/javascript";
  script.src ="http://maps.googleapis.com/maps/api/js?key=mykey&amp;sensor=false&amp;callback=initialize";
  document.body.appendChild(script);
  </code></pre>
  
  <p><strong>How do i load the api once, lets say in the header, and then create a new map each time I go to specific page. WIthout loading the maps API again. (Note that im using Jquery mobile so my header only gets loaded one time for a session.)</strong></p>
  
  <p><strong>I get this error:</strong></p>
  
  <p>Warning: you have included the Google Maps API multiple times on this page. This may cause unexpected errors. </p>
  
  <p><strong>Ii would like to tell you my setup.</strong></p>
  
  <p>-Im using Google Map APi v3</p>
  
  <p>-I'm loading the API dynamically after the page has loaded.</p>
  
  <p>-I'm using Jquery mobile, which means the page with google maps only gets partially reloaded when you     visit it.</p>
  
  <p>-Im using google maps for two things to show the map and for geolocation.</p>
  
  <p>-I'm using the Google map api on several pages.</p>
  
  <p><strong>Im interacting with the map in 3 different places: In a header javascript see code below</strong></p>
  
  <ul>
  <li><p>A header javascript</p></li>
  <li><p>A javascript in the body</p></li>
  <li><p>The DIV in the body that holds the map.</p></li>
  </ul>
  
  <p>Here is my code for the javascript that handles loading the API, showing the map, markers etc:</p>
  
  <pre><code>        &lt;script&gt;
              $('.error').hide();
              //search criterias
              var radius;
              var timerange;
              var type;
              //user position variables
              var userposition = false;
              var mylatitudedegree = "=55.698";
              var mylongitudedegree = "=12.579";
              //map variables
              var mapready = false;
              var map;
              var bound;
              var markersArray = [];
              //array for keeping track of the markers
              var markercenter;
              //hack
              var pageinit = 0;
              var initializer = 0;
              var triggersearch = 0;
              var loadscripts = 0;
              var isgooglemapsloaded = false;
  
                  $( '#soegsagside' ).live( 'pageinit',function(event)
                  {
                  pageinit++;
  
                  if (navigator.geolocation) {
                      navigator.geolocation.getCurrentPosition(setPosition, function(error) {
                          alert('Din location er ikke tilgængelig! Error code: ' + error.code);
                          userposition = false;
                      }, {
                          maximumAge : 60000,
                          timeout : 10000,
                          enableHighAccuracy : true
                      });
                  } 
                  else {
                      alert("Din browser tillader ikke, at vise din lokation!");
                      userposition = false;
                  }
  
                  loadScript();       
  
                  $("#search_filter_button").click(function() {
                      //hide the "skal udfyldes" labels
                      $('.error').hide();
                      // validate and process form here
                      radius = $("select#choose_radius_select").val();
                      if (radius == "vælg") {
                          $("label#radius_error").show();
                          $("select#choose_radius_select").focus();
                          return false;
                      }
                      timerange = $("select#choose_timerange_select").val();
                      if (timerange == "vælg") {
                          $("label#timerange_error").show();
                          $("select#choose_timerange_select").focus();
                          return false;
                      }
                      type = $("select#vælg_type").val();
                      if (type == "vælg") {
                          $("label#select_type_error").show();
                          $("select#vælg_type").focus();
                          return false;
                      }
                      //------------------post to php script ---------------
                      var dataString = 'radius=' + radius + '&amp;timerange=' + timerange + '&amp;type=' + type + '&amp;mylatitudedegree=' + mylatitudedegree + '&amp;mylongitudedegree=' + mylongitudedegree;
                      $.ajax({
                          type : "POST",
                          url : "soegsagDB.php",
                          data : dataString,
                          success : function(data) {
                              $('#søgeresultater').html(data);
                              $('#søgeresultater').trigger('create');
                              clearOverlays();
                              createtaskmarkers();
                              findCenterOfMarkers();
                              if (userposition) {
                                  usergeoposition = new google.maps.LatLng(mylatitudedegree, mylongitudedegree);
                                  map.setCenter(usergeoposition);
                                  createuserposition(usergeoposition);
                              } else {
                                  map.setCenter(markercenter);
                              }
                              expandMapBoundForMarkers()
  
                          }
                      });
                      //end of post search query to server
                      return false;
                  });
                  //end of click seach button
              });
              //end of page ready
  
              function setPosition(position) {
                  userposition = true;
                  myposition = position.coords;
                  mylatitudedegree = position.coords.latitude;
                  mylongitudedegree = position.coords.longitude;
                  var milli = new Date();
              }
  
              //function for clearing the markerArray
              function clearOverlays() {
                  for (var i = 0; i &lt; markersArray.length; i++) {
                      markersArray[i].setMap(null);
                  }
              }
  
              //Function for initializing the map, which is called when the map is created
              function initialize() {
                  initializer++;
                  bound = new google.maps.LatLngBounds();
  
                  var mapOptions = {
                      zoom : 13,
                      center : new google.maps.LatLng(55, 12),
                      mapTypeId : google.maps.MapTypeId.ROADMAP
                  }
  
                  //Create a map
                  map = new google.maps.Map(document.getElementById("map"), mapOptions);
                  mapready = true;
                  $("#search_filter_button").trigger('click');//Trigger click on the search button
                  triggersearch++;
              }
  
              //create user positio marker
              function createuserposition(usergeoposition) {
                  var userPositionMarker = new google.maps.Marker({
                      position : usergeoposition,
                      map : map,
                      title : "Din position",
                  });
                  markersArray.push(userPositionMarker);
              }
  
              function createtaskmarkers() {
                  //Create the markers of the tasks
                  //1. find the task &lt;li&gt; that contain the data and loop through each one
                  //2. for each task collect the dato into variables and create markers and infowindows
                  //3. calculate center of point
                  //4. extendt map area to contain all points
  
                  var data = $.map($('li'), function(element) {
                      if (element.hasAttribute("data-latitude")) {
  
                          var tempPos = new google.maps.LatLng($(element).attr('data-latitude'), $(element).attr('data-longitude'));
                          var link = $(element).attr('data-link');
                          var title = $(element).attr('data-title');
                          var type = $(element).attr('data-type');
                          var date = $(element).attr('data-date');
  
                          tempMarker = new google.maps.Marker({
                              position : tempPos,
                              map : map,
                              title : title,
                          });
  
                          tempMarker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
  
                          var tempContentString = '&lt;div style="width: 200px; height: 100px;"&gt;' + date + '&lt;br&gt;&lt;/br&gt;' + '&lt;a href="' + link + '" rel="external"&gt;&lt;b&gt;' + type + ' , ' + title + '&lt;/b&gt;&lt;/a&gt;' + '&lt;/div&gt;';
  
                          //Create infowindow
                          var tempInfowindow = new google.maps.InfoWindow({
                              content : tempContentString
                          });
                          //add market to markerArray
                          markersArray.push(tempMarker);
                          //Create event with infowindow
                          google.maps.event.addListener(tempMarker, 'click', function() {
                              tempInfowindow.open(map, this);
                          });
                      }
                  });
              }
  
              function findCenterOfMarkers() {
                  //calculate center of markers and change mapcenter to that
                  var sumlatitude = 0;
                  var sumlongitude = 0;
                  for ( position = 0; position &lt; markersArray.length; position++) {
                      sumlatitude += markersArray[position].getPosition().lat();
                      sumlongitude += markersArray[position].getPosition().lat();
                  }
                  avglatitude = sumlatitude / markersArray.length;
                  avglongitude = sumlongitude / markersArray.length;
                  markercenter = new google.maps.LatLng(avglatitude, avglongitude);
              }
  
              function expandMapBoundForMarkers() {
                  //Extend bounds for map to fit all markers into map
                  for (var i in markersArray) {
                      bound.extend(markersArray[i].getPosition());
                  }
                  map.fitBounds(bound);
              }
  
              //loads the google maps api with KEY and appends the script to the document body
              function loadScript() {
                  var script = document.createElement("script");
                  script.type = "text/javascript";
                  script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyC8wZ6RmFySy0DnWvrUaA-2OJqcM1_AOIc&amp;sensor=false&amp;callback=initialize";
                  document.body.appendChild(script);
              }
              &lt;/script&gt;
  </code></pre>
  
  <p>The only thing in the body of the page that has to do with the maps. Is the DIV that the map is loaded into.</p>
  
  <pre><code>&lt;div id="map" style="width: 80%; height: 280px; margin: auto; background-color: gray"&gt;Kortet loader, vent venligst.&lt;/div&gt; &lt;!--alternative for full screen style="position:absolute;top:30px;bottom:50px;left:0;right:0;"--&gt;
  </code></pre>
  
  <p>The API is also loaded in a common header script. Because I in general need to load it on other pages.</p>
  
  <pre><code>&lt;script src='http://maps.google.com/maps/api/js?sensor=false'&gt;&lt;/script&gt;
  </code></pre>