I have a page that has a map of OpenLayers ( version 3 ). On this map, I have inserted some interactions, such as: Create and change polygons. Well, so far, all right.
I create the polygons, which are saved in an array variable and at the same time are written to the database for later reference or change. Still on the same page, without closing it or doing any refresh page, I select the polygon that I want to change, and it is redrawn on the map and I can change it and save it again without problems .
However, the problem is here, when you close the page and access it again, the system searches for the polygons that have already been saved in the database, and when selecting to do the editing, it redraws the polygon on the map, but I do not I can modify it.
I wanted help to find out why I can not change it.
Map code:
var vectorSource = new ol.source.Vector();
// create a vector layer used for editing
var vector_layer = new ol.layer.Vector({
title: 'Vetores',
visible: false,
name: 'my_vectorlayer',
source: vectorSource,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(255, 255, 255, 0.2)'
}),
stroke: new ol.style.Stroke({
color: '#ffcc33',
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: '#ffcc33'
})
})
})
});
var overlayGroup = new ol.layer.Group({
title: 'Layers',
layers: []
});
mapPrincipal = new ol.Map({
target: 'map',
renderer: 'canvas',
//renderer: 'webgl',
layers: [
new ol.layer.Group({
'title': 'Mapas',
layers: [
new ol.layer.Tile({
title: 'Water color',
type: 'base',
visible: false,
source: new ol.source.Stamen({
layer: 'watercolor'
})
}),
new ol.layer.Tile({
title: 'OSM',
type: 'base',
visible: true,
source: new ol.source.OSM()
}),
new ol.layer.Group({
title: 'Satellite and roads',
type: 'base',
combine: true,
visible: false,
layers: [
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'sat'})
}),
new ol.layer.Tile({
source: new ol.source.MapQuest({layer: 'hyb'})
})
]
}),
new ol.layer.Tile({
title: 'Satellite',
type: 'base',
visible: false,
source: new ol.source.MapQuest({layer: 'sat'})
})
]
}),
overlayGroup,
new ol.layer.Group({
title: 'Dimensionamento',
layers: [vector_layer]
})
],
view: new ol.View({
zoom: 12,
center: ol.proj.transform([-49.086656570434556, -26.486168960979036], 'EPSG:4326', 'EPSG:3857')
})
});
Code for creation and change:
var Modify = {
coords: '',
init: function() {
this.select = new ol.interaction.Select();
mapPrincipal.addInteraction(this.select);
this.modify = new ol.interaction.Modify({
features: this.select.getFeatures()
});
mapPrincipal.addInteraction(this.modify);
this.setEvents();
},
setEvents: function() {
var selectedFeatures = this.select.getFeatures();
this.select.on('change:active', function() {
console.log('Feature ativa!');
console.log(selectedFeatures);
selectedFeatures.forEach(selectedFeatures.remove, selectedFeatures);
});
this.modify.on('modifyend',function(e){
//Draw.setCoord(e.features.getArray()[0].getGeometry().getCoordinates());
elevatorias[chave].coords = e.features.getArray()[0].getGeometry().getCoordinates();
});
$(document).on('keyup', function(event) {
if (event.keyCode == 46) {
// remove all selected features from select_interaction and my_vectorlayer
selectedFeatures.forEach(function(selected_feature) {
var selected_feature_id = selected_feature.getId();
// remove from select_interaction
selectedFeatures.remove(selected_feature);
// features aus vectorlayer entfernen
var vectorlayer_features = vector_layer.getSource().getFeatures();
vectorlayer_features.forEach(function(source_feature) {
var source_feature_id = source_feature.getId();
if (source_feature_id === selected_feature_id) {
// remove from my_vectorlayer
vector_layer.getSource().removeFeature(source_feature);
}
});
});
}
});
},
setActive: function(active) {
this.select.setActive(active);
this.modify.setActive(active);
},
setStyle: function(hex) {
/*
vector_layer.setStyle(new ol.style.Style({
stroke: new ol.style.Stroke({ color: '#000' }),
text: new ol.style.Text({
font: '12px Calibri,sans-serif',
fill: new ol.style.Fill({ color: '#000' }),
stroke: new ol.style.Stroke({
color: '#fff', width: 2
})
})
}));
*/
var hexToRBAColor = ol.color.asArray(hex);
vector_layer.getSource().forEachFeature(function(feature){
feature.setStyle(new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(' + hexToRBAColor[0] + ', ' + hexToRBAColor[1] + ', ' + hexToRBAColor[2] + ', 0.2)'
}),
stroke: new ol.style.Stroke({
color: hex,
width: 2
}),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: hex
})
})
}));
});
},
clearMap: function() {
vector_layer.getSource().clear();
if (this.select.getFeatures()) {
this.select.getFeatures().clear();
}
}
};
Modify.init();
var Draw = {
coords: '',
lineString: '',
kmRedeTotal: 0,
color: '',
wgs84Sphere: '',
init: function() {
/* Declaração de variáveis */
coords = new Array();
lineString = new Array();
kmRedeTotal = 0;
wgs84Sphere = new ol.Sphere(6378137);
mapPrincipal.addInteraction(this.Polygon);
this.Polygon.setActive(false);
mapPrincipal.addInteraction(this.LineString);
this.LineString.setActive(false);
this.Polygon.on('drawend', function(event) {
//coords[coords.length] = event.feature.getGeometry().getCoordinates()[0];
elevatorias[chave].coords = event.feature.getGeometry().getCoordinates();
marker_layer.getSource().forEachFeature(function(e) {
if (ol.extent.containsCoordinate(event.feature.getGeometry().getExtent(), e.getGeometry().getCoordinates())) {
clientes.push({nome: e.get('name'), id: e.get('id'), consumo: e.get('consumo')});
}
});
});
this.LineString.on('drawend', function(event) {
lineString[lineString.length] = event.feature.getGeometry().getCoordinates();
console.log(lineString);
for(var i = 1; i <= (lineString[(lineString.length-1)].length-1); i++){
kmRedeTotal += Draw.CalculateDistance(lineString[(lineString.length-1)][(i-1)][0], lineString[(lineString.length-1)][(i-1)][1], lineString[(lineString.length-1)][i][0], lineString[(lineString.length-1)][i][1]);
};
console.log(kmRedeTotal);
});
var button = document.createElement('button');
button.innerHTML = '<i class="glyphicon glyphicon-ok" style="font-size: 0.6em;"></i>';
button.setAttribute("title", "Desenhar Polígono");
var button2 = document.createElement('button');
button2.innerHTML = '<i class="glyphicon glyphicon-pencil" style="font-size: 0.6em;"></i>';
button2.setAttribute("title", "Alterar Polígono");
var button3 = document.createElement('button');
button3.innerHTML = '<i class="glyphicon glyphicon-remove" style="font-size: 0.6em;"></i>';
button3.setAttribute("title", "Deletar Polígono");
var button4 = document.createElement('button');
button4.innerHTML = '<i class="glyphicon glyphicon-tint" style="font-size: 0.6em;"></i>';
button4.setAttribute("title", "Mudar a cor");
button4.setAttribute("id", "btnChangeColor");
var button5 = document.createElement('button');
button5.innerHTML = '<i class="glyphicon glyphicon-cog" style="font-size: 0.6em;"></i>';
button5.setAttribute("title", "Calcular Kilômetro de Rede");
button5.setAttribute("id", "btnCalcKmRede");
button.addEventListener('click', function(e) {
Draw.setActive(true, 'Polygon');
Modify.setActive(false);
}, false);
button2.addEventListener('click', function(e) {
Draw.setActive(false, 'Polygon');
Modify.setActive(true);
}, false);
button3.addEventListener('click', function(e) {
Modify.clearMap();
}, false);
button4.addEventListener('click', function(e) {
$(this).ColorPicker({
onSubmit: function(hsb, hex, rgb, el) {
color = '#' + hex;
$(el).ColorPickerHide();
Modify.setStyle(color);
}});
}, false);
button5.addEventListener('click', function(e) {
Draw.getActive() && Draw.setActive(true, 'LineString');
}, false);
var element = document.createElement('div');
element.className = 'rotate-north ol-unselectable ol-control';
element.setAttribute("style", "display:none;");
element.appendChild(button);
element.appendChild(button2);
element.appendChild(button3);
element.appendChild(button4);
element.appendChild(button5);
mapPrincipal.addControl(new ol.control.Control({
element: element
}));
},
setCoord: function(value) {
coords = value;
},
getColor: function() {
return color;
},
getCoord: function() {
return coords;
},
getKmTotalRede: function() {
return kmRedeTotal;
},
getLineString: function() {
return lineString;
},
LineString: new ol.interaction.Draw({
source: vector_layer.getSource(),
type: /** @type {ol.geom.GeometryType} */ ('LineString')
}),
Polygon: new ol.interaction.Draw({
source: vector_layer.getSource(),
type: /** @type {ol.geom.GeometryType} */ ('Polygon')
}),
getActive: function() {
return this.activeType ? this[this.activeType].getActive() : false;
},
setActive: function(active, type) {
if (active) {
this.activeType && this[this.activeType].setActive(false);
this[type].setActive(true);
this.activeType = type; //'Polygon';
} else {
this.activeType && this[this.activeType].setActive(false);
this.activeType = null;
}
},
CalculateDistance: function(lng1, lat1, lng2, lat2) {
return wgs84Sphere.haversineDistance(Draw.Transform(lng1,lat1),Draw.Transform(lng2,lat2));
},
Transform: function(lng, lat) {
return ol.proj.transform([lng, lat], 'EPSG:3857', 'EPSG:4326');
}
};
Draw.init();
// The snap interaction must be added after the Modify and Draw interactions
// in order for its map browser event handlers to be fired first. Its handlers
// are responsible of doing the snapping.
var snap = new ol.interaction.Snap({
source: vector_layer.getSource()
});
mapPrincipal.addInteraction(snap);
Here is the code that is in the button that creates the polygon:
Draw.setActive(true, 'Polygon');
Modify.setActive(false);
Here is the code that is in the button that changes the polygon that is already stored in the database:
Modify.setActive(true);
Modify.setStyle(elevatorias[chave].color);
vectorSource.addFeature(new ol.Feature({
name: 'my_vectorlayer',
geometry: new ol.geom.Polygon(elevatorias[chave].coords)
}));
elevatorias
is the array variable that received the polygons that are in the database.
So that's it, gentlemen.