<html>
<head>
<title>GeoJSON</title>
<link href="http://openlayers.org/en/v3.13.0/css/ol.css" type="text/css">
<script src="http://openlayers.org/en/v3.13.0/build/ol.js"></script>
<style type="text/css">
#mouse_p{
position: absolute;
top: 10px;
left: 10px;
z-index: 100;
}
#map{
position: relative;
top: 30px;
left: 30px;
width: 800px;
height: 300px;
}
#mouse_s{
position: absolute;
top: 10px;
right: 10px;
z-index: 100;
}
#demo{
position: absolute;
bottom: 0px;
right: 0px;
}
#type{
position: fixed;
bottom: 0px;
left: 0px;
}
</style>
</head>
<body>
<div id="map" >
<div id="mouse_p"></div>
<div id="mouse_s"></div></div>
<div id="demo"></div>
<button onclick="getfeatures()">click me</button>
<select id="type">
<option value="None">Modify</option>
<option value="Point">Point</option>
<option value="LineString">LineString</option>
<option value="Polygon">Polygon</option>
</select>
<script>
var style = {
'Polygon': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'yellow', width: 1
}),
fill: new ol.style.Fill({
color: 'rgba(255, 255, 0, 1)'
})
}),
'LineString': new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'red', width: 1
}),
}),
};
var styleFunction = function(feature) {
return style[feature.getGeometry().getType()];
};
var geojsonObject = {
'type': 'FeatureCollection',
'crs': {
'type': 'name'
},
'features':[]
};
var features = (new ol.format.GeoJSON()).readFeatures(geojsonObject);
var vectorSource = new ol.source.Vector({
features: features,
format: new ol.format.GeoJSON()
});
var vectorLayer = new ol.layer.Vector({
title: "Vector",
source: vectorSource,
style: styleFunction
});
var osm = new ol.layer.Tile({
source: new ol.source.OSM({layer: 'sat'})
});
var map = new ol.Map({
layers: [osm, vectorLayer],
target: 'map',
view: new ol.View({center: [2131312,6027113],zoom: 18})
});
var mousePosition = new ol.control.MousePosition({
target: 'mouse_p'
});
var scaleLine = new ol.control.ScaleLine({
target: 'mouse_s'});
map.addControl(scaleLine);
map.addControl(mousePosition);
var draw;
var typeSelect = document.getElementById('type');
var select = new ol.interaction.Select();
var modify = new ol.interaction.Modify({
features: select.getFeatures()
});
function addInteraction(){
var value = typeSelect.value;
if (value !== 'None') {
draw = new ol.interaction.Draw({
source: vectorSource,
type: (value)
});
map.addInteraction(draw);
vectorSource.addFeatures(draw);
}
else{
map.addInteraction(select);
map.addInteraction(modify);
}
}
typeSelect.onchange = function() {
map.removeInteraction(draw);
map.removeInteraction(select);
map.removeInteraction(modify);
addInteraction();
};
addInteraction();
var writer = new ol.format.GeoJSON();
var geojsonStr = writer.writeFeatures(vectorSource.getFeatures());
function getfeatures(){
document.getElementById("demo").innerHTML = geojsonStr;
}
</script>
<script>
</script>
</body>
</html>