I want to create a webapp in which the user can draw features on a raster and add attributes to it. Sadly, I am a bit of a newbie.
Using OpenLayers and a GeoServer, I succesfully managed to display a raster on the OpenLayers. Furthermore, I also managed to create a draw layer, in which the user can choose between options: point, circle and polygon.
Now I only want to add the option to add attributes to the feature that has been drawn. (And subsequently for example, click afterwards on it to see said attributes).
Creating the map (‘…’ for working stuff that I don’t necessarily want to disclose):
var mapView = new ol.View ({
center: ol.proj.fromLonLat([..., ...]),
zoom: ...,
});
var map = new ol.Map ({
target: 'map',
view: mapView,
})
var noneTile = new ol.layer.Tile({
title: 'None',
type: 'base',
visible: false
});
var osmTile = new ol.layer.Tile ({
title: 'Open Street Map',
visible: true,
type: 'base',
source: new ol.source.OSM()
});
// map.addLayer(osmTile)
var baseGroup = new ol.layer.Group({
title: 'Base Maps',
fold: true,
layers: [osmTile, noneTile]
});
map.addLayer(baseGroup)
var Raster = new ol.layer.Tile({
title: 'Raster',
source: new ol.source.TileWMS({
url: ...,
params: {'LAYERS':..., 'TILED': true},
serverType: 'geoserver',
visible: true
})
});
// map.addLayer(Raster);
So this works, now I add the draw function:
// Add draw layer
const source = new ol.source.Vector({wrapX: false});
const drawLayer = new ol.layer.Vector({
source: source,
});
const typeSelect = document.getElementById('type');
let draw; // global so we can remove it later
function addInteraction() {
const value = typeSelect.value;
if (value !== 'None') {
draw = new ol.interaction.Draw({
source: source,
type: typeSelect.value,
});
map.addInteraction(draw);
}
}
/**
* Handle change event.
*/
typeSelect.onchange = function () {
map.removeInteraction(draw);
addInteraction();
};
document.getElementById('undo').addEventListener('click', function () {
draw.removeLastPoint();
});
addInteraction();
I think these are the most important parts of the code. Now, this gives me nicely the map with the raster on it and the ability to draw features. But I cannot add attributes yet, and I am stuck there.
What I tried (following: Assign Id / name attribute for uniquely identifying drawn polygon):
let draw; // global so we can remove it later
function addInteraction() {
const value = typeSelect.value;
if (value !== 'None') {
draw = new ol.interaction.Draw({
source: source,
type: typeSelect.value,
});
map.addInteraction(draw);
draw.on('drawend', function(evt){
var feature = evt.feature;
feature.setId(some_uniq_id);
//do you want to set other properties?
feature.setProperties({
name: 'some_name'
});
});
}
}
But this does not work for me. At least, I cannot see the id and attributes and the drawn polygon removes from itself.
What am I doing wrong or what do I need to do/add?