openlayers 利用draw交互组件实现框选功能,并显示框选经纬度
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../js/ol.js"></script>
<script src="../js/jquery-3.3.1.min.js"></script>
<link href="../css/ol.css" rel="stylesheet"/>
<style type="text/css">
body, html {
width: 100%;
height: 100%;
margin: 0;
font-family: "Microsoft YaHei"
}
#map, #info {
width: 60%;
height: 60%;
}
</style>
</head>
<body>
<div id="btn">
<button id="btnclick" onclick="clickHandler()">框选范围</button>
</div>
<div id="map"></div>
<div id="info">
<table>
<tr>
<td>框选范围:</td>
<td>左上角坐标:</td>
<td>经度:<input id="zjd" readonly=“readonly”/></td>
<td></td>
<td>右下角坐标:</td>
<td>经度:<input id="yjd" readonly=“readonly”/></td>
</tr>
<tr>
<td></td>
<td></td>
<td>纬度:<input id="zwd" readonly=“readonly”/></td>
<td></td>
<td></td>
<td>纬度:<input id="ywd" readonly=“readonly”/></td>
</tr>
</table>
</div>
<script>
var style = new ol.style.Style({
fill: new ol.style.Fill({
color: 'rgba(96,96,96, 0.3)'
}),
//划线的时候的图样
stroke: new ol.style.Stroke({
color: 'rgba(96,96,96, 0.3)',
width: 2
}),
image: new ol.style.Circle({
radius: 5,
stroke: new ol.style.Stroke({
color: 'rgba(96,96,96, 0.3)'
}),
fill: new ol.style.Fill({
color: 'rgba(96,96,96, 0.3)'
})
})
});
var source = new ol.source.OSM();
map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: source
})
],
view: new ol.View({
center: ol.proj.transform([120.15, 30.28], 'EPSG:4326', 'EPSG:3857'),
zoom: 9
})
});
var source = new ol.source.Vector();
var layer = new ol.layer.Vector({
source: source,
style: style
});
var draw = new ol.interaction.Draw({
source: layer.getSource(),
type: 'Circle',
style: style,
geometryFunction: ol.interaction.Draw.createBox()
});
function clickHandler(e1) {
$('#map').bind("click", function (e) {
var pointermove = $('#map').bind("pointermove", function (e2) {
var coordinate = ol.proj.transform(map.getEventCoordinate(e2), 'EPSG:3857', 'EPSG:4326');
$("#yjd").attr("value", coordinate[0].toFixed(2));
$("#ywd").attr("value", coordinate[1].toFixed(2));
}).bind("click", function () {
$("#map").off('pointermove');
$("#map").off('click');
});
if ($("#zjd").val() == "" && $("#zwd").val() == "") {
var coordinate = ol.proj.transform(map.getEventCoordinate(e), 'EPSG:3857', 'EPSG:4326');
$("#zjd").attr("value", coordinate[0].toFixed(2));
$("#zwd").attr("value", coordinate[1].toFixed(2));
}
});
if ("取消框选" == ($("#btnclick").text())) {
$("#btnclick").text("框选范围");
$("input").attr("value", "");
layer.getSource().clear();
map.removeLayer(layer);
} else {
$("#btnclick").text("取消框选");
map.addInteraction(draw);
}
}
draw.on('drawend', function () {
map.addLayer(layer);
map.removeInteraction(draw);
});
</script>
</body>
</html>
转载自:https://blog.csdn.net/qq_39846607/article/details/85274998