Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17570

Google Map javascript api key

I am using a cordova application and have a browser key for map.

<script async defer

        src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBHJxzPHD_egYnhxntqcvfem35YRjruzAg&callback=initMap">
</script>

but I want to take my key from server , I took and I store this key as

localStorage.getItem("MapCode")

this locastorage gives

"https://maps.googleapis.com/maps/api/js?key=AIzaSyBHJxzPHD_egYnhxntqcvfem35YRjruzAg&callback=initMap"

so I want to write this to src but I couldn't do it.

<script async defer

            src=localStorage.getItem("MapCode")>
    </script>

How can I solve this?Thanks in advance

Upvotes: 2

Views: 11596

Answers (1)

xomena
xomena

Reputation: 32100

You can load Google Maps JavaScript API dynamically. For this purpose you can create the following code:

function loadScript() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = localStorage.getItem("MapCode");
    document.body.appendChild(script);
}

window.onload = loadScript;

Please look at the sample code http://jsbin.com/carobun/edit?html,output

code snippet:

var map;

function initialize() {
    var c = new google.maps.LatLng(54.8867537,-1.557352);
    var mapOptions = {
        zoom:7,
        center: c
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
 
function loadScript() {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://maps.googleapis.com/maps/api/js?v=3' +
        '&key=AIzaSyDztlrk_3CnzGHo7CFvLFqE_2bUKEq1JEU&callback=initialize';
    document.body.appendChild(script);
}

window.onload = loadScript;    
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<div id="map-canvas"></div>

Upvotes: 5

Related Questions