OpenLayers 3 image mask - javascript

I try to add on my map an image mask on the foreground, some kind of shadow frame.
The problem is that I've not been able to find a good solution to do so by trying:
precompose/postcompose overload (drawing the image with the canvas's ctx)
adding a layer
adding an overlay
adding a div over the map (events propagation issues and jQuery exceptions)
Has anyone faced this problem?

A solution is to bind on postcompose event.
Here is the JS code making it working:
var osm = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [osm],
target: 'map',
controls: ol.control.defaults({
attributionOptions: /** #type {olx.control.AttributionOptions} */ ({
collapsible: false
})
}),
view: new ol.View({
center: [0, 0],
zoom: 5
})
});
var image = new Image();
var loaded = false;
image.src = 'http://safari.am/images/frame_shadow.png';
image.onload = function() {
loaded = true;
};
osm.on('postcompose', function(event) {
var ctx = event.context;
if(loaded)
ctx.drawImage(image, 0, 0);
ctx.restore();
});
You can find the full solution in the following JSFiddle

Related

OpenLayers4: How to give icon a bigger click radius

I am trying to make an Icon feature that I can click on easier on mobile phones. I have an icon set up nicely and when using a mouse to click on it there is no issue. However when using my finger or thumb on a mobile phone it is quite difficult to get an accurate click. I am using a ol.geom.Point and giving it an icon style. I tried an ol.geom.Circle but I can't get the icon style to work with it.
Here is an example of my working ol.geom.Point:
for (i in spots) {
var spot = spots[i];
var coords = spot['coords'];
var lat = parseFloat(coords.split(',')[0]);
var lng = parseFloat(coords.split(',')[1]);
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([lng, lat])),
type: 'spot'
});
iconFeature.setStyle(spotMarker);
features.push(iconFeature);
}
vectorSourceSpots = new ol.source.Vector({
features: features
});
var vectorLayer = new ol.layer.Vector({
source: vectorSourceSpots
});
map.addLayer(vectorLayer);
Here is the spotMarker style:
var spotMarker = new ol.style.Style({
image: new ol.style.Icon(({
src: 'images/spot.png'
}))
});
I've also tried with a ol.geom.Circle but I could not see my icon when I tried this:
for (i in spots) {
var spot = spots[i];
var coords = spot['coords'];
var lat = parseFloat(coords.split(',')[0]);
var lng = parseFloat(coords.split(',')[1]);
var iconFeature = new ol.Feature({
geometry: new ol.geom.Circle(ol.proj.fromLonLat([lng, lat]), 5),
type: 'spot'
});
iconFeature.setStyle(spotMarker);
features.push(iconFeature);
}
vectorSourceSpots = new ol.source.Vector({
features: features
});
var vectorLayer = new ol.layer.Vector({
source: vectorSourceSpots
});
map.addLayer(vectorLayer);
What I want is to have the icon remain the same size, but just to increase the click radius around the icon. Almost like an invisible circle a bit bigger than the icon with the same center.
Is this possible?
You will use forEachFeatureAtPixel to add event on the features, then you can set hitTolerance on its options parameter.
check this api document: forEachFeatureAtPixel
you may need to write:
var addEvent = function(map, evt) {
map.forEachFeatureAtPixel(evt.pixel, function(feature, layer) {
}, {
hitTolerance: 10
});
};
map.on('click', function(evt) {
addEvent(map, evt);
});

How to turn off the blue dot left behind after using the extent interaction

I am using the Openlayers extent interaction to allow the user to select an AOI. After the user does this and removes the drawn extent I would like the blue dot to also disappear. Currently it just hangs out on the map and then pops back to the mouse once the interactions key is pressed again.
This behavior can be seen in the Openlayers Extent Interaction example here. Shift+drag starts the extent interaction. Shift+click removes the extent but the blue dot is left there. Is there a way to remove this ?? Once the extent is removed there is no other interaction possible with the blue dot, so what is the purpose of it even being there ??
If you check out the API docs for ol.interaction.Extent
You can pass a style to pointerStyle to update the style of the dot.
var extent = new ol.interaction.Extent({
condition: ol.events.condition.platformModifierKeyOnly,
pointerStyle: [] // <-- Makes the dot invisible
});
var vectorSource = new ol.source.Vector({
url: 'https://openlayers.org/en/v3.20.1/examples/data/geojson/countries.geojson',
format: new ol.format.GeoJSON()
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
}),
new ol.layer.Vector({
source: vectorSource
})
],
target: 'map',
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
var extent = new ol.interaction.Extent({
condition: ol.events.condition.platformModifierKeyOnly,
pointerStyle: []
});
map.addInteraction(extent);
extent.setActive(false);
//Enable interaction by holding shift
this.addEventListener('keydown', function(event) {
if (event.keyCode == 16) {
extent.setActive(true);
}
});
this.addEventListener('keyup', function(event) {
if (event.keyCode == 16) {
extent.setActive(false);
}
});
<link href="https://openlayers.org/en/v3.20.1/css/ol.css" rel="stylesheet" />
<script src="https://openlayers.org/en/v3.20.1/build/ol.js"></script>
<div id="map" class="map"></div>

