Openlayers之Popup标注

1、Popup标注

Popup标注,即通过冒泡的方式显示标注点的信息,一般与基本的标注点一起使用,而且可以结合HTML、CSS等样式自定义标注信息样式,在弹出框中描述详细点的信息;

2、代码实现

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <link href="../css/ol.css" rel="stylesheet" />
    <script src="../lib/jquery/jquery.js"></script>
    <script src="../lib/ol/ol.js"></script>
    <style type="text/css">
        body, html
        {
            border:none;
            padding:0;
            margin:0;
        }
        #menu
        {
            width:100%;
            height:20px;
            padding:5px 10px;
            font-size:14px;
            font-family:"微软雅黑";
            left:10px;
        }
        .ol-popup
        {
            position:absolute;
            background-color:white;
            padding:15px;
            border-radius:10px;
            border:1px solid #cccccc;
            bottom:12px;
            left:-50px;
        }
        .ol-popup:after,.ol-popup:before
        {
            top:100%;
            border:solid transparent;
            content:" ";
            height:0px;
            width:0px;
            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;
            left:-11px;
        }
        .ol-popup-closer
        {
            text-decoration:none;
            position:absolute;
            top:2px;
            right:8px;
        }
        #popup-content
        {
            font-size:14px;
            font-family:"微软雅黑";
        }
        #popup-content .markerInfo
        {
            font-weight:bold;
        }
    </style>
    <script type="text/javascript">
        $(function () {
            //初始化地图
            var map = new ol.Map({
                target: 'map',
                layers: [
                    new ol.layer.Tile({
                        source:new ol.source.OSM()
                    })
                ],
                view: new ol.View({
                    center: [0, 0],
                    zoom:4
                })
            });
            //北京的地理坐标
            var beijing = ol.proj.fromLonLat([116.28, 39.54]);

            //要素信息
            var featureInfo = {
                //地理位置
                geo: beijing,
                //属性信息
                att: {
                    //标题
                    title: "北京市",
                    //超链接
                    titleURL: "http://www.baidu.com",
                    //文本内容
                    text: "北京,简称“京”,中华人民共和国首都、直辖市、国家中心城市、超大城市,全国政治中心、文化中心、国际交往中心、科技创新中心,是中国共产党...",
                    //图像地址
                    imgURL: "../images/label/bj.png"
                },
            };

            //创建标签样式
            var createLabelStyle = function (feature) {
                //返回一个样式
                return new ol.style.Style({
                    //点的样式
                    image: new ol.style.Icon({
                        //标注图片和文字之间的距离
                        anchor: [0.5, 60],
                        //标注样式的起点位置
                        anchorOrigin: 'top-right',
                        //X方向单位
                        anchorXUnits: 'fraction',
                        //Y方向单位
                        anchorYUnits: 'pixels',
                        //偏移起点位置的方向
                        offsetOrigin: 'top-right',
                        //透明度
                        opacity: 0.75,
                        //图标的url
                        src: '../images/label/blueIcon.png' 
                    }),
                    //文本样式
                    text: new ol.style.Text({
                        //对其方式
                        textAlign: 'center',
                        //基准线
                        textBaseline: 'middle',
                        //文字样式
                        font: 'normal 14px 微软雅黑',
                        //文本内容
                        text: feature.get('name'),
                        //文本填充样式
                        fill: new ol.style.Fill({ color: '#aa3300' }),
                        //笔触
                        stroke: new ol.style.Stroke({ color: '#ffcc33', width: 2 })
                    })
                });
            }

            //实例化Vector要素,通过矢量图层添加到地图容器中
            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中
            map.addLayer(vectorLayer);

            //获取id为popup的div标签
            var container = document.getElementById('popup');
            //获取id为popup-content的div标签
            var content = document.getElementById('popup-content');
            //获取id为popup-closer的a标签
            var closer = document.getElementById('popup-closer');

            //初始化一个覆盖层
            var popup = new ol.Overlay({
                //元素内容
                element: container,
                //If set to true the map is panned when calling setPosition, 
                //so that the overlay is entirely visible in the current viewport. 
                //The default is false.
                autoPan: true,
                ////覆盖层如何与位置坐标匹配
                positioning: 'bottom-center',
                //事件传播到地图视点的时候是否应该停止
                stopEvent: false,
                //The animation options used to pan the overlay into view. 
                //This animation is only used when autoPan is enabled. 
                autoPanAnimation: {
                    //动画持续时间
                    duration:250
                }
            });
            //将覆盖层添加到map中
            map.addOverlay(popup);

            //为要素添加信息的函数
            function addFeatureInfo(info) {
                //创建一个a标签元素
                var elementA = document.createElement('a');
                //设置a标签的样式类
                elementA.className = 'markerInfo';
                //设置a标签的超链接地址
                elementA.href = info.att.titleURL;
                //设置a标签的文本内容
                setInnerText(elementA, info.att.title);
                //将a标签元素添加到内容div标签中
                content.appendChild(elementA);

                //创建一个div标签元素
                var elementDiv = document.createElement('div');
                //设置div标签的内容
                setInnerText(elementDiv, info.att.text);
                //将div标签加入到内容div标签中
                content.appendChild(elementDiv);

                //创建一个图像标签
                var elementImg = document.createElement('img');
                //指定图像标签的URL
                elementImg.src = info.att.imgURL;
                //将img标签加入到内容div标签中
                content.appendChild(elementImg);
            }

            //设置文本函数
            function setInnerText(element,text) {
                if (typeof element.textContent == 'string') {
                    element.textContent = text;
                } else {
                    element.innerText = text;
                }
            }

            //为map注册一个单击事件的监听
            map.on('click', function (evt) {
                //获取坐标点
                var coordinate = evt.coordinate;

                //forEachLayerAtPixel(pixel, callback, opt_this, opt_layerFilter, opt_this2)
                //Detect layers that have a color value at a pixel on the viewport, 
                //and execute a callback with each matching layer. 
                //Layers included in the detection can be configured through opt_layerFilter.
                var feature = map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
                    //在视口中遍历所有具有像素颜色的图层,如果图层存在,则返回
                    return feature;
                });

                if (feature) {
                    //将内容div的内容清空
                    content.innerHTML = '';
                    //添加要素信息
                    addFeatureInfo(featureInfo);
                    //如果当前popup覆盖层没有坐标,则设置坐标
                    if (popup.getPosition() == undefined) {
                        popup.setPosition(coordinate);
                    }
                }
            });

            //为map注册一个pointermove事件的监听
            //pointermove事件
            //Triggered when a pointer is moved. 
            //Note that on touch devices this is triggered when the map is panned, so is not the same as mousemove.
            map.on('pointermove', function (e) {
                //Returns the map pixel position for a browser event relative to the viewport.
                //获取map的像素位置信息
                var pixel = map.getEventPixel(e.originalEvent);
                //hasFeatureAtPixel(pixel, opt_options)
                //Detect if features intersect a pixel on the viewport.
                //map视口中是否包含某个要素
                var hit = map.hasFeatureAtPixel(pixel);
                //设置符合当前条件的鼠标样式
                map.getTargetElement().style.cursor = hit ? 'pointer' : '';
            });
        });
    </script>
</head>
<body>
    <div id="menu">鼠标单击标注点弹出Popup标注</div>
    <div id="map">
         <div id="popup" class="ol-popup">
             <a href="#" id="popup-closer" class="ol-popou-closer"></a>
             <div id="popup-content"></div>
         </div>
    </div>
</body>
</html>

3、结果展示

未单击标注点之前


单击标注点之后,弹出该点的详细信息


转载自:https://blog.csdn.net/SmileCoffin/article/details/56014624

You may also like...

退出移动版