I'm writing a userscript (greasemonkey script) that needs to add a google map to a page on a website that I don't control.
I tried to add the script like so (which works well when loading other scripts that I tried) :
var my_script = document.createElement('script');
my_script.setAttribute('src',
'https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false');
document.head.appendChild(my_script);
But this fails with:
Failed to execute 'write' on 'Document': It isn't possible to write into a
document from an asynchronously-loaded external script unless it is explicitly
opened.
How can I load and use the maps api from a userscript?
Go to the Google Maps Platform > Credentials page. On the Credentials page, click Create credentials > API key. The API key created dialog displays your newly created API key. Click Close.
Applications using the Places API are bound by the terms of your Agreement with Google. Subject to the terms of your Agreement, you must not pre-fetch, index, store, or cache any Content except under the limited conditions stated in the terms.
map() is a very useful function but, unfortunately, it only works with synchronous functions. A simple workaround for using async map functions is to use Promose. all() or its more tolerant brother Promise.
according to the docs it's only possible to load the API per script
unless you provide the parameter callback
=> load Google Maps API asynchronously
I don't have any experience in writing userscripts but i hope it helps.
ATTENTION: Don't forget to add the callback function into the global namespace.
(In plain JS you would add it to the window object.)
You have to add a callback function to the script loading. If you are using it in phonegap, you should check internet connection, and also if it is already loaded. Yuo can ask and I will give you the piece of code.
<!DOCTYPE html>
<html>
<head>
<title>Asynchronous Loading</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script>
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644)
};
var 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.exp&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With