<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>OpenLayers 图形交互编辑</title>
<link rel="stylesheet" href="./include/ol.css" />
<script src="./include/ol.js"></script>
</head>
<body>
<div id="map"></div>
<script>
var pointFeature = new ol.Feature({
geometry: new ol.geom.Point([114.1947, 30.5255]),
name: "Point Feature",
});
var lineFeature = new ol.Feature({
geometry: new ol.geom.LineString([
[114.2218, 30.5695],
[114.2829, 30.4912],
]),
name: "Line Feature",
});
var polygonFeature = new ol.Feature({
geometry: new ol.geom.Polygon([
[
[114.2757, 30.5822],
[114.3526, 30.5879],
[114.3608, 30.5367],
[114.3234, 30.5187],
[114.2826, 30.553],
],
]),
name: "Polygon Feature",
});
var source = new ol.source.Vector({
features: [pointFeature, lineFeature, polygonFeature],
});
var vectorLayer = new ol.layer.Vector({
source: source,
style: new ol.style.Style({
fill: new ol.style.Fill({
color: "rgba(255, 255, 255, 0.2)",
}),
stroke: new ol.style.Stroke({ color: "#f00", width: 2 }),
image: new ol.style.Circle({
radius: 7,
fill: new ol.style.Fill({
color: "#f00",
}),
}),
}),
});
var map = new ol.Map({
layers: [
new ol.layer.Tile({
title: "天地图矢量地图",
source: new ol.source.XYZ({
url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=您的天地图密钥",
wrapX: false,
}),
}),
new ol.layer.Tile({
title: "天地图矢量地图",
source: new ol.source.XYZ({
url: "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=您的天地图密钥",
wrapX: false,
}),
}),
],
target: "map",
view: new ol.View({
center: [114.2905, 30.5607],
projection: "EPSG:4326",
minZoom: 2,
zoom: 12,
}),
});
map.addLayer(vectorLayer);
// 图形编辑
var Modify = {
init: function () {
this.select = new ol.interaction.Select();
map.addInteraction(this.select);
this.modify = new ol.interaction.Modify({
features: this.select.getFeatures(),
});
map.addInteraction(this.modify);
this.setEvents();
},
setEvents: function () {
var selectedFeatures = this.select.getFeatures();
this.select.on("change:active", function () {
selectedFeatures.forEach(selectedFeatures.remove, selectedFeatures);
});
},
setActive: function (active) {
this.select.setActive(active);
this.modify.setActive(active);
},
};
Modify.init();
Modify.setActive(true);
</script>
</body>
</html>