Wechat: yu389741| Email: gisdqy@163.com

Shop:https://www.giserdqy.com/shop

Openlayers入门


最近在研究GIS相关的内容,因此接触了Openlayers这一开源JS框架。一开始感觉对不怎么会使用和调试JS的我来说,发现这个东西写出来的东西好难好难调试,又不会用JS调试器,只得慢慢的alert()。

         经过一段时间的调试之后发现原来所谓的JS也并没有那么的难,仅仅使用简单的alert()就能完成调试,当然前提是对于Openlayers有一定的认识。个人推荐首先读懂网上的示例程序,一般都有详细的解释说明的,当然官网上也给出了一些例子。

         废话不多说了,直接上代码。

<html>

<head>

   <title>OSM Local Tiles</title>

   <link rel=”stylesheet”href=”http://202.117.77.146/openlayers/theme/default/style.css”type=”text/css” />

                   <linkrel=”stylesheet” href=”css/admin.css”type=”text/css” />

   <script src=”http://202.117.77.146/openlayers/OpenLayers.js”></script>

   <scriptsrc=”http://202.117.77.146/openlayers/OpenStreetMap.js”></script>

         <scriptsrc=”js/ajax.js” type=”text/javascript”></script>

</head>

<!– body.onload is called once the pageis loaded (call the ‘init’ function) –>

<body onload=”init();”>

   <div class = “map” id=”map”>

   </div>

         <divclass=”Menu” id=”pos” onClick=”showFun(1);”>

                   insertlog

   </div>

         <divclass=”Menu” id=”pos”>

                   insertlog

   </div>

   <div class=”locate” id=”mousepos_div”>    

   </div>

         <divclass=”MenuHidden” id=”posMenu”>

                   <divclass=”listMenu”>

                            <label>VNUM:</label>  <inputname=”carNum” id =”carNum” type=”text”value=”陕” size=”15″ />

                   </div>

                   <divclass=”listMenu”>

                            <label>startTime:</label> 

                            <inputname=”startTime” id=”startTime” type=”text”size=”15″/>

                   </div>

                   <divclass=”listMenu”>

                            <label>endTime:</label> 

                            <inputname=”endTime” id=”endTime” type=”text”size=”15″ />

                   </div>

                   <divclass=”listMenu”>

                              <input type=”button”name=”getLine” value=”getLines”onclick=”getLayers(1);”/>

                   </div>

                   <divclass=”listMenu”>

                              <input type=”button”name=”getPoint” value=”getPoints”onclick=”getLayers(2);”/>

                   </div>

                   <inputtype=”hidden” name=”layerOpt” id =”layerOpt”> 

   </div>

         <scripttype=”text/javascript”>

      var lat=34.1789548;

       var lon=108.947654;

       var zoom=8;

 

       var map;

       

       function init() {

           map = new OpenLayers.Map (“map”, {

                controls:[

                     new OpenLayers.Control.Navigation(),

                    newOpenLayers.Control.PanZoomBar(),

                    //newOpenLayers.Control.PanZoom(),

                    newOpenLayers.Control.Permalink(),

                    newOpenLayers.Control.ScaleLine({geodesic: true}),

                    newOpenLayers.Control.Permalink(‘permalink’),

                    newOpenLayers.Control.KeyboardDefaults(),

                    newOpenLayers.Control.NavToolbar(),

                     newOpenLayers.Control.Attribution()],

                maxExtent: newOpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),

                maxResolution: 156543.0339,

                numZoomLevels: 19,

                units: ‘m’,

                projection: newOpenLayers.Projection(“EPSG:900913”),

                displayProjection: newOpenLayers.Projection(“EPSG:4326”)

           } );

           var newLayer = new OpenLayers.Layer.OSM(“Local Tiles”,”http://202.117.77.146/osm_tiles/${z}/${x}/${y}.png”, {numZoomLevels:19, transitionEffect: “resize”});

           map.addLayer(newLayer);

 

           var switcherControl = new OpenLayers.Control.LayerSwitcher();

           map.addControl(switcherControl);

           var vector_layer = new OpenLayers.Layer.Vector(‘Editable Vectors’);

           map.addControl(new OpenLayers.Control.EditingToolbar(vector_layer));

           map.addLayer(vector_layer);

 

           map.addControl(new OpenLayers.Control.Graticule({visible: false}));

           var mousepos = new OpenLayers.Control.MousePosition({div:document.getElementById(‘mousepos_div’)});

           map.addControl(mousepos);

           mousepos.moveTo(new OpenLayers.Pixel(64,0));

           

           map.addControl(new OpenLayers.Control.OverviewMap());

           if( ! map.getCenter() ){

                var lonLat = newOpenLayers.LonLat(lon, lat).transform(newOpenLayers.Projection(“EPSG:4326”), map.getProjectionObject());

                map.setCenter (lonLat, zoom);

           }

       }

                 function showFun(obj){

                            varfunL;

                            if(1== obj){

                                     funL= document.getElementById(‘posMenu’);

                            }

 

                            if( funL.className == ‘MenuHidden’){

                                     funL.className= ‘MenuList’;                                     

                            }

                      else{

                                     funL.className= ‘MenuHidden’;

                      }

                   }

                   functiongetLayers(obj){

                                      var carNum =document.getElementById(“carNum”);

                                     varsTime = document.getElementById(“startTime”);

                                     vareTime = document.getElementById(“endTime”);

                                     document.getElementById(“layerOpt”).value= obj;

 

                                     varurl = “getLayer.mapAJAX?carNo=” + carNum.value

                                                                 +”&timeS=” + sTime.value + “&timeE=” +eTime.value; 

                                     sendRequest(url,processGPSLayer);

                   }

                  

                   functionshowLayers(map,layOpt,geometryStr){

                            //线路样式

                            varstyle_green = {

                                     strokeColor:”#0000FF”,

                                     strokeWidth:3,

                                     strokeDashstyle:”dashdot”,

                                     pointRadius:6,

                                     pointerEvents:”visiblePainted”

                            };

                            //画线图层设置

                            varlayer_style = OpenLayers.Util.extend({}, style_green);

                            layer_style.fillOpacity= 0.2;

                            layer_style.graphicOpacity= 1;

                            //画线图层

                            varvectors = new OpenLayers.Layer.Vector(“Simple Geometry”, {style:layer_style});

                            //vectors.styleMap= setStyleForVectorLayer(“sourceLyr”);

                            map.addLayer(vectors);

                           

                            varawk1 = “POINT(” + geometries[0] + “)”;

                            varlonLat = new OpenLayers.Geometry.fromWKT(awk1).transform(newOpenLayers.Projection(“EPSG:4326”), map.getProjectionObject());

           map.setCenter (lonLat, 12);

           

                            vargeometries = geometryStr.split(“,”);

                           

                            if(1== layOpt){

                                     for(vari = 0; i < geometries.length-1;i++)

                                     {

                                               varawk = “LINESTRING(” + geometries[i] + “,” + geometries[i+1]+ “)”;

                                               varlineFeature = new OpenLayers.Feature.Vector();

                                               lineFeature.geometry= new OpenLayers.Geometry.fromWKT(awk).transform(new OpenLayers.Projection(“EPSG:4326”),map.getProjectionObject());

                                               vectors.addFeatures([lineFeature]);

                                     }

                            }

                   }

                  

                   functionprocessGPSLayer(){

                            if(XMLHttpReq.readyState == 4) {

                                     //判断对象状态      

                              if (XMLHttpReq.status == 200) {

                                                        //信息已经成功返回,开始处理信息                                                                                      

                                            varstr = unescape(XMLHttpReq.responseText);

                                               varresult = str.split(“@@”);  

                                               if(“W”== result[0]){

                                                        alert(“输入数据的格式错误(车牌号和时间)!”);

                                               }

                                               elseif(“N” == result[0]){

                                                        alert(“没有数据!”);

                                               }

                                               else{

                                                        var opt =document.getElementById(“layerOpt”).value;

                                                        showLayers(map,opt,result[0]);

                                               }                

                               }

                               else {

                                                //页面不正常       

                                               window.alert(“您所请求的页面有异常。”); 

                                     } 

                            }

                   }       

 

   </script>

