openlayer调用geoserver发布的地图实现地图的基本功能

主要实现的功能有放大,缩小,获取地图大小,平移,线路测量,面积测量,拉宽功能,显示标注,移除标注,画多边形获取经纬度坐标。根据经纬度坐标显示多边形。地图切换,图层控制等功能

Html代码 复制代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4.     <head>  
  5.         <title>OpenLayers map preview</title>  
  6.         <!-- Import OL CSS, auto import does not work with our minified OL.js build -->  
  7.         <link rel="stylesheet" type="text/css" href="../theme/default/style.css"/>  
  8.          <link rel="stylesheet" href="../theme/default/google.css" type="text/css">  
  9.         <!-- Basic CSS definitions -->  
  10.         <style type="text/css">  
  11.             /* General settings */   
  12.             body {   
  13.                 font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;   
  14.                 font-size: small;   
  15.             }   
  16.             /* Toolbar styles */   
  17.             #toolbar {   
  18.                 position: relative;   
  19.                 padding-bottom: 0.5em;    
  20.                   
  21.             }   
  22.                
  23.             /* The map and the location bar */   
  24.             #map {   
  25.                 clear: both;   
  26.                 position: relative;   
  27.                 width: 698px;   
  28.                 height: 330px;   
  29.                 border: 1px solid black;   
  30.             }   
  31.                
  32.             #wrapper {   
  33.                 width: 698px;   
  34.             }   
  35.                
  36.             #location {   
  37.                 float: right;   
  38.             }   
  39.   
  40.             /* Styles used by the default GetFeatureInfo output, added to make IE happy */   
  41.             table.featureInfo, table.featureInfo td, table.featureInfo th {   
  42.                 border: 1px solid #ddd;   
  43.                 border-collapse: collapse;   
  44.                 margin: 0;   
  45.                 padding: 0;   
  46.                 font-size: 90%;   
  47.                 padding: .2em .1em;   
  48.             }   
  49.                
  50.             table.featureInfo th {   
  51.                 padding: .2em .2em;   
  52.                 text-transform: uppercase;   
  53.                 font-weight: bold;   
  54.                 background: #eee;   
  55.             }   
  56.                
  57.             table.featureInfo td {   
  58.                 background: #fff;   
  59.             }   
  60.                
  61.             table.featureInfo tr.odd td {   
  62.                 background: #eee;   
  63.             }   
  64.                
  65.             table.featureInfo caption {   
  66.                 text-align: left;   
  67.                 font-size: 100%;   
  68.                 font-weight: bold;   
  69.                 text-transform: uppercase;   
  70.                 padding: .2em .2em;   
  71.             }   
  72.         </style>  
  73.         <!-- Import OpenLayers, reduced, wms read only version -->  
  74.        <script src="../lib/OpenLayers.js" ></script>  
  75.         <script src="http://maps.google.com/maps/api/js?sensor=false"></script>  
  76.         <script defer="defer" type="text/javascript">  
  77.             var map, measureControls;   
  78.             var untiled;   
  79.             var tiled;   
  80.                
  81.             function init(){   
  82.                 format = 'image/png';   
  83.                 var bounds = new OpenLayers.Bounds(  //地图区域范围   
  84.                     74.137, 6.319,   
  85.                     135.086, 53.558   
  86.                 );   
  87.                 var options = {   
  88.                     controls: [],   
  89.                      maxExtent: bounds,   
  90.                     maxResolution: 0.23808203125,   
  91.                     projection: "EPSG:4610",   
  92.                     numZoomLevels: 7,    
  93.                     units: 'degrees'   
  94.                 };   
  95.                 map = new OpenLayers.Map('map', options);   
  96.            
  97.                /**********************加载图层 开始*******************************/   
  98.               /*   tiled = new OpenLayers.Layer.WMS(  //图层组   
  99.                     "基础图层", "http://localhost:8080/geoserver/wms",   
  100.                     {   
  101.                         height: '330',   
  102.                         width: '698',   
  103.                         layers: 'sf',   
  104.                         styles: '',   
  105.                         srs: 'EPSG:4326',   
  106.                         format: format,   
  107.                         tiled: 'true',   
  108.                         tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom   
  109.                     },   
  110.                     {   
  111.                         buffer: 0,   
  112.                         displayOutsideMaxExtent: true   
  113.                     }    
  114.                 );*/   
  115.                    
  116.                 var streams = new OpenLayers.Layer.WMS(    //图层组   
  117.                     "中国", "http://localhost:8080/geoserver/wms",   
  118.                     {   
  119.                        height: '330',   
  120.                         width: '698',   
  121.                         layers: 'china',   
  122.                         styles: '',   
  123.                         srs: 'EPSG:4610',   
  124.                         format: format,   
  125.                         tiled: 'true',   
  126.                         tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom   
  127.                     },   
  128.                     {   
  129.                         buffer: 0,   
  130.                         displayOutsideMaxExtent: true   
  131.   
  132.                     }    
  133.                 );   
  134.                
  135.                 untiled = new OpenLayers.Layer.WMS(  //单独图层   
  136.                     "省会", "http://127.0.0.1:8080/geoserver/wms",   
  137.                     {   
  138.                         height: '330',   
  139.                         width: '698',   
  140.                         layers: 'china:provice',   
  141.                         styles: '',   
  142.                         srs: 'EPSG:4610',   
  143.                         transparent: "true",   
  144.                         format: format   
  145.                     },   
  146.                     {singleTile: true, ratio: 1}    
  147.                 );   
  148.                  untiled.setVisibility(false); //设置为不显示   
  149.                 //var gmap = new OpenLayers.Layer.Google("Google Streets", {visibility: false});       
  150.                 /* var dm_wms = new OpenLayers.Layer.WMS( "点图层",   
  151.                 "http://127.0.0.1:8080/geoserver/wms",   
  152.                 {layers: "sf:bugsites,sf:archsites",   
  153.                  transparent: "true", format: "image/png"});*/   
  154.   
  155.                map.addLayers([streams,untiled]);   
  156.               /********************END 加载图层*********************************/   
  157.   
  158.                /************************加载一般的基础控件********************************/      
  159.                 map.addControl(new OpenLayers.Control.PanZoomBar({  //添加平移缩放工具条   
  160.                     position: new OpenLayers.Pixel(2, 15)   
  161.                 }));   
  162.                 map.addControl(new OpenLayers.Control.Navigation());  //双击放大,平移   
  163.                 map.addControl(new OpenLayers.Control.Scale($('scale')));  //获取地图比例尺   
  164.                 map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));  //获取鼠标的经纬度   
  165.                 map.setCenter(new OpenLayers.LonLat(100.254, 35.25), 1);  //添加平移缩放工具条   
  166.                 map.addControl(new OpenLayers.Control.OverviewMap());  //添加鹰眼图   
  167.                 map.addControl(new OpenLayers.Control.LayerSwitcher({'ascending':false}));  //图层切换工具               
  168.                 map.addControl(new OpenLayers.Control.Permalink('xxxx'));  //添加永久链接   
  169.                 //map.addControl(new OpenLayers.Control.MouseToolbar());   
  170.   
  171.                 //map.zoomToMaxExtent();   
  172.                 var zb=new OpenLayers.Control.ZoomBox({out:true});   
  173.                 var panel = new OpenLayers.Control.Panel({defaultControl: zb});   
  174.                 map.addControl(panel);   
  175.              /************END************加载一般的基础控件********************************/      
  176.   
  177.                /***********************鼠标点击,获取图层数据*******************************/      
  178.                 map.events.register('click', map, function (e) {   
  179.                     document.getElementById('nodelist').innerHTML = "Loading... please wait...";   
  180.                     var params = {   
  181.                         REQUEST: "GetFeatureInfo",   
  182.                         EXCEPTIONS: "application/vnd.ogc.se_xml",   
  183.                         BBOX: map.getExtent().toBBOX(),   
  184.                         X: e.xy.x,   
  185.                         Y: e.xy.y,   
  186.                         INFO_FORMAT: 'text/html',   
  187.                         QUERY_LAYERS: map.layers[0].params.LAYERS,   
  188.                         FEATURE_COUNT: 50,   
  189.                         Layers: 'ok',   
  190.                         Styles: '',   
  191.                         Srs: 'EPSG:4610',   
  192.                         WIDTH: map.size.w,   
  193.                         HEIGHT: map.size.h,   
  194.                         format: format};   
  195.                     OpenLayers.loadURL("http://localhost:8080/geoserver/wms", params, this, setHTML, setHTML);   
  196.                     OpenLayers.Event.stop(e);   
  197.                 });   
  198.               /**************END*********鼠标点击,获取图层数据*******************************/      
  199.   
  200.             /**********************************点、线、面测量开始**********************************************/   
  201.              var sketchSymbolizers = {   
  202.                 "Point": {   
  203.                     pointRadius: 4,    
  204.                     graphicName: "square",   
  205.                     fillColor: "white",   
  206.                     fillOpacity: 1,   
  207.                     strokeWidth: 1,   
  208.                     strokeOpacity: 1,   
  209.                     strokeColor: "#333333"   
  210.                 },   
  211.                 "Line": {   
  212.                     strokeWidth: 3,   
  213.                     strokeOpacity: 1,   
  214.                     strokeColor: "#666666",   
  215.                     strokeDashstyle: "dash"   
  216.                 },   
  217.                 "Polygon": {   
  218.                     strokeWidth: 2,   
  219.                     strokeOpacity: 1,   
  220.                     strokeColor: "#666666",   
  221.                     fillColor: "white",   
  222.                     fillOpacity: 0.3   
  223.                 }   
  224.             };   
  225.             var style = new OpenLayers.Style();   
  226.             style.addRules([   
  227.                 new OpenLayers.Rule({symbolizer: sketchSymbolizers})   
  228.             ]);   
  229.              var styleMap = new OpenLayers.StyleMap({"default": style});   
  230.              measureControls = {   
  231.                 line: new OpenLayers.Control.Measure(   
  232.                     OpenLayers.Handler.Path, {   
  233.                         persist: true,   
  234.                         handlerOptions: {   
  235.                             layerOptions: {styleMap: styleMap}   
  236.                         }   
  237.                     }   
  238.                 ),   
  239.                 polygon: new OpenLayers.Control.Measure(   
  240.                     OpenLayers.Handler.Polygon, {   
  241.                         persist: true,   
  242.                         handlerOptions: {   
  243.                             layerOptions: {styleMap: styleMap}   
  244.                         }   
  245.                     }   
  246.                 )   
  247.             };   
  248.              var control;   
  249.             for(var key in measureControls) {   
  250.                 control = measureControls[key];   
  251.                 control.events.on({   
  252.                     "measure": handleMeasurements,   
  253.                     "measurepartial": handleMeasurements   
  254.                 });   
  255.                 map.addControl(control);   
  256.             }   
  257.             /***************************END************点,线、面积测量*****************************************/   
  258.   
  259.               //添加点标注的图层   
  260.               markers = new OpenLayers.Layer.Markers("markers");   
  261.               map.addLayer(markers);     
  262.               markers.setZIndex(200);   
  263.   
  264.        }   
  265.                
  266.         //获取面积的结果赋值   
  267.           function handleMeasurements(event) {   
  268.             var geometry = event.geometry;   
  269.             var units = event.units;   
  270.             var order = event.order;   
  271.             var measure = event.measure;   
  272.             var element = document.getElementById('output');   
  273.             var out = "";   
  274.             if(order == 1) {   
  275.                 out += "面积为: " + measure.toFixed(3) + " " + units;   
  276.             } else {   
  277.                 out += "面积为: " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";   
  278.             }   
  279.             element.innerHTML = out;   
  280.         }   
  281.         function setHTML(response){   
  282.             document.getElementById('nodelist').innerHTML = response.responseText;   
  283.         };   
  284.         //缩小   
  285.         function zoomOut(){   
  286.             map.zoomOut();   
  287.         }   
  288.         //放大   
  289.         function zoomIn(){   
  290.             map.zoomIn();   
  291.         }   
  292.         //获取地图数据   
  293.         function getSize(){   
  294.             alert(map.getSize()+",高度为="+map.getSize().h);   
  295.         }   
  296.         //切换鼠标事件功能   
  297.         function toggleControl(_value) {   
  298.                
  299.             for(key in measureControls) {   
  300.                 var control = measureControls[key];   
  301.                 if(_value == key ) {   
  302.                     control.activate();   
  303.                 } else {   
  304.                     control.deactivate();   
  305.                 }   
  306.             }   
  307.         }   
  308.   
  309.         /*********************拉宽并获取经纬度坐标系*********************************/   
  310.         function boxExtend(){   
  311.             var controlBox = new OpenLayers.Control();   
  312.               OpenLayers.Util.extend(controlBox, {   
  313.                     draw: function () {   
  314.                         this.box = new OpenLayers.Handler.Box( controlBox,   
  315.                             {"done": this.notice},{ "persist": true},   
  316.                             {keyMask:OpenLayers.Handler.MOD_SHIFT });   
  317.                         this.box.activate();   
  318.                     },   
  319.   
  320.                     notice: function (bounds) {        
  321.                         var ll = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.left, bounds.bottom));    
  322.                         var ur = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.right, bounds.top));    
  323.                         alert(ll.lon.toFixed(4) + ", " +    
  324.                               ll.lat.toFixed(4) + ", " +    
  325.                               ur.lon.toFixed(4) + ", " +    
  326.                               ur.lat.toFixed(4));   
  327.                     }   
  328.                 });   
  329.             map.addControl(controlBox);   
  330.         }   
  331.         var markers,marker;   
  332.         var markArr=new Array();   
  333.         function addMarker(){   
  334.              var url = 'http://www.openlayers.org/dev/img/marker.png';   
  335.                 var sz = new OpenLayers.Size(20, 20);  //尺寸大小   
  336.                 var calculateOffset = function(size) {   
  337.                                     return new OpenLayers.Pixel(-(size.w/2), -size.h);   
  338.                                  };   
  339.                 var icon = new OpenLayers.Icon(url, sz, null, calculateOffset);   
  340.                    
  341.                 marker = new OpenLayers.Marker(new OpenLayers.LonLat(113.34851,33.22630), icon);   
  342.                 markers.addMarker(marker);   
  343.   
  344.                // marker = new OpenLayers.Marker(madrid, icon.clone());   
  345.                // markers.addMarker(marker);               
  346.         }   
  347.          function removeMarker() {   
  348.                 markers.removeMarker(marker);   
  349.          }   
  350.          /*******************多边形获取经纬度坐标系*************************/   
  351.          function test(){   
  352.             var getpolygonxy = new OpenLayers.Control();   
  353.             OpenLayers.Util.extend(getpolygonxy, {   
  354.                 draw: function() {   
  355.                     this.polygonnew OpenLayers.Handler.Polygon(getpolygonxy ,   
  356.                             { "done": this.notice },{ "persist": true},   
  357.                             { keyMask: OpenLayers.Handler.MOD_SHIFT });   
  358.                     this.polygon.activate();   
  359.                 },   
  360.                 notice: function(bounds) {   
  361.                     alert(bounds);//坐标信息                       
  362.                 }   
  363.             });   
  364.             map.addControl(getpolygonxy);   
  365.          }   
  366.        
  367.         </script>  
  368.     </head>  
  369.     <body onload="init()">  
  370.         <div id="toolbar" style="display:">              
  371.             <input type="button" value="放大" onclick="zoomIn()"/>  
  372.             <input type="button" value="缩小" onclick="zoomOut()"/>  
  373.             <input type="button" value="获取地图大小" onclick="getSize()"/>  
  374.             <input type="button" value="平移" onclick="toggleControl('none')"/>  
  375.             <input type="button" value="线路测量" onclick="toggleControl('line')"/>  
  376.             <input type="button" value="测量面积" onclick="toggleControl('polygon')"/>  
  377.             <input type="button" value="shift拉框" onclick="boxExtend()"/>  
  378.             <input type="button" value="显示标注" onclick="addMarker()"/>  
  379.             <input type="button" value="移除标注" onclick="removeMarker()"/>  
  380.             <input type="button" value="画多边形获取经纬度坐标" onclick="test()"/>  
  381.         </div>  
  382.         <div id="map">  
  383.               
  384.         </div>  
  385.         <div id="wrapper">  
  386.             <div id="location">经纬度坐标</div>  
  387.             <div id="scale">  
  388.             </div>  
  389.             <div id="output">  
  390.             </div>  
  391.         </div>  
  392.         <div id="xystr"></div>  
  393.         <div id="nodelist">  
  394.             <em>Click on the map to get feature info</em>  
  395.         </div>  
  396.     </body>  
  397. </html>  
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>OpenLayers map preview</title>
        <!-- Import OL CSS, auto import does not work with our minified OL.js build -->
        <link rel="stylesheet" type="text/css" href="../theme/default/style.css"/>
		 <link rel="stylesheet" href="../theme/default/google.css" type="text/css">
        <!-- Basic CSS definitions -->
        <style type="text/css">
            /* General settings */
            body {
                font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
                font-size: small;
            }
            /* Toolbar styles */
            #toolbar {
                position: relative;
                padding-bottom: 0.5em; 
               
            }
            
            /* The map and the location bar */
            #map {
                clear: both;
                position: relative;
                width: 698px;
                height: 330px;
                border: 1px solid black;
            }
            
            #wrapper {
                width: 698px;
            }
            
            #location {
                float: right;
            }

            /* Styles used by the default GetFeatureInfo output, added to make IE happy */
            table.featureInfo, table.featureInfo td, table.featureInfo th {
                border: 1px solid #ddd;
                border-collapse: collapse;
                margin: 0;
                padding: 0;
                font-size: 90%;
                padding: .2em .1em;
            }
            
            table.featureInfo th {
                padding: .2em .2em;
                text-transform: uppercase;
                font-weight: bold;
                background: #eee;
            }
            
            table.featureInfo td {
                background: #fff;
            }
            
            table.featureInfo tr.odd td {
                background: #eee;
            }
            
            table.featureInfo caption {
                text-align: left;
                font-size: 100%;
                font-weight: bold;
                text-transform: uppercase;
                padding: .2em .2em;
            }
        </style>
        <!-- Import OpenLayers, reduced, wms read only version -->
       <script src="../lib/OpenLayers.js" ></script>
	    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
        <script defer="defer" type="text/javascript">
            var map, measureControls;
            var untiled;
            var tiled;
			
            function init(){
                format = 'image/png';
				var bounds = new OpenLayers.Bounds(  //地图区域范围
                    74.137, 6.319,
                    135.086, 53.558
                );
                var options = {
                    controls: [],
					 maxExtent: bounds,
                    maxResolution: 0.23808203125,
					projection: "EPSG:4610",
					numZoomLevels: 7, 
					units: 'degrees'
                };
                map = new OpenLayers.Map('map', options);
        
               /**********************加载图层 开始*******************************/
              /*   tiled = new OpenLayers.Layer.WMS(  //图层组
                    "基础图层", "http://localhost:8080/geoserver/wms",
                    {
                        height: '330',
                        width: '698',
                        layers: 'sf',
                        styles: '',
                        srs: 'EPSG:4326',
                        format: format,
                        tiled: 'true',
                        tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
                    },
                    {
                        buffer: 0,
                        displayOutsideMaxExtent: true
                    } 
                );*/
				
				var streams = new OpenLayers.Layer.WMS(    //图层组
                    "中国", "http://localhost:8080/geoserver/wms",
                    {
                       height: '330',
                        width: '698',
                        layers: 'china',
                        styles: '',
                        srs: 'EPSG:4610',
                        format: format,
                        tiled: 'true',
                        tilesOrigin : map.maxExtent.left + ',' + map.maxExtent.bottom
                    },
                    {
						buffer: 0,
						displayOutsideMaxExtent: true

					} 
                );
            
				untiled = new OpenLayers.Layer.WMS(  //单独图层
                    "省会", "http://127.0.0.1:8080/geoserver/wms",
                    {
                        height: '330',
                        width: '698',
                        layers: 'china:provice',
                        styles: '',
                        srs: 'EPSG:4610',
						transparent: "true",
                        format: format
                    },
                    {singleTile: true, ratio: 1} 
                );
				 untiled.setVisibility(false); //设置为不显示
				//var gmap = new OpenLayers.Layer.Google("Google Streets", {visibility: false});    
				/* var dm_wms = new OpenLayers.Layer.WMS( "点图层",
                "http://127.0.0.1:8080/geoserver/wms",
                {layers: "sf:bugsites,sf:archsites",
                 transparent: "true", format: "image/png"});*/

               map.addLayers([streams,untiled]);
			  /********************END 加载图层*********************************/

               /************************加载一般的基础控件********************************/   
                map.addControl(new OpenLayers.Control.PanZoomBar({  //添加平移缩放工具条
                    position: new OpenLayers.Pixel(2, 15)
                }));
                map.addControl(new OpenLayers.Control.Navigation());  //双击放大,平移
                map.addControl(new OpenLayers.Control.Scale($('scale')));  //获取地图比例尺
                map.addControl(new OpenLayers.Control.MousePosition({element: $('location')}));  //获取鼠标的经纬度
				map.setCenter(new OpenLayers.LonLat(100.254, 35.25), 1);  //添加平移缩放工具条
				map.addControl(new OpenLayers.Control.OverviewMap());  //添加鹰眼图
				map.addControl(new OpenLayers.Control.LayerSwitcher({'ascending':false}));  //图层切换工具			
                map.addControl(new OpenLayers.Control.Permalink('xxxx'));  //添加永久链接
				//map.addControl(new OpenLayers.Control.MouseToolbar());

				//map.zoomToMaxExtent();
				var zb=new OpenLayers.Control.ZoomBox({out:true});
				var panel = new OpenLayers.Control.Panel({defaultControl: zb});
				map.addControl(panel);
			 /************END************加载一般的基础控件********************************/   

               /***********************鼠标点击,获取图层数据*******************************/   
                map.events.register('click', map, function (e) {
                    document.getElementById('nodelist').innerHTML = "Loading... please wait...";
                    var params = {
                        REQUEST: "GetFeatureInfo",
                        EXCEPTIONS: "application/vnd.ogc.se_xml",
                        BBOX: map.getExtent().toBBOX(),
                        X: e.xy.x,
                        Y: e.xy.y,
                        INFO_FORMAT: 'text/html',
                        QUERY_LAYERS: map.layers[0].params.LAYERS,
                        FEATURE_COUNT: 50,
                        Layers: 'ok',
                        Styles: '',
                        Srs: 'EPSG:4610',
                        WIDTH: map.size.w,
                        HEIGHT: map.size.h,
                        format: format};
                    OpenLayers.loadURL("http://localhost:8080/geoserver/wms", params, this, setHTML, setHTML);
                    OpenLayers.Event.stop(e);
                });
			  /**************END*********鼠标点击,获取图层数据*******************************/   

			/**********************************点、线、面测量开始**********************************************/
			 var sketchSymbolizers = {
                "Point": {
                    pointRadius: 4,	
                    graphicName: "square",
                    fillColor: "white",
                    fillOpacity: 1,
                    strokeWidth: 1,
                    strokeOpacity: 1,
                    strokeColor: "#333333"
                },
                "Line": {
                    strokeWidth: 3,
                    strokeOpacity: 1,
                    strokeColor: "#666666",
                    strokeDashstyle: "dash"
                },
                "Polygon": {
                    strokeWidth: 2,
                    strokeOpacity: 1,
                    strokeColor: "#666666",
                    fillColor: "white",
                    fillOpacity: 0.3
                }
            };
            var style = new OpenLayers.Style();
            style.addRules([
                new OpenLayers.Rule({symbolizer: sketchSymbolizers})
            ]);
			 var styleMap = new OpenLayers.StyleMap({"default": style});
			 measureControls = {
                line: new OpenLayers.Control.Measure(
                    OpenLayers.Handler.Path, {
                        persist: true,
                        handlerOptions: {
                            layerOptions: {styleMap: styleMap}
                        }
                    }
                ),
                polygon: new OpenLayers.Control.Measure(
                    OpenLayers.Handler.Polygon, {
                        persist: true,
                        handlerOptions: {
                            layerOptions: {styleMap: styleMap}
                        }
                    }
                )
            };
			 var control;
            for(var key in measureControls) {
                control = measureControls[key];
                control.events.on({
                    "measure": handleMeasurements,
                    "measurepartial": handleMeasurements
                });
                map.addControl(control);
            }
			/***************************END************点,线、面积测量*****************************************/

			  //添加点标注的图层
			  markers = new OpenLayers.Layer.Markers("markers");
              map.addLayer(markers);  
			  markers.setZIndex(200);

       }
            
		//获取面积的结果赋值
		  function handleMeasurements(event) {
            var geometry = event.geometry;
            var units = event.units;
            var order = event.order;
            var measure = event.measure;
            var element = document.getElementById('output');
            var out = "";
            if(order == 1) {
                out += "面积为: " + measure.toFixed(3) + " " + units;
            } else {
                out += "面积为: " + measure.toFixed(3) + " " + units + "<sup>2</" + "sup>";
            }
            element.innerHTML = out;
        }
		function setHTML(response){
			document.getElementById('nodelist').innerHTML = response.responseText;
		};
		//缩小
		function zoomOut(){
			map.zoomOut();
		}
		//放大
		function zoomIn(){
			map.zoomIn();
		}
		//获取地图数据
		function getSize(){
			alert(map.getSize()+",高度为="+map.getSize().h);
		}
		//切换鼠标事件功能
		function toggleControl(_value) {
			
            for(key in measureControls) {
                var control = measureControls[key];
                if(_value == key ) {
                    control.activate();
                } else {
                    control.deactivate();
                }
            }
        }

		/*********************拉宽并获取经纬度坐标系*********************************/
		function boxExtend(){
			var controlBox = new OpenLayers.Control();
              OpenLayers.Util.extend(controlBox, {
                    draw: function () {
                        this.box = new OpenLayers.Handler.Box( controlBox,
                            {"done": this.notice},{ "persist": true},
                            {keyMask:OpenLayers.Handler.MOD_SHIFT });
                        this.box.activate();
                    },

                    notice: function (bounds) {		
                        var ll = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.left, bounds.bottom)); 
                        var ur = map.getLonLatFromPixel(new OpenLayers.Pixel(bounds.right, bounds.top)); 
                        alert(ll.lon.toFixed(4) + ", " + 
                              ll.lat.toFixed(4) + ", " + 
                              ur.lon.toFixed(4) + ", " + 
                              ur.lat.toFixed(4));
                    }
                });
			map.addControl(controlBox);
		}
		var markers,marker;
		var markArr=new Array();
		function addMarker(){
			 var url = 'http://www.openlayers.org/dev/img/marker.png';
                var sz = new OpenLayers.Size(20, 20);  //尺寸大小
                var calculateOffset = function(size) {
                                    return new OpenLayers.Pixel(-(size.w/2), -size.h);
                                 };
                var icon = new OpenLayers.Icon(url, sz, null, calculateOffset);
				
				marker = new OpenLayers.Marker(new OpenLayers.LonLat(113.34851,33.22630), icon);
                markers.addMarker(marker);

               // marker = new OpenLayers.Marker(madrid, icon.clone());
               // markers.addMarker(marker);			
		}
		 function removeMarker() {
                markers.removeMarker(marker);
         }
		 /*******************多边形获取经纬度坐标系*************************/
		 function test(){
			var getpolygonxy = new OpenLayers.Control();
			OpenLayers.Util.extend(getpolygonxy, {
				draw: function() {
					this.polygon= new OpenLayers.Handler.Polygon(getpolygonxy ,
							{ "done": this.notice },{ "persist": true},
							{ keyMask: OpenLayers.Handler.MOD_SHIFT });
					this.polygon.activate();
				},
				notice: function(bounds) {
					alert(bounds);//坐标信息					
				}
			});
			map.addControl(getpolygonxy);
		 }
	
        </script>
    </head>
    <body οnlοad="init()">
        <div id="toolbar" style="display:">			
			<input type="button" value="放大" οnclick="zoomIn()"/>
			<input type="button" value="缩小" οnclick="zoomOut()"/>
			<input type="button" value="获取地图大小" οnclick="getSize()"/>
			<input type="button" value="平移" οnclick="toggleControl('none')"/>
			<input type="button" value="线路测量" οnclick="toggleControl('line')"/>
			<input type="button" value="测量面积" οnclick="toggleControl('polygon')"/>
			<input type="button" value="shift拉框" οnclick="boxExtend()"/>
			<input type="button" value="显示标注" οnclick="addMarker()"/>
			<input type="button" value="移除标注" οnclick="removeMarker()"/>
			<input type="button" value="画多边形获取经纬度坐标" οnclick="test()"/>
        </div>
        <div id="map">
           
        </div>
        <div id="wrapper">
            <div id="location">经纬度坐标</div>
            <div id="scale">
            </div>
			<div id="output">
			</div>
        </div>
		<div id="xystr"></div>
        <div id="nodelist">
            <em>Click on the map to get feature info</em>
        </div>
    </body>
