openlayers之selectfeature

概述:

在本文叙述如何在openlayers中实现鼠标经过某一对象时,对象高亮;点击某一对象时,弹出该对象的信息。重点为OpenLayers.Layer.Vector和OpenLayers.Control.SelectFeature,下面开始讲解。

效果:

鼠标经过高亮显示对象名称

鼠标点击显示对象信息

实现:

1、创建地图,添加地图

        var map1, vectors;
        OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '2';
        $(function(){
            var bounds = new OpenLayers.Bounds(
                    73.45100463562233, 18.16324718764174,
                    134.97679764650596, 53.531943152223576
            );
            var options = {
                controls: [],
                maxExtent: bounds,
                maxResolution: 0.2403351289487642,
                projection: "EPSG:4326",
                units: 'degrees'
            };
            map1 = new OpenLayers.Map('map1', options);

            map1.addLayer(getWms("china"));
            map1.addControl(new OpenLayers.Control.Zoom());
            map1.addControl(new OpenLayers.Control.Navigation());
            map1.zoomToExtent(bounds);
            addVectors();
        });

2、添加矢量图层Vector,并添加测试对象

            var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
            renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;
            vectors = new OpenLayers.Layer.Vector("Vector Layer", {
                renderers: renderer
            });
            map1.addLayer(vectors);
            var wkts = [
                "POINT(107.5758285931443 29.7822116459692)",
                "LINESTRING(120.18304604073 30.3305841465568,108.805692477062 32.0850224203499)",
                "POLYGON((102.797302689433 36.5936423859273,105.519115206186 29.4789248520356,100.346180647351 19.9699202912212))"
            ];
            var wktFormat = new OpenLayers.Format.WKT();
            for(var i= 0,dl=wkts.length;i<dl;i++){
                var geometry = wktFormat.read(wkts[i]);
                vectors.addFeatures(geometry);
            }

3、添加鼠标高亮

            var selecthover = new OpenLayers.Control.SelectFeature(
                    vectors,
                    {
                        hover: true,
                        highlightOnly:true
                    }
            );
            map1.addControl(selecthover);
            map1.addControl(select);
            selecthover.activate();
            selecthover.events.on({
                'featurehighlighted': function(feature) {
                    var sFch = feature.feature;
                    var pt = sFch.geometry.getBounds().getCenterLonLat();
                    var scrPt = map1.getPixelFromLonLat(pt);
                    var div = $("<div />").appendTo($("#map1")).html(scrPt.x+","+scrPt.y).css("position","absolute")
                            .css("z-index","1001").css("background","#000").css("color","#fff").css("padding","5px 8px")
                            .css("left",scrPt.x+"px").css("top",scrPt.y+"px").attr("id","div");
                },
                'featureunhighlighted': function(feature) {
                    $("#div").remove();
                }
            });

4、添加点击对象显示信息

            var select =  new OpenLayers.Control.SelectFeature(
                    vectors,
                    {
                        clickout: true,
                        toggle: false,
                        multiple: false,
                        hover: false,
                        toggleKey: "ctrlKey", // ctrl key removes from selection
                        multipleKey: "shiftKey", // shift key adds to selection
                        box: true
                    }
            );
            select.activate();

            var selected;
            vectors.events.on({
                'featureselected': function(feature) {
                    $("#div").remove();
                    var selectedFeature = feature.feature;
                    selected = selectedFeature;
                    var pt = selectedFeature.geometry.getBounds().getCenterLonLat();
                    var popup=new OpenLayers.Popup("city",
                            pt,
                            new OpenLayers.Size(230,20),
                            "坐标:"+pt.lon+","+pt.lat,
                            true,
                            onPopupClose
                    );
                    popup.setBorder("1px solid #999");
                    selectedFeature.popup = popup;
                    map1.addPopup(popup,true);
                },
                'featureunselected': function(feature) {
                    var selectedFeature = feature.feature;
                    map1.removePopup(selectedFeature.popup);
                    selectedFeature.popup=null;
                }
            });

            function onPopupClose(){
                select.unselect(selected);
            }

注:

在实现鼠标经过高亮和点击对象显示属性都用到了OpenLayers.Control.SelectFeature,注意两者参数设置的区别!

