0

I have a button when gets clicked will do ajax and load a html file to bootstrap modal that has this line of code.

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAbePUCw9D44HfcTuiWyFQs_HbQ_6Qw-fA&signed_in=true&libraries=places&callback=initMap"
    async defer></script>

When I clicked the button again I get this error.

You have included the Google Maps API multiple times on this page. This may cause unexpected errors.

How to prevent googlemaps script gets loaded twice?

Here is my code

<div class="modal fade" id="trackMapModal" role="dialog"></div>

<button class='pull-right track' id="2"><strong>Track it!</strong></button>
<script>
$("#trackMapModal").appendTo("body");
$(".track").click(function(){
    var id = this.id;
    $.ajax({
        type:"POST",
        url:"<?=base_url("/track/viewMap")?>",
        dataType:"html",
        data: {id : id},
        success:function(res){
            $("#trackMapModal").html(res).modal("show");
        }
    })
});
</script>

And at /track/viewMap it will return a map where there is this script

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAbePUCw9D44HfcTuiWyFQs_HbQ_6Qw-fA&signed_in=true&libraries=places&callback=initMap"
async defer></script>

That script will have callback that will run initMap() function when its loaded.

/track/viewMap code

function viewMap(){
    $id = $this->input->post("id,true);
    $data["id"]=$id;
    $data["loc"]["dest"]=array("lat"=>51.1124587,"lng"=>42.1245457);

    $this->load->view("/MAIN/mapModal",$data);
}

on view named /MAIN/mapModal

<div id="map"></div>
<script>
function initMap() {
    var directionsService = new google.maps.DirectionsService;
    var directionsDisplay = new google.maps.DirectionsRenderer;
    var marker2;
    var map = new google.maps.Map(document.getElementById('map'),{
        center: {lat: <?=$loc["lat"]?>, lng: <?=$loc["lng"]?>},zoom:17
    });
    marker2 = new google.maps.Marker({
        position: myLatlng,
        map: map
    });
    marker2.setMap(map);

}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAbePUCw9D44HfcTuiWyFQs_HbQ_6Qw-fA&signed_in=true&libraries=places&callback=initMap" async defer></script>
Calvin
  • 605
  • 10
  • 26
  • Don't load it twice... (unless we see more of your code) – evolutionxbox Oct 12 '16 at 08:59
  • 1
    I don't understand how questions like this get upvoted yet better questions with full code get downvoted – Pete Oct 12 '16 at 09:02
  • are you loading the html page into an iframe? – sam rodrigues Oct 12 '16 at 09:03
  • @samrodrigues no, to a bootstrap modal sorry I forgot to say where it is loaded – Calvin Oct 12 '16 at 09:11
  • 1
    Possible duplicate of [Loading Javascript Dynamically and how to check if the script exists](http://stackoverflow.com/questions/3768768/loading-javascript-dynamically-and-how-to-check-if-the-script-exists) – Liam Oct 12 '16 at 09:14
  • In my experience the overhead of loading the script is minimal and the advantage and added complexity of loading it dynamically is just not worth it. Load it as normal by putting the link in the head and forget about it – Liam Oct 12 '16 at 09:16
  • @Vlanzyvinz and the script tag is within the html page loading in the modal.Put the script tag onto the main page where the button is and do a init of the google map when the modal has popped up.May not be the best soln.please correct me if i am wrong. – sam rodrigues Oct 12 '16 at 09:22
  • on this [http://stackoverflow.com/questions/3768768/loading-javascript-dynamically-and-how-to-check-if-the-script-exists] is there a way to make it to async defer?
    @samrodrigues I tried putting the script tag on the main. and do initMap() on the view page with this script `$(document).ready(function(){initMap();})` but somehow the maps image tile dont load except I zoom out (dont know whats making it like that). but when using script on the modal view page works good.
    – Calvin Oct 12 '16 at 09:35
  • have you tried to load the `` in the bottom of your code? Also, something that i can suggest you if you want to show googlemaps inside modal bootstrap, you can load the map outside the modal and then you `append` it using javascript :) – may Oct 12 '16 at 09:56
  • 1
    http://stackoverflow.com/questions/32216547/google-map-appear-with-grey-inside-modal-in-bootstrap – sam rodrigues Oct 12 '16 at 10:17
  • @samrodrigues I think the answer on the link you gave me will work. I cant try it yet cause the code is not on this laptop. – Calvin Oct 12 '16 at 10:24

2 Answers2

4

You could give the script tag an id and add it in with javascript if it's not already there. You will also have to check if the google map API has already loaded. Something like:

function initMap(){
   // your map set up scripts in here
    ...
}

if(window.google && window.google.maps){
    // the map API is already be loaded (from a previous button click, maybe)
    initMap();

} else if(!document.getElementById('google-map-script')) {
    // the script tag is not present so add it to the DOM
    var scriptTag = document.createElement('script');
    scriptTag .id = 'google-map-script';
    scriptTag .src = 'https://maps.googleapis.com/maps/api/js?key=AIzaSyAbePUCw9D44HfcTuiWyFQs_HbQ_6Qw-fA&signed_in=true&libraries=places&callback=initMap';
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(scriptTag);
}
kevmc
  • 1,284
  • 7
  • 8
0

I suggest to load map outside the modal.

Load map (wherever you want):

<div id="map" style="height:300px; width:895px;" align="center">

Show map inside modal under <div class="modal-body">

<div class="modal-fade">
 <div class="modal-dialog modal-lg">
  <div class="modal-content">
   <div class="modal-header">
   </div>
   <div class="modal-body" id='add'>

  <div class="map"></div>
and the rest of your modal body here...

<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAbePUCw9D44HfcTuiWyFQs_HbQ_6Qw-fA&signed_in=true&libraries=places&callback=initMap"
async defer></script>

In your javascript:

map =  new google.maps.Map(document.getElementById("map"),mapOptions);
setTimeout(function(){
        $('.map').append($("#map").css("margin-top","0px").get(0));
        },500);
may
  • 675
  • 1
  • 10
  • 26
  • Is the script placed on php file that is loaded by ajax?
    unfortunately, I can produce the map after I call the ajax.
    – Calvin Oct 12 '16 at 10:22