</html>

 根据经纬度坐标串显示多边形代码如下

 

 

Html代码 复制代码  收藏代码
  1. var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {style:layer_style });   
  2.             var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);   
  3.             layer_style.fillOpacity = 0.2;   
  4.             layer_style.graphicOpacity =0.2;   
  5.   
  6.             // create a polygon feature from a linear ring of points   
  7.             var pointList = [];             
  8.             var point1 = new OpenLayers.Geometry.Point(99.480233398438 ,34.892876953125);   
  9.             var point2 = new OpenLayers.Geometry.Point(106.74173535156, 25.96480078125);   
  10.             var point3 = new OpenLayers.Geometry.Point(116.26501660156, 36.6784921875);   
  11.             var point4 = new OpenLayers.Geometry.Point(109.59871972656 , 41.559173828125);   
  12.             var point5 = new OpenLayers.Geometry.Point(99.480233398438,34.892876953125);   
  13.             pointList.push(point1);   
  14.             pointList.push(point2);   
  15.             pointList.push(point3);   
  16.             pointList.push(point4);   
  17.             pointList.push(point5);   
  18.             pointList.push(pointList[0]);   
  19.             var linearRing = new OpenLayers.Geometry.LinearRing(pointList);   
  20.             var polygonFeature = new OpenLayers.Feature.Vector(   
  21.             new OpenLayers.Geometry.Polygon([linearRing]));   
  22.              map.addLayer(vectorLayer);   
  23.            // map.setCenter(new OpenLayers.LonLat(point.x, point.y), 5);   
  24.             vectorLayer.addFeatures([ polygonFeature]);  
