How to change image color in openlayers3? - javascript

I am new to openlayers3. I am showing point as a image but I want to change color of image dynamically.Is it possible in openlayers3 or have any other facility like canvas in openlayers3?
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'data/icon.png'
}))
});

Taking Icon Colors as starting point where they use a transparent PNG with ol.Color option to have multiple color dots I've tried to change the colors like this without success...
var london = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-0.12755, 51.507222]))
});
london.setStyle(new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
color: '#ff0000',
crossOrigin: 'anonymous',
src: 'https://openlayers.org/en/v4.1.1/examples/data/dot.png'
}))
}));
var vectorSource = new ol.source.Vector({
features: [london]
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
var rasterLayer = new ol.layer.Tile({
source: new ol.source.TileJSON({
url: 'https://api.tiles.mapbox.com/v3/mapbox.geography-class.json?secure',
crossOrigin: ''
})
});
var map = new ol.Map({
layers: [rasterLayer, vectorLayer],
target: document.getElementById('map'),
view: new ol.View({
center: ol.proj.fromLonLat([2.896372, 44.60240]),
zoom: 3
})
});
map.on('singleclick', function (event) { // Use 'pointermove' to capture mouse movement over the feature
map.forEachFeatureAtPixel(event.pixel, function (feature, layer) {
/* Get the current image instance and its color */
var image = feature.getStyle().getImage();
console.log(image.getColor());
/* Color gets stored in image.i, but there's no setter */
console.log(image.i);
/* Trying to force the color change: */
image.i = [0, 255, 0, 1];
/* Dispatch the changed() event on layer, to force styles reload */
layer.changed();
console.log(image.getColor()); // Logs new color, but it doesn't work...
});
});
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.1.1/build/ol.js"></script>
<div id="map" class="map"></div>
See how you can retrieve an icon's color like this:
var image = feature.getStyle().getImage(),
color = image.getColor(); // returns [R, G, B, alpha]
but there's no setColor() method, so there's no way to change the color in runtime...
EDIT: Reviewing again your question and your code, I've noticed you never set a color for your icon, so maybe you don't really want to actually change the color in response to an event but just set a color. If that's what you want, then it's easy:
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
src: 'data/icon.png',
color: '#ff0000' // allows HEX as String or RGB(a) as Array
}))
});
See: http://openlayers.org/en/latest/apidoc/ol.style.Icon.html

Related

How to display information using Overlay in Openlayers?

I had a vector in my map with an image but ned to use gif instead static image so i exchanged o.layer.vector for ol.Overlay, it displays my gif but I can't get any way to add it to my layerSwitcher because overlay doesn't have title property, also with vector i could display some information using forEachFeaturePixel but now i cant. Is there any way to add my overlay to layerSwitcher and display information clicking on it?
This is what i had:
lastPoint = new ol.layer.Vector({
source: new ol.source.Vector({
features: [new ol.Feature(
new ol.geom.Point(
ol.proj.fromLonLat(lastCoordinates, map.getView().getProjection())
)
)]
}),
visible: true,
title: "Evento sísmico",
style: new ol.style.Style({
image: new ol.style.Icon({
anchor: [0.5, 0.5],
size: [30, 28],
offset: [0.2, 0.2],
scale: 1,
src: "assets/img/red-point.png"
}),
}),
})
addEarthqPoint = (e, map, clickedCoordinate, date, time, depth, magnitude, overlayLayerEarthq) => {
map.forEachFeatureAtPixel(e.pixel, () => {
overlayLayerEarthq.setPosition(clickedCoordinate);
overlayTitleEarthq.innerHTML = "Detalle de evento: "
overlayFeatureDate.innerHTML = "Fecha: " + date;
overlayFeatureTime.innerHTML = "Hora (UTC-5): " + time;
overlayFeatureDepth.innerHTML = "Profundidad: " + depth + " km";
overlayFeatureMagnitude.innerHTML = "Magnitud: M " + magnitude;
}, {
layerFilter: (layerCandidate) => {
return layerCandidate.get("title") === "Evento sísmico";
}
});
}
mapClicked = (overlayLayer, overlayLayerEarthq) => {
map.on("click", function (e) {
const clickedCoordinate = e.coordinate;
overlayLayer.setPosition(undefined);
overlayLayerEarthq.setPosition(undefined);
/* using preview values to use into function */
addEarthqPoint(e, map, clickedCoordinate, lastDate, lastTime, lastDepth, lastMagnitude, overlayLayerEarthq);
});
}
This is my new Overlay:
lastPoint = new ol.Overlay({
position: ol.proj.fromLonLat(lastCoordinates, map.getView().getProjection()),
positioning: 'center-center',
element: document.getElementById('new-gif'),
stopEvent: false
});
Or is there any better way to use a gif instead an image?

How to load geojson file as a Tile Layer

I am trying to load the big GeoJSON file using the OpenLayers. The problem is after loading it then the complete map becomes slow to do any other operation. So my question is there anyway to load a geojson file as a Tile rather ?
Here is my code:
function addGEOJSONLayer() {
console.log("reached");
var url= 'http://172.61.25.51:8080/test/ab.json';
var vectorSource = new ol.source.Vector({
strategy: ol.loadingstrategy.bbox,
projection: 'EPSG:4326',
loader: function(extent, resolution, projection) {
$.ajax(url).then(function(response) {
console.log(response);
var features = new ol.format.GeoJSON().readFeatures(response);
vectorSource.addFeatures(features);
});
}
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: function (feature, resolution) {
return [new ol.style.Style({
stroke: new ol.style.Stroke({
width: 1,
color: feature.get('stroke')
}),
fill: new ol.style.Fill({
color: feature.get('fill'),
})
})];
}
});
var ext = vectorLayer.getSource().getExtent();
map.getView().fit(ext, map.getSize());
map.addLayer(vectorLayer);
}
Any suggestions will be of great help! Thanks