完整代码如下:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>openlayers map</title>
    <link rel="stylesheet" href="http://localhost/olapi/theme/default/style.css" type="text/css">
    <style>
        html, body{
            padding:0;
            margin:0;
            height:100%;
            width:100%;
            overflow: hidden;
            font-size: 12px;
        }
        #map1{
            width: 100%;
            height: 100%;
            float: left;
            border-right: 1px solid #000000;
        }
    </style>
    <script src="http://localhost/olapi/OpenLayers.js"></script>
    <script src="http://localhost/olapi/lib/OpenLayers/Lang/zh-CN.js"></script>
    <script src="http://localhost/jquery/jquery-1.8.3.js"></script>
    <script>
        var map1, vectors;
        OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '2';
        $(function(){
            var bounds = new OpenLayers.Bounds(
                    73.45100463562233, 18.16324718764174,
                    134.97679764650596, 53.531943152223576
            );
            var options = {
                controls: [],
                maxExtent: bounds,
                maxResolution: 0.2403351289487642,
                projection: "EPSG:4326",
                units: 'degrees'
            };
            map1 = new OpenLayers.Map('map1', options);

            map1.addLayer(getWms("china"));
            map1.addControl(new OpenLayers.Control.Zoom());
            map1.addControl(new OpenLayers.Control.Navigation());
            map1.zoomToExtent(bounds);
            addVectors();
        });

        function getWms(layer){
            return new OpenLayers.Layer.WMS(
                    "Geoserver layers - Tiled",
                    "http://localhost:8081/geoserver/lzugis/wms",
                    {
                        "LAYERS": layer,
                        "STYLES": '',
                        format: 'image/png'
                    },
                    {
                        buffer: 0,
                        displayOutsideMaxExtent: true,
                        isBaseLayer: true,
                        yx : {'EPSG:4326' : true}
                    }
            );
        }

        function addVectors(){
            var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
            renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;
            vectors = new OpenLayers.Layer.Vector("Vector Layer", {
                renderers: renderer
            });
            map1.addLayer(vectors);
            var wkts = [
                "POINT(107.5758285931443 29.7822116459692)",
                "LINESTRING(120.18304604073 30.3305841465568,108.805692477062 32.0850224203499)",
                "POLYGON((102.797302689433 36.5936423859273,105.519115206186 29.4789248520356,100.346180647351 19.9699202912212))"
            ];
            var wktFormat = new OpenLayers.Format.WKT();
            for(var i= 0,dl=wkts.length;i<dl;i++){
                var geometry = wktFormat.read(wkts[i]);
                vectors.addFeatures(geometry);
            }

            var select =  new OpenLayers.Control.SelectFeature(
                    vectors,
                    {
                        clickout: true,
                        toggle: false,
                        multiple: false,
                        hover: false,
                        toggleKey: "ctrlKey", // ctrl key removes from selection
                        multipleKey: "shiftKey", // shift key adds to selection
                        box: true
                    }
            );
            var selecthover = new OpenLayers.Control.SelectFeature(
                    vectors,
                    {
                        hover: true,
                        highlightOnly:true
                    }
            );
            map1.addControl(selecthover);
            map1.addControl(select);
            selecthover.activate();
            selecthover.events.on({
                'featurehighlighted': function(feature) {
                    var sFch = feature.feature;
                    var pt = sFch.geometry.getBounds().getCenterLonLat();
                    var scrPt = map1.getPixelFromLonLat(pt);
                    var div = $("<div />").appendTo($("#map1")).html(scrPt.x+","+scrPt.y).css("position","absolute")
                            .css("z-index","1001").css("background","#000").css("color","#fff").css("padding","5px 8px")
                            .css("left",scrPt.x+"px").css("top",scrPt.y+"px").attr("id","div");
                },
                'featureunhighlighted': function(feature) {
                    $("#div").remove();
                }
            });
            select.activate();

            var selected;
            vectors.events.on({
                'featureselected': function(feature) {
                    $("#div").remove();
                    var selectedFeature = feature.feature;
                    selected = selectedFeature;
                    var pt = selectedFeature.geometry.getBounds().getCenterLonLat();
                    var popup=new OpenLayers.Popup("city",
                            pt,
                            new OpenLayers.Size(230,20),
                            "坐标:"+pt.lon+","+pt.lat,
                            true,
                            onPopupClose
                    );
                    popup.setBorder("1px solid #999");
                    selectedFeature.popup = popup;
                    map1.addPopup(popup,true);
                },
                'featureunselected': function(feature) {
                    var selectedFeature = feature.feature;
                    map1.removePopup(selectedFeature.popup);
                    selectedFeature.popup=null;
                }
            });

            function onPopupClose(){
                select.unselect(selected);
            }
        }
    </script>
</head>
<body>
    <div id="map1"></div>
</body>
</html>

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏JackieZheng

Spring读书笔记——bean加载

我们的日常开发几乎离不开Spring,他为我们的开发带来了很大的便捷,那么Spring框架是如何做到方便他人的呢。今天就来说说bean如何被加载加载。 我们在x...

22790
来自专栏大前端_Web

easyUI组件datagrid的二次封装

版权声明:本文为吴孔云博客原创文章,转载请注明出处并带上链接,谢谢。 https://blog.csdn.net/wkyseo/articl...

31630
来自专栏Kubernetes

runC源码分析——namespace

runc/libcontainer/configs/config.go中定义了container对应的Namespaces。另外对于User Namespace...

42380
来自专栏Android知识点总结

开源计划之--Android数字运动小插件--NumGo

8020
来自专栏GIS讲堂

excel中提取中文拼音

概述:在工作时,有时候会用到汉语拼音,本文讲述如何在Excel中通过vba程序提取汉字的拼音。

28330
来自专栏我的小碗汤

日志文件转储压缩实现

日志的转储和压缩是非常关键的,它不仅可以减少硬盘空间占用,主要还可以在发生故障时根据日志定位出故障原因。下面来看看golang和java的文件转储实现。

11410
来自专栏Java后端技术

复制指定源位置的多级文件夹下所有文件到指定目标位置

  3.遍历源位置文件夹下所有的文件,修改源位置为当前遍历项的文件位置,目标位置为刚刚上部创建的文件夹位置。

8610
来自专栏技术碎碎念

Tomcat启动过程源码解读

根据Tomcat源码来看一下Tomcat启动过程都做了什么 部分代码为主要流程代码,删去了try-catch以及一些校验逻辑,方便理解主流程 先来一张启动过程时...

39090
来自专栏xingoo, 一个梦想做发明家的程序员

【插件开发】—— 9 编辑器代码分块着色-高亮显示!

前文回顾: 1 插件学习篇 2 简单的建立插件工程以及模型文件分析 3 利用扩展点,开发透视图 4 SWT编程须知 5 SWT简单控件的使用与布局搭...

30260
来自专栏GIS讲堂

OL2中测量工具的扩展

11510

扫码关注云+社区

领取腾讯云代金券