var vectorLayer = new OpenLayers.Layer.Vector("Simple Geometry", {style:layer_style });
			var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
            layer_style.fillOpacity = 0.2;
            layer_style.graphicOpacity =0.2;

            // create a polygon feature from a linear ring of points
            var pointList = [];          
			var point1 = new OpenLayers.Geometry.Point(99.480233398438 ,34.892876953125);
			var point2 = new OpenLayers.Geometry.Point(106.74173535156, 25.96480078125);
			var point3 = new OpenLayers.Geometry.Point(116.26501660156, 36.6784921875);
			var point4 = new OpenLayers.Geometry.Point(109.59871972656 , 41.559173828125);
			var point5 = new OpenLayers.Geometry.Point(99.480233398438,34.892876953125);
			pointList.push(point1);
			pointList.push(point2);
			pointList.push(point3);
			pointList.push(point4);
			pointList.push(point5);
			pointList.push(pointList[0]);
            var linearRing = new OpenLayers.Geometry.LinearRing(pointList);
            var polygonFeature = new OpenLayers.Feature.Vector(
            new OpenLayers.Geometry.Polygon([linearRing]));
			 map.addLayer(vectorLayer);
           // map.setCenter(new OpenLayers.LonLat(point.x, point.y), 5);
            vectorLayer.addFeatures([ polygonFeature]);

 

根据经纬度坐标窜画多边形,线性等可以参考OpenLayers-2.10\examples 下的vector-features.html代码

评论 1 您还未登录,请先 登录 后发表或查看评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

li_xin_an666

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值