Issue with layer rotation via compose hooks

I'm developing a tool to rotate a static image layer and I'm currently facing an issue on mobile.
Static image layer must rotate around a specific point. I use precompose and postcompose hooks in order to alter canvas and make the rotation.
It works great on desktop but i don't understand what is going on on mobile (Android Chrome or FF).
jsFiddle : https://jsfiddle.net/wuty2m9v/7/
/* Vars */
const center = ol.proj.transform([1.44, 43.603], "EPSG:4326", "EPSG:3857")
const imgSize = [400, 267]
const imgExtent = [center[0], center[1], center[0] + imgSize[0], center[1] + imgSize[1]]
let rotation = 45
/* Init map */
const map = new ol.Map({
target: 'map',
view: new ol.View({
zoom: 16,
center,
}),
layers: [
// Map tiles layer
new ol.layer.Tile({
source: new ol.source.OSM()
}),
// Feature layer
new ol.layer.Vector({
source: new ol.source.Vector({
features: [
new ol.Feature({
geometry: new ol.geom.Point(center),
}),
],
}),
}),
],
})
/* Init image layer */
const imgLayer = new ol.layer.Image({
opacity: 0.7,
source: new ol.source.ImageStatic({
url: "https://pbs.twimg.com/profile_images/685220121598660608/2uZUdcS1.jpg",
imageExtent: imgExtent,
})
})
imgLayer.on("precompose", evt => {
const pixel = map.getPixelFromCoordinate(center)
const ctx = evt.context
ctx.save()
ctx.translate(pixel[0], pixel[1])
ctx.rotate(rotation * Math.PI / 180)
ctx.translate(-pixel[0], -pixel[1])
})
imgLayer.on("postcompose", evt => {
const ctx = evt.context
ctx.restore()
})
map.addLayer(imgLayer)
On desktop, image rotate correctly around the point. Drag the map : point and image follow the map.
On mobile, image doesn't rotate correctly around the point, it is made around the canvas origin, canvas translations don't look good. Drag the map to watch the chaos :)
You'll need to take into account the pixel ratio when doing transforms. The pixels you get from map.getPixelFromCoordinate are css pixels. To get canvas pixels, you need to multiply them by ol.has.DEVICE_PIXEL_RATIO:
ctx.translate(pixel[0] * ol.has.DEVICE_PIXEL_RATIO, pixel[1] * ol.has.DEVICE_PIXEL_RATIO);
and
ctx.translate(-pixel[0] * ol.has.DEVICE_PIXEL_RATIO, -pixel[1] * ol.has.DEVICE_PIXEL_RATIO);
See https://jsfiddle.net/wuty2m9v/8/ for an updated version of your JSFiddle.
If you are interesting in drawing images on a OL3 map, take a look at the ol.source.GeoImage I've published on GitHub: http://viglino.github.io/ol3-ext/examples/map.geoimage.html
With your example: https://jsfiddle.net/Viglino/cqL17a3y/
/* Init image layer */
const imgLayer = new ol.layer.Image({
opacity: 0.7,
source: new ol.source.GeoImage({
url: "https://pbs.twimg.com/profile_images/685220121598660608/2uZUdcS1.jpg",
imageCenter: center,
imageScale: [1,1],
imageRotate: rotation*Math.PI/180,
projection: 'EPSG:3857',
})
})
Regards

OpenLayers 3: Trying to add image underlay to a vector layer

