2

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

1 Answer 1

5

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>

Sign up to request clarification or add additional context in comments.

1 Comment

I do not see any mention of the async and defer keywords the solution. Are these accounted for in any way or are they assumed to not be important in the answer? Asking to learn. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.