Changing Source url of a XYZ layer and redrawing the layer/map?

I wanna change the url of my ol3 map source. I've tryed using things such as map.set or map.getlayers().set or whatever but I can't seem to find a way to access my source object. Here's the code:
function init() {
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
projection: 'PIXELS',
tileGrid: mapTileGrid,
url: loc
})
})
],
view: new ol.View({
projection: ol.proj.get('PIXELS'),
extent: mapExtent,
maxResolution: mapTileGrid.getResolution(0)
})
});
map.getView().fit(mapExtent, map.getSize());
console.log(map.get("layergroup").get("layers").get("url"));
map.get("layergroup").get("layers").set("url",loc);
}
What's a way to change the url property and reload the layer ?
I also tried using the setSource function as in the following answer : here
but it seems to not work (can't setSource of undefined).
try the following
function init() {
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.XYZ({
projection: 'PIXELS',
tileGrid: mapTileGrid,
url: loc
})
})
],
view: new ol.View({
projection: ol.proj.get('PIXELS'),
extent: mapExtent,
maxResolution: mapTileGrid.getResolution(0)
})
});
map.getView().fit(mapExtent, map.getSize());
//get alll the layers exist on your map
var layers = map.getLayers();
//lets assume you want to set the url for the first layer found
layers[0].getSource().setUrl(loc);
}

OpenLayers-3 - What is the correct usage of source.clear()

I have a ol 3.10.1 map where the goal is to redraw the features of a layer dynamically. On the road to get there, I'm using the source.clear() function. The strange thing is that the source.clear() actually clear the features from the layer at the current zoom level, but while zooming in or out the features are still there. Am I using the source.clear() function the correct way? Please find bellow the code snippet which I'm using for testing purposes.
var image = new ol.style.Circle({
radius: 5,
fill: null,
stroke: new ol.style.Stroke({color: 'red', width: 1})
});
var styles = {
'Point': [new ol.style.Style({
image: image
})]};
var styleFunction = function(feature, resolution) {
return styles[feature.getGeometry().getType()];
};
var CITYClusterSource = new ol.source.Cluster({
source: new ol.source.Vector({
url: 'world_cities.json',
format: new ol.format.GeoJSON(),
projection: 'EPSG:3857'
}),
})
var CITYClusterLayer = new ol.layer.Vector({
source: CITYClusterSource,
style: styleFunction
});
setTimeout(function () { CITYClusterSource.clear(); }, 5000);
var map = new ol.Map({
target: 'map',
renderer: 'canvas',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
CITYClusterLayer
],
view: new ol.View({
center: ol.proj.transform([15.0, 45.0], 'EPSG:4326', 'EPSG:3857'),
zoom:3
})
});
I'm using the setTimout() function to have the features visible for some seconds, before they are supposed to be cleared.
Please advice.
UPDATE: http://jsfiddle.net/jonataswalker/ayewaz87/
I forgot, OL will load your features again and again, for each resolution. So if you want to remove once and for all, use a custom loader, see fiddle.
Your source is asynchronously loaded, so set a timeout when it's ready:
CITYClusterSource.once('change', function(evt){
if (CITYClusterSource.getState() === 'ready') {
// now the source is fully loaded
setTimeout(function () { CITYClusterSource.clear(); }, 5000);
}
});
Note the once method, you can use on instead of it.

How can i assign a logo to the vector source (GPX) in OpenLayers 3?

im learing OpenLayers 3 and i am trying to assign an png image to the logo attribute of the layer.Vector.source like this:
var vectorSpeedLimit40 = new ol.layer.Vector({
title: 'speedlimit40',
source: new ol.source.Vector({
url: 'gpx/Fotoboks_40.gpx',
format: new ol.format.GPX({
extraStyles: false
}),
logo: '/imgs/lc.png'
})
});
var rasterLayer = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [rasterLayer, vectorSpeedLimit40],
target: document.getElementById('map-canvas'),
view: new ol.View({
center: [0, 0],
zoom: 3
})
});
Where i thought this would show instances of the png, it shows small blue circles instead like this:
I have checked, double checked, triple checked and the path is correct relative to the client.
What am i doing wrong? Thanks!
To assign a specific image to a vectorLayer with a GPX source you have to assign the image property a new ol.style.Icon with the src attribute to the image like this:
var vectorSource = new ol.source.Vector({
// Specify that the source is of type GPX
format: new ol.format.GPX(),
// Here you specify the path to the image file
url: 'gpx/source.gpx'
})
var vectorStyle = new ol.style.Style({
// Set the image attribute to a new ol.style.Icon
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */ ({
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
scale: 0.2,
// Here you specify the path to the image file
src: 'imgs/image.png'
}))
})
var vectorLayer = new ol.layer.Vector({
// Here you specify the source and style attributes of the ol.layer.Vector to the ones that are made above
source: vectorSource,
style: vectorStyle
});
// Then add it to the map
map.addLayer(vectorLayer);

Categories