I want to include a map with OpenLayers3 in one div
of my web.
The function that determines and creates it is the following:
function traza_mapa() {
var myVista = new ol.View({
center: ol.proj.fromLonLat([-30,40],'EPSG:3857', 'EPSG:4326'),
zoom: 4,
});
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
],
view: myVista,
controls: new ol.control.defaults({
zoom: true,
attribution: false,
})
});
map.addControl(new ol.control.ZoomSlider());
};
traza_mapa();
It is at the end of a script that performs a series of operations at the click of a button. Specifically, it reads a local file and extracts a series of data from it.
This function is at the end and I want it to draw the map inside adiv id='map'
I understand that at the end of the statement traza_mapa()
I should include it in the div
. It doesn't. However if I run traza_mapa()
in the browser console once the local file is loaded it does draw the map.
I think what I need is for this function to call itself at the end of the script, but I can't see how.
The code for loading the text file is as follows
function handleFileSelect(evt) {
var files = evt.target.files;
var lectores = new Array();
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate.toLocaleDateString(), '</li>');
lectores[i] = new FileReader();
lectores[i].onload = function(e) {
resultados_texto = this.result;
}
lectores[i].readAsText(f);
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
Well, this "Hello World" from OpenLayers works fine for me.
And also this example using a button to load the map in the
div
:Now if I try using the example you've provided:
I have tried with three versions, using the version
3.2.0
gave me the following error:Make sure in the JavaScript console that the same thing isn't happening with your code.
I have then switched to versions
3.9.0
and3.15.0
and your code has run without problems.