<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://openlayers.org/en/v5.3.0/css/ol.css" />
<script type="text/javascript" src="https://openlayers.org/en/v5.3.0/build/ol.js"></script>
<title>Document</title>
</head>
<body>
<div id="selectedFeatures" style="margin: 20px;min-height: 100px;"></div>
<div id="map"></div>
<script>
var beijing = ol.proj.fromLonLat([116.28, 39.54]);
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
center: beijing,
zoom: 4
})
});
//實例化矢量點要素,通過矢量圖層添加到地圖容器中
//這樣就實現了預先加載圖文標注
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(beijing),
name: '北京市', //名稱屬性
population: 2115 //人口數(萬)
});
//設置點要素樣式
iconFeature.setStyle(createLabelStyle(iconFeature));
//矢量標注的數據源
var vectorSource = new ol.source.Vector({
features: [iconFeature]
});
//矢量標注圖層
var vectorLayer = new ol.layer.Vector({
source: vectorSource
});
map.addLayer(vectorLayer);
//矢量標注樣式設置函數,設置image為圖標ol.style.Icon
function createLabelStyle(feature){
// console.log(feature);
return new ol.style.Style({
text: new ol.style.Text({
textAlign: 'center', //位置
textBaseline: 'bottom', //基准線
font: 'normal 12px 微軟雅黑', //文字樣式
text: feature.get('name'), //文本內容
fill: new ol.style.Fill({ //文本填充樣式(即文字顏色)
color: '#000'
}),
stroke: new ol.style.Stroke({
color: '#F00',
width: 2
})
})
});
}
var coordinate1 = [10806361.310845079, 3942927.667062532]; //鼠標單擊點的坐標
var coordinate2 = [11540156.782382771, 4539747.983913189] //鼠標單擊點的坐標
var coordinate3 = [12225032.55581795, 3982063.4255445423] //鼠標單擊點的坐標
var arr =[coordinate1,coordinate2,coordinate3]
//新建一個要素ol.Feature
arr.forEach((ar,index) => {
var newFeature = new ol.Feature({
geometry: new ol.geom.Point(ar), //幾何信息
name: '標注點'+index
});
newFeature.setStyle(createLabelStyle(newFeature)); //設置要素樣式
vectorSource.addFeature(newFeature);
});
var draw = new ol.interaction.Draw({
source: vectorLayer.getSource(),
type:"Circle",
style:new ol.style.Style({
// 將點設置成圓形樣式
image: new ol.style.Circle({
// 點的顏色
fill: new ol.style.Fill({
color: '#F00'
}),
// 圓形半徑
radius: 5
}),
// 線樣式
stroke: new ol.style.Stroke({
color: '#0F0',
lineCap: 'round', // 設置線的兩端為圓頭
width: 5
})
}),
geometryFunction: ol.interaction.Draw.createBox() // 使畫出來的現狀為矩形
});
map.addInteraction(draw);
draw.on('drawend',function(evt){
var polygon = evt.feature.getGeometry();
setTimeout(function(){ //如果不設置延遲,范圍內要素選中后自動取消選中,具體原因不知道
var extent = polygon.getExtent()
var features = vectorLayer.getSource().getFeaturesInExtent(extent); //先縮小feature的范圍
var str = "";
for(var i=0;i<features.length;i++){
var newCoords = features[i].getGeometry().getCoordinates();
if (features[i].get("name")) {
str += "<div class=\"selectedItem\" οnclick='showDeviceOnMap(\""+features[i].getId()+"\");'>"+features[i].get("name")+"</div>";
}
}
document.getElementById('selectedFeatures').innerHTML = str
},300)
})
</script>
</body>
</html>