openlayers学习之popup弹窗实现(二)

一、定义popup弹窗dom对象

要展示弹窗,我们首先需要一个dom对象来承载。

<div id="popup" class="ol-popup">
        <a href="#" id="popup-closer" class="ol-popup-closer" onclick="closePopup();"></a>
        <div id="popup-title" class="popup-title"></div>
        <div id="popup-content" class="popup-content"></div>
    </div>

二、定义弹窗样式

在css文件中定义弹窗的样式。

.ol-popup {
    display: none;
    position: absolute;
    background-color: white;
    -moz-box-shadow: 0 1px 4px rgba(0,0,0,0.2);
    -webkit-filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
    filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
    border: 1px solid #cccccc;
    bottom: 12px;
    left: -50px;
    width: 200px;
}
.ol-popup:after, .ol-popup:before {
    top: 100%;
    border: solid transparent;
    content: " ";
    height: 0;
    width: 0;
    position: absolute;
    pointer-events: none;
}
.ol-popup:after {
    border-top-color: white;
    border-width: 10px;
    left: 48px;
    margin-left: -10px;
}
.ol-popup:before {
    border-top-color: #cccccc;
    border-width: 11px;
    left: 48px;
    margin-left: -11px;
}
.popup-title{
    font-weight: bold;
    border-bottom:1px solid #cccccc;
    padding: 5px 8px;
}
.popup-content{
    padding: 5px 8px;
}
.ol-popup-closer {
    text-decoration: none;
    position: absolute;
    top: 6px;
    right: 6px;
}
.ol-popup-closer:after {
    content: "✖";
}

三、定义Overlay

声明一个Overlay,为它绑定前面创建的dom对象,将其加进Map。

var overlay = new ol.Overlay({
    element: document.getElementById('popup'),             //绑定dom对象,纯js必须使用document绑定,不能像Map的dom对象,只写‘popup’
    autoPan: true,                  //点击地图边缘时,地图自动调节
    autoPanMargin: 20,
    positioning: 'center-center'
});
map.addOverlay(overlay);

四、设置单击地图后弹窗显示信息

设置当在地图上左键单击时,弹窗显示所点击的点的经纬度信息。

var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var title = document.getElementById('popup-title');
var closer = document.getElementById('popup-closer');

map.on("singleclick", function (evt) {
    var coordinate = evt.coordinate; // 获取坐标
    var hdms = ol.coordinate.toStringHDMS(ol.proj.toLonLat(coordinate)); // 转换坐标格式
    console.log(hdms);
    overlay.setPosition(coordinate);
    content.innerHTML = '<p>You clicked here:</p><code>' + hdms +
        '</code>';			//弹窗展示内容为经纬度信息
    container.style.display = 'block';
    title.innerHTML = "提示信息";
    title.style.display = 'block';
});

五、设置弹窗关闭事件

为弹窗右上角的关闭按钮设置关闭事件函数

function closePopup() {
    // 把弹窗位置设置为undefined,并清空坐标数据
    overlay.setPosition(undefined);
    document.getElementById("popup-closer").blur();
    return false;
}

最终效果如下:
在这里插入图片描述

  • 4
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值