I am importing a map created using qgis2web inside a <iframe>
.
<iframe id="leaflet"
src="/qgis/index.html"
scrolling="no"
frameborder="0"
style="height: 100vh;width: 100%">
</iframe>
I need to access an object (the map) declared in a <script>
inside the /qgis/index.html file and modify some of its properties.
I was able to do it directly inside the /qgis/index.html file, but because this folder is exported from another software and will be often modify, I want to write all this code inside the main index.html file, where the map is imported inside the <iframe>
The object in the /qgis/index.html file :
<script>
...
var map = L.map('map', {zoomControl:true, maxZoom:18, minZoom:15});
...
</script>
...And the modifications I want to perform inside the main index.html file :
<script>
var lat = -0.017;
var lng = 0.015;
var zoom = 16;
map.setView([lat, lng], zoom);
</script>
I tried to do it via document.getElementById('map');
but it did not work.
EDIT 1
What I tried (unsuccessfully)
index.html :
<script>
var lat = -0.017;
var lng = 0.015;
var zoom = 16;
var map = document.getElementById("leaflet").contentWindow.map;
map.setView([lat, lng], zoom);
EDIT 2 Working, but the iframe load enters a loop and load itself indefinitely
index.html
<iframe id = 'iframeid'
src="/qgis/index.html"
scrolling="no"
frameborder="0"
style="height: 100vh;width: 100%"
onload="on_load(this)">
</iframe>
...
<script type="text/javascript">
function on_load(iframe) {
try {
var lat = -0.017;
var lng = 0.015;
var zoom = 16;
var map = document.getElementById("iframeid").contentWindow.map;
map.setView([lat, lng], zoom);
} catch (e) {
// This can happen if the src of the iframe is
// on another domain
alert('exception: ' + e);
}
}
</script>