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>


转载自:https://blog.csdn.net/GISShiXiSheng/article/details/46012383

You may also like...