openlayers地图点击事件(OpenLayers 点击显示经纬度Demo)
导读:这里给大家分享我在OpenLayers地图开发工作中总结出的一下代码和注意点,希望对大家有所帮助...
这里给大家分享我在OpenLayers地图开发工作中总结出的一下代码和注意点 ,希望对大家有所帮助
效果如下:
核心代码展示:附带讲解注释
点位图片:
完整demo代码:
<!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>点击出点位</title>
<style>
*{padding: 0;margin: 0}
.list-box {
width: 300px;
height: 100px;
background: white;
box-sizing: border-box;
padding: 20px;
line-height: 60px;
overflow: auto;
position: fixed;
right: 10px;
top: 10px;
z-index: 999;
text-align: center;
}
</style>
</head>
<body>
<div id="map"></div>
<div class="list-box">
</div>
<script>
var map = new ol.Map({ // 初始化地图
target: map,// 选择地图对象
layers: [
new ol.layer.Tile({// 初始化Tile外部图层
source: new ol.source.XYZ({// 初始化XYZ切片服务图层
url:
n
function createLabelStyle(feature) {
return new ol.style.Style({
image: new ol.style.Icon({
anchor: [40, 42],
scale: 0.5, // 图标缩小显示
anchorOrigin: top-right, // 标注样式的起点位置
anchorXUnits: pixels, // X方向单位:分数
anchorYUnits: pixels, // Y方向单位:像素
offsetOrigin: bottom-left, // 偏移起点位置的方向
opacity: 1, // 透明度
src: dian.png //图标的URL
}),
text: new ol.style.Text({
textAlign: center, //位置
textBaseline: middle, //基准线
font: normal 14px 微软雅黑, //文字样式
fill: new ol.style.Fill({ //文本填充样式(即文字颜色)
color: #000
}),
stroke: new ol.style.Stroke({
color: #F00,
width: 2
})
})
});
}
var newFeature = new ol.Feature({
geometry: new ol.geom.Point([0,0]) //几何信息
});
newFeature.setStyle(createLabelStyle(newFeature)); //设置要素样式
vectorSource.addFeature(newFeature);
map.on(click, function (evt) {
var coordinate = evt.coordinate; //鼠标单击点的坐标
//新建一个要素ol.Feature
newFeature.set(geometry,new ol.geom.Point(coordinate))
document.getElementsByClassName("list-box")[0].innerHTML = <p> 经度: + coordinate[0].toFixed(3) + 纬度: + coordinate[1].toFixed(3) + </p>
});
map.on(moveend, function (evt) {
if (map.getView().getZoom() >= 16) {
BGLayer.setVisible(true)
} else {
BGLayer.setVisible(false)
}
})
</script>
</body>
</html>
如果对您有所帮助 ,欢迎您点个关注,我会定时更新技术文档 ,大家一起讨论学习 ,一起进步 。
声明:本站所有文章 ,如无特殊说明或标注 ,均为本站原创发布 。任何个人或组织 ,在未征得本站同意时 ,禁止复制 、盗用 、采集、发布本站内容到任何网站 、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益 ,可联系我们进行处理 。
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!