本文基于腾讯课堂老胡的课《跟我学Openlayers--基础实例详解》做的学习笔记,使用的openlayers 5.3.x api。
源码 见 1047.html ,对应的 官网示例 https://openlayers.org/en/latest/examples/kml-earthquakes.html?q=kml
image.png image.pngKML源,数据处理方式和前例相同
信息弹窗使用了bootstrap的tooltip
注意:引用bootstrap之前要先引用jQuery
<!DOCTYPE html>
<html>
<head>
<title>KML地震</title>
<link rel="stylesheet" href="../include/ol.css" type="text/css" />
<link rel="stylesheet" href="../include/bootstrap.css" type="text/css" />
<script src="../include/jquery.js"></script>
<script src="../include/ol.js"></script>
<script src="../include/bootstrap.min.js"></script>
</head>
<style>
#map {
position: relative;
}
#info {
position: absolute;
height: 1px;
width: 1px;
z-index: 100;
}
.tooltip.in {
opacity: 1;
}
.tooltip.top .tooltip-arrow {
border-top-color: white;
}
.tooltip-inner {
border: 2px solid white;
}
</style>
<body>
<div id="info"></div>
<div id="map" class="map"></div>
<script>
//定义地震样式
var styleCache = {};
var styleFunction = function (feature) {
var name = feature.get("name");
var magnitude = parseFloat(name.substr(2));
var radius = 5 + 20 * (magnitude - 5);
var style = styleCache[radius];
if (!style) {
style = new ol.style.Style({
image: new ol.style.Circle({
radius: radius,
fill: new ol.style.Fill({
color: "rgba(255, 153, 0, 0.4)"
}),
stroke: new ol.style.Stroke({
color: "rgba(255, 204, 0, 0.2)",
width: 1
})
})
});
styleCache[radius] = style;
}
return style;
};
var vector = new ol.layer.Vector({
source: new ol.source.Vector({
url: "../data/2012_Earthquakes_Mag5.kml",
format: new ol.format.KML({
extractStyles: false //注意,不从kml读取样式信息,只读取数据信息
})
}),
style: styleFunction //样式信息我们自己指定
});
var raster = new ol.layer.Tile({
source: new ol.source.Stamen({
layer: "toner"
})
});
var map = new ol.Map({
layers: [raster, vector],
target: "map",
view: new ol.View({
center: [0, 0],
zoom: 2
})
});
var info = $("#info"); //弹窗
info.tooltip({
animation: false,
trigger: "manual"
});
//传入屏幕坐标,根据屏幕坐标取得当前要素,弹框显示当前要素的文本信息
var displayFeatureInfo = function (pixel) {
info.css({
left: pixel[0] + "px",
top: pixel[1] - 15 + "px"
});
var feature = map.forEachFeatureAtPixel(pixel, function (feature) {
return feature;
});
if (feature) {
info
.tooltip("hide") //先隐藏,设置完了之后,再显示出来
.attr("data-original-title", feature.get("name"))
.tooltip("fixTitle")
.tooltip("show");
} else {
info.tooltip("hide");
}
};
map.on("pointermove", function (evt) {
if (evt.dragging) { //地图拖拽时,隐藏弹框
info.tooltip("hide");
return;
}
displayFeatureInfo(map.getEventPixel(evt.originalEvent));
});
</script>
</body>
</html>
网友评论