Can't get OpenLayers 3 map to display in Bootstrap modal - javascript

It looks like there is a weird bug when trying to display an ol3 map within a modal. The map is in the modal but it doesn't display. Resizing the window manually forces it display however. Here's a link to try and see what I mean. Click on the settings pulldown within each map. Click on 'Get Feature Info'. This will toggle the modal with a map in it (but not displaying). Resize your window. Voila!
I tried many ways to use javascript and jQuery to trigger a resize event along the lines of:
$('#featinfo').on('shown.bs.modal', function () {
ol.Map.event.trigger(map5, "resize"); //borrowed from google.maps.event. How to do this in ol3?
});
Help?

I had the same problem. You need to force the map to load after the modal has been open.
Try having a function that inits the map:
function loadMap () {
var map = new ol.Map({
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}).extend([mousePositionControl]),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
}
And shown.bs.modal is the event trigered once the modal is opened
<script>
$('#GazModal').on('shown.bs.modal', function () {
loadMap();
})
</script>

Have you tried:
map.updateSize();

Make sure you set a height and width for the Open Layers map container..
#map {
width:100%;
height:500px;
}
Demo: http://www.bootply.com/68637

In the controller of my modal I create the map when the rendered promise from $modalInstance is resolved
$modalInstance.rendered.then(function () {
createMap();
});

It seems that the creation of the modal and the map is happening almost simultaneously so when you create the map it can't find the div element to create it. I put a small timeout after the creation of the modal to solve it
setTimeout(() => {
const map2 = new Map({
target: 'scanmap',
layers: [
new TileLayer({ source: new OSM() })
],
view: new View({
center: [0, 0],
zoom: 6
})
});
}, 100);

In an AngularJS application i had the same problem.
I resolved it by adding a little timout on $onInit()
constructor(private $log: ILogService, private $window: any, private $timeout: ITimeoutService) {
}
$onInit() {
// we need a timout here to load map after the modal!
this.$timeout(() => {
this.initMyMap();
});
}

Related

"map.once is not a function error" trying to duplicate OpenLayers example

I am trying to duplicate this OpenLayers 6 example
https://openlayers.org/en/latest/examples/export-map.html
It is to a javascript to download your OpenLayers 6 map
I am using different configuration and haven't been able to get it to work
http://australiamap.ca/export-map/
I get a "map.once is not a function error"
Here is your code (i truncated some part for readability)
window.onload = init;
function init(){
const torontoCenterCoordinate = [-8850000, 5410000]
const map = new ol.Map({
view: new ol.View({
center: torontoCenterCoordinate,
zoom: 10
}),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map'
})
}
function init2(){
...
}
document.getElementById('export-png').addEventListener('click', function () {
map.once('rendercomplete', function () {
...
});
map.renderSync();
});
You are trying to access variable map which is declare inside function init inside event listener of click. That's possible due to how scope work in JavaScript.
There is a coincidence that map actually resolve to a DOM element (in modern browser if you have an HTML element with id map then browser will save that element into variable map for you)
To fix your problem, you can either:
Move move to global scope so event listener can access it
// outside of init
const map = new ol.Map({
view: new ol.View({
center: torontoCenterCoordinate,
zoom: 10
}),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map'
})
Move even listener inside init
function init(){
const torontoCenterCoordinate = [-8850000, 5410000]
const map = new ol.Map({
view: new ol.View({
center: torontoCenterCoordinate,
zoom: 10
}),
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map'
})
document.getElementById('export-png').addEventListener('click', function () {
map.once('rendercomplete', function () {
...
});
map.renderSync();
});
}

"SecurityError: This operation is insecure" when calling domtoimage.toPng() in OpenLayers example

I am currently working on adding functionality to convert an OpenLayers Map into a png file (The example is here). However, when calling domtoimage.toPng() in the below code, Firefox (Ubuntu version 68.0.2) gives me the error SecurityError: This operation is insecure. I have checked all around and no one else seems to be having this problem with the dom-to-image library, and so I am stuck on how to fix this error. My JavaScript code for the Map is very similar to the code given in the example and is given here:
<script type="text/javascript">
var extent = [0, 0, 3000, 4213];
var projection = new ol.proj.Projection({
code: 'my-image',
units: 'pixels',
extent: extent,
});
var map = new ol.Map({
controls: ol.control.defaults().extend([
new ol.control.FullScreen()
]),
layers: [
new ol.layer.Image({
source: new ol.source.ImageStatic({
attributions: 'My Image Attributions',
url: "{{record | img_url}}", // Django stuff defined earlier
projection: projection,
imageExtent: extent
})
})
],
target: 'map',
view: new ol.View({
projection: projection,
center: ol.extent.getCenter(extent),
zoom: 2,
maxZoom: 8
})
});
map.addOverlay(new ol.Overlay({
position: [0, 0],
element: document.getElementById('null')
}));
// export options for dom-to-image.
var exportOptions = {
filter: function(element) {
return element.className ? element.className.indexOf('ol-control') === -1 : true;
}
};
document.getElementById('export-png').addEventListener('click', function() {
map.once('rendercomplete', function() {
domtoimage.toPng(map.getTargetElement(), exportOptions)
.then(function(dataURL) {
var link = document.getElementById('image-download');
link.href = dataURL;
link.click();
});
});
map.renderSync();
});
The HTML is effectively the same as in the example and so I believe the problem lies somewhere in here. Perhaps it is something with using a StaticImage in the Map? Or maybe going through the Django framework tampers with it in some unknown way? I am not entirely sure, and any diagnosis/help with fixing this issue would be much appreciated.
I think there should be something like:
new ol.layer.Tile({
name: 'name',
source: new ol.source.TileWMS({
...
crossOrigin: 'anonymous' // <-- Add this to the json.
})
})
Read more:
https://openlayers.org/en/v4.6.5/apidoc/ol.source.ImageWMS.html
https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image