</body>

</html>

 

可以看到,在HTML文件之中,定义了一系列的div,一开始某些css链接和JS链接带有IP地址是因为他们被我放在了另一台机器上。就跟别人给的例子一样,首先包含openlayers内部的样式表文件,其中admin.css为我自己定义的JS文件,在附件中会给出。然后引入openlayer.Js和openstreetmap.Js(可以不包含),已使用其所含有的一些函数。

同时我们可以看到在内嵌的JS代码之中包含有一些函数,各函数功能如下:

函数名

功能

init()

用于初始化要显示地图的一些功能部件,包括缩放面板、图层选择器、鹰眼显示器、经纬度显示、地图矢量编辑器等,同时加载基本图层,本例使用的基本图层为自己在另一台机器上部署的以mod_tile为基础的WMS服务器上的缓存图片(有一个系列专门讲述了部署的方法)。

showFun()

响应界面的函数,主要用于隐藏或展开功能菜单

getLayers(obj)

Ajax请求函数,用于实现向远端服务器请求数据

showLayers(map,layOpt,geometryStr)

   显示图层,会根据layOpt取值的不同而加载不同的图层

processGPSLayer()

    Ajax响应处理函数,由系统调用,主要负责处理反馈的数据

具体每部分代码的具体细节就不再加以赘

转载自:https://blog.csdn.net/txww1/article/details/40215199