currently i have a vector map displayed using a KML file as the vector source.
what i want to do is have an image underlay this vector map.
The map is an indoor floormap, the image is the exact same as the vector map only there is more details in it, text written on it etc. What i need is for the map image to underlay the vector map so that the walls of the vector map align perfectly with the walls of the image. This can happen because the KML was created by tracing on top of the images using QGIS.
so far ive been able to have the KML vector map and png image appear on the map, but they are not alligned with each other and are not the same size. This is what i need help with!
here some code for what i currently have:
create the map, no layers yet (maps selected from dropdown boxes)
var map = new ol.Map({
layers: [],
target: 'floormap',
interactions: ol.interaction.defaults({mouseWheelZoom:false}),
view: new ol.View({
center: [0, 0],
zoom: 19,
minZoom: 15,
maxZoom: 30
})
});
add selected map (KML) to map
map.removeLayer(vector);
vector = new ol.layer.Vector({
source: new ol.source.Vector({
url: MAPS_URL + maps[map_id],
format: new ol.format.KML()
})
});
map.addLayer(vector);
setMapExtent(vector);
now i tried to add the image, which works but its not alligned
// this part here i feel may be the problem,
// i just copied and pasted from an example om openlayers.org,
// i dont actually know much about the extent and how to match it to
// the vector map
var extent = [0,0,1024,684];
var projection = new ol.proj.Projection({
code: 'xkcd-image',
units: 'pixels',
extent: extent
});
image = new ol.layer.Image({
source: new ol.source.ImageStatic({
attributions: [
new ol.Attribution({
html: '© xkcd'
})
],
url: MAPS_URL + images[map_id],
projection: projection,
imageExtent: extent
})
});
map.addLayer(image);
the setMapExtent method
function setMapExtent(vectorMap) {
var vectorSource = vectorMap.getSource();
var listenerKey = vectorSource.on('change', function () {
if (vectorSource.getState() === 'ready') {
var extent = vectorSource.getExtent();
map.getView().fitExtent(extent, map.getSize());
vectorSource.unByKey(listenerKey);
}
});
}
at this point i have a vector map with an image sitting way above the map, and the image seems to be smaller too.
Can anyone help me with this issue?
*** Solution! ***
a working solution, although probably not the best way to do it, but it works none the less.
var map = new ol.Map({
layers: [],
target: 'floormap',
interactions: ol.interaction.defaults({mouseWheelZoom:false}),
view: new ol.View({
center: [0, 0],
zoom: 19,
minZoom: 15,
maxZoom: 30
})
});
add new map layer
map.removeLayer(vector);
vector = new ol.layer.Vector({
source: new ol.source.Vector({
url: MAPS_URL + maps[map_id],
format: new ol.format.KML()
})
});
map.addLayer(vector);
setMapExtent(vector);
// call image adding function pass in vector
// to get its extend
addImage(vector);
the addImage function
function addImage(vectorMap) {
var vectorSource = vectorMap.getSource();
// listen for one change on the vector to get the extent of it
// for use in setting the image extent. tried to use on.('load')
// but it didnt work
var listenerKey = vectorSource.once('change', function () {
var extent = vectorSource.getExtent();
var projection = new ol.proj.Projection({
code: 'xkcd-image',
units: 'pixels',
extent: extent
});
image = new ol.layer.Image({
source: new ol.source.ImageStatic({
attributions: [],
url: MAPS_URL + images[map_id],
projection: projection,
imageExtent: extent
})
});
// remove vector layer else they keep stacking up
map.removeLayer(vector);
// add image
map.addLayer(image);
// re-add vector only push so it goes above the image
map.getLayers().push(vector);
});
}
seems to work pretty well! can anyone help me with layer ordering?
Your static image must be georeferenced correctly with the view's projection.
Default view's projection is EPSG:3857 (Spherical Mercator)., the extent of this projection is [-20026376.39, -20048966.10, 20026376.39, 20048966.10]
In your code you specify a projection in pixels for your static layer. You need to use the view's projection, something like this :
// Here the extent of your layer in EPSG:3857 -> [minx, miy, max, mayy]
var extent = [-10000000, -10000000, 10000000, 10000000];
image = new ol.layer.Image({
source: new ol.source.ImageStatic({
attributions: [
new ol.Attribution({
html: '© xkcd'
})
],
url: MAPS_URL + images[map_id],
imageSize: [1024, 684], // Don't forget the image size here
imageExtent: extent
})
});
map.addLayer(image);
Update:
For layer ordering if you want your vector layer on top use push:
http://openlayers.org/en/v3.8.2/apidoc/ol.Collection.html#push
map.getLayers().push(vector)

Marker or overlay moving animation moving smoothly in openlayers 3

I created a plunkr which has a moving marker like a car.
var olview = new ol.View({
center: [-5484111.13, -1884437.22],
zoom: 18,
minZoom: 2,
maxZoom: 20
});
var osm = new ol.source.OSM();
var lineString = new ol.geom.LineString([]);
var map = new ol.Map({
target: 'map',
view: olview,
renderer: 'canvas',
layers: [
new ol.layer.Tile({
source: osm,
opacity: 0.6
})
]
});
var car = document.getElementById('geo1');
var marker = new ol.Overlay({
positioning: 'center-center',
offset: [0, 0],
element: car,
stopEvent: false
});
map.addOverlay(marker);
var path = [
[-5484101.57, -1884475.44],
[-5484114.71, -1884432.74],
[-5484117.70, -1884416.62],
[-5484106.95, -1884392.28]
];
lineString.setCoordinates(path);
map.once('postcompose', function(event) {
console.info('postcompose');
interval = setInterval(animation, 500);
});
var i = 0, interval;
var animation = function(){
if (i == path.length){
i = 0;
}
marker.setPosition(path[i]);
i++;
};
This is written in openlayers, I want it to look smooth when moving similar to this.
https://github.com/terikon/marker-animate-unobtrusive
I'm a complete beginner in openlayers, can someone help me with this? Thanks!
I've made three tests. First and second are pure ol3 and last is with tween.js.
I'm using Arc.js to create a path.
The first example is using setInterval.
The second example is using window.requestAnimationFrame.
And the last with Tween.js.
Your example doesn't run smoothly because it is just a few coordinates.
Note that the Tween.js integration is not an integration at all. It is just a tricky CSS manipulation.

Categories