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>
@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