一、效果
下拉列表操作方式中選擇draw的時候,可以繪製要素;選擇select的時候,可以選擇要素;選擇modify的時候,可以修改要素。
二、代碼
新建一個ModifyOL.HTML。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>openlayer修改要素</title>
<link href="ol/ol.css" rel="stylesheet" />
<script src="ol/ol.js"></script>
<script src="jquery-1.7.2.js"></script>
<style type="text/css">
#map,
html,
body {
height: 100%;
width: 100%;
}
.content {
width: 100px;
}
</style>
</head>
<body>
<div id="map"></div>
<form class="form-inline">
<label>操作方式 </label>
<select id="interaction">
<option value="draw">draw</option>
<option value="select">select</option>
<option value="modify">modify</option>
</select>
<label>幾何類型 </label>
<select id="type">
<option value="Point">Point</option>
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
<option value="Circle">Circle</option>
<option value="None">None</option>
</select>
</form>
<script>
var layers = [
new ol.layer.Tile({
source: new ol.source.XYZ({
url: "http://rt{0-3}.map.gtimg.com/realtimerender?z={z}&x={x}&y={-y}&type=vector&style=0"
})
})
];
var source = new ol.source.Vector({ wrapX: false });
var vector = new ol.layer.Vector({
source: source
});
var view = new ol.View({
center: ol.proj.transform([116.400146, 40.250184], 'EPSG:4326', 'EPSG:3857'),
zoom: 9
});
var map = new ol.Map({
layers: layers,
target: 'map',
view: view
});
map.addLayer(vector);
var typeSelect = document.getElementById('type');
var typeInteraction = document.getElementById('interaction');
var draw,snap;
// 定義選擇控件,wrapX爲false,當比例尺小於一定程度時,對象不會被切割
var select = new ol.interaction.Select({
wrapX: false
});
// 定義修改控件
var modify = new ol.interaction.Modify({
features: select.getFeatures()
});
function addInteraction() {
var interactionvalue = typeInteraction.value;
var value = typeSelect.value;
if (interactionvalue == 'draw' && value !== 'None') {
draw = new ol.interaction.Draw({
source: source,
type: typeSelect.value
});
map.addInteraction(draw);
snap = new ol.interaction.Snap({source: source});
map.addInteraction(snap);
}
else if (interactionvalue == 'select') {
map.addInteraction(select);
}else if (interactionvalue == 'modify') {
map.addInteraction(select);
map.addInteraction(modify);
map.addInteraction(snap);
}
}
/**
* 變更時激發
*/
typeSelect.onchange = function() {
map.removeInteraction(draw);
map.removeInteraction(snap);
map.removeInteraction(select);
map.removeInteraction(modify);
addInteraction();
};
typeInteraction.onchange = function() {
map.removeInteraction(draw);
map.removeInteraction(snap);
map.removeInteraction(select);
map.removeInteraction(modify);
addInteraction();
};
addInteraction();
</script>
</body>
</html>