How do I trigger an on demand refresh/redraw of ol.Map

I have a function called "LoadMap"
rcisWebMapLoad.prototype.LoadMap = function (param1, param2) {
//Get some vector objects and create layers
var fieldVectorObjs = rcisWebMapVectorObjs.GetFieldVectorObjects(param1, param2);
var objectVectorLines = rcisWebMapVectorObjs.GetLinesVectorObjects(param1, param2, 1);
//Create Map object and add layers then insert into map div
control.map = new ol.Map({
target: 'map',
renderer: 'canvas',
layers: layers,
view: new ol.View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 8
})
});
//******* MapServer imagery ***************
var aerial = new ol.layer.Tile({
name: 'Imagery',
source: new ol.source.TileWMS({
url: mapServerPath.ResponseString,
params: { 'LAYERS': 'aerial', 'FORMAT': 'image/png', 'TILED': true },
serverType: 'mapserver'
})
});
control.map.addLayer(aerial);
}
This loads the map great!!
I have my imagery and vector objects on the map...however the problem comes when I want to switch to a different map ie.(Different imagery and vector objects)...
UPDATE:
originally I thought the map was not getting updated but in reality another map get's generated and added right under the original map...How do I reuse or replace the map object that is already there to display another map?
Because I'm using AngularJS and passing the maps parameters through a service I can not just call the page again and get the parameters from the query string as someone suggested to me before.
This seems like something that would be a main function for an online map.
Any help is greatly appreciated
Okay, so I was not able to force an on-demand refresh of the map object for OpenLayers 3.
So what I ended up doing was to destroy the map object and create a new one each time.
so for the example above it would look like this...
For angularJS users you also need to make sure that you create an empty map in your .factory load function (so there is something to destroy initially)...if you're not using angular you would just need to create the map on page load.
function rcisWebMapLoad() {
this.map = new ol.Map({});
}
rcisWebMapLoad.prototype.LoadMap = function (param1, param2) {
//Get some vector objects and create layers
var fieldVectorObjs = rcisWebMapVectorObjs.GetFieldVectorObjects(param1, param2);
var objectVectorLines = rcisWebMapVectorObjs.GetLinesVectorObjects(param1, param2, 1);
var layers = [];
Destroy map object before creating a new one
control.map.setTarget(null);
control.map = null;
//Create Map object and add layers then insert into map div
control.map = new ol.Map({
target: 'map',
renderer: 'canvas',
layers: layers,
view: new ol.View({
projection: 'EPSG:4326',
center: [0, 0],
zoom: 8
})
});
//******* MapServer imagery ***************
var aerial = new ol.layer.Tile({
name: 'Imagery',
source: new ol.source.TileWMS({
url: mapServerPath.ResponseString,
params: { 'LAYERS': 'aerial', 'FORMAT': 'image/png', 'TILED': true },
serverType: 'mapserver'
})
});
control.map.addLayer(aerial);
}

How to store map tiles locally using openlayers

I just picked up a piece of code from the openlayers3 examples see HERE, now everytime you click the "geolocate me" button the tiles of the map are reloaded , now is there anyway for the tiles of the map to be stored locally ? I.E. when i click on the "geolocate me!" button the 2nd time around the tiles should be loaded from the users browser locally, rather than being fetched from the internet.
The code for generating the map is as following:
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: view
});
I tried the following using localstorage:
if(localStorage.layer) {
localStorage.setItem('layer' , JSON.stringify(new ol.layer.Tile({ source: new ol.source.OSM()}) )); console.log(localStorage.layer);
}
var map = new ol.Map({
layers: localStorage.layer ? [JSON.parse(localStorage.getItem('layer'))] : [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: * #type {olx.control.AttributionOptions} ({
collapsible: false
})
}),
view: view
});
But this does't seem to work, what can i do so that the tiles of the map are stored locally instead of being loaded from over the internet ?
a example i have seen using the DOJO library is HERE.

OpenLayers 3.6.0 TouchEvents

I can't seem to add event listeners for touch events. Only moveend gets fired.
map.on('zoomend', mapEvent);
map.on('moveend', mapEvent);
map.on('touchmove', mapEvent);
map.on('touchstart', mapEvent);
None of these work
map = new ol.Map({
eventListeners: {
"zoomend": mapEvent,
"changelayer": mapEvent,
"changebaselayer": mapEvent,
"mousedown": mapEvent,
"touchmove": mapEvent
},
And this causing an error - "Uncaught TypeError: Cannot read property 'register' of undefined"
map.events.register('touchmove', map, function(e) {
console.log("touchmove")
});
map.events.register('touchend', map, function(e) {
console.log("touchend")
});
So now I'm totally lost!?
That is exactly what is supposed to happen!
All those events you listed, besides moveend, don't exist on OpenLayers 3.6.0 anymore. Also, the config option eventListeners under ol.Map doesn't exist.
You can check all events and config options for ol.Map on the official API docs. The events are listed on Fires section.
Additionally, check this JSFiddle for some other events (pointermove, pointerdrag). On Chrome, you can also use Developer Tools (F12) to emulate a touch device and see what happens.
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
map.on('moveend', function(e) {
console.log("moveend")
});
map.on('pointermove', function(e) {
console.log("pointermove")
});
map.on('pointerdrag', function(e) {
console.log("pointerdrag")
});

Categories

Resources