OpenLayers3应用

OpenLayers3应用

sf2gis@163.com

2015年6月17日

 

1 使用WEB服务

1.1 显示OpenStreetMap

示例:

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <link rel="stylesheet"href="http://openlayers.org/en/v3.6.0/css/ol.css"type="text/css">

      <style>

           .map2{height:400px;width:100%;}

      </style>

      <scriptsrc="http://openlayers.org/en/v3.6.0/build/ol.js"type="text/javascript"></script>

     

      <title>testOpenLayers</title>

</head>

<body>

      <h2>Head Test OpenLayers</h2>

      <button id="zoom-out">Zoom out</button>

    <button id="zoom-in">Zoomin</button>

      <div id="map2"class="map2">Map</div>

      <script type="text/javascript">

      var attribution = new ol.control.Attribution({

      collapsible:true

      });  

      var tileAttr=new ol.Attribution({

      html: 'All maps © ' + '<ahref="http://www.localhost:8080/">MyTest GeoServer</a>'

    });

           map=new ol.Map

           ({

                 target:'map2',

                 controls: ol.control.defaults({ attribution: false}).extend([attribution]),

                 layers:[

                      new ol.layer.Tile({source:newol.source.OSM()}),//openstreetmap tms

                       newol.layer.Tile({//tiledebug grid

                  source:new ol.source.TileDebug({

                        projection:'EPSG:3857',

                  tileGrid:ol.tilegrid.createXYZ({maxZoom: 22})})}),

                      new ol.layer.Tile({source:newol.source.XYZ({//geoserver local tms

                      attributions:[tileAttr],

                  projection:ol.proj.get('EPSG:3857'),

                  url:'http://localhost:8080/geoserver/gwc/service/tms/1.0.0/testShp%3Astates3857@testTms3857@png/{z}/{x}/{-y}.png'

                      }),

                      opacity: 0.5

                 })],

                 view:new ol.View

                 ({

                      center:ol.proj.transform([-98,40],'EPSG:4326','EPSG:3857'),

                      zoom:3

                 })

           })

          

           document.getElementById('zoom-out').onclick = function() {

             var view =map.getView();

             var zoom =view.getZoom();

             view.setZoom(zoom- 1);

           };

 

           document.getElementById('zoom-in').onclick = function() {

             var view =map.getView();

             var zoom =view.getZoom();

             view.setZoom(zoom+ 1);

           };

 

      </script>

</body>

</html>

1.2 显示MapQuest服务

参考:官网示例http://openlayers.org/en/v3.6.0/doc/quickstart.html。

<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.0 Transitional//EN">

 

<html>

<head>

      <link rel="stylesheet"href="http://openlayers.org/en/v3.6.0/css/ol.css"type="text/css">

      <style>

           .map2{height:400px;width:100%;}

      </style>

      <script src="http://openlayers.org/en/v3.6.0/build/ol.js"type="text/javascript"></script>

     

      <title>testOpenLayers</title>

</head>

<body>

      <h2>Head Test OpenLayers</h2>

      <div id="map2"class="map2">Map</div>

      <script type="text/javascript">

           map=new ol.Map

           ({

                 target:'map2',

                 layers:[new ol.layer.Tile({source:newol.source.MapQuest({layer:'osm'})})],

                 view:new ol.View

                 ({

                      center:ol.proj.transform([-116,38],'EPSG:4326','EPSG:3857'),

                      zoom:4

                 })

           })

      </script>

</body>

</html>

1.3 显示WMS

参考:wms-image.html示例。

WMS服务参见:GeoServer.docx

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <link rel="stylesheet"href="http://openlayers.org/en/v3.6.0/css/ol.css"type="text/css">

      <style>

           .map2{height:400px;width:100%;}

      </style>

      <script src="http://openlayers.org/en/v3.6.0/build/ol.js"type="text/javascript"></script>

     

      <title>testOpenLayers</title>

</head>

<body>

      <h2>Head Test OpenLayers</h2>

      <div id="map2"class="map2">Map</div>

      <script type="text/javascript">

           map=new ol.Map

           ({

                 target:'map2',

                 layers:[new ol.layer.Image({source:newol.source.ImageWMS({

                      url:'http://localhost:8080/geoserver/testShp/wms',

                      params: {'LAYERS':'states'},

                  serverType:'geoserver'

                      })

                 })],

                 view:new ol.View

                 ({

                      center:ol.proj.transform([-116,38],'EPSG:4326','EPSG:3857'),

                      zoom:4

                 })

           })

      </script>

</body>

</html>

1.4 显示WMTS?

 

1.5 显示TMS

找到TMS的服务地址,使用level/x/y.format进行替换。

参考:xyz.html示例。

WMS服务参见:GeoServer.docx

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <link rel="stylesheet"href="http://openlayers.org/en/v3.6.0/css/ol.css"type="text/css">

      <style>

           .map2{height:400px;width:100%;}

      </style>

      <scriptsrc="http://openlayers.org/en/v3.6.0/build/ol.js" type="text/javascript"></script>

     

      <title>testOpenLayers</title>

</head>

<body>

      <h2>Head Test OpenLayers</h2>

      <div id="map2"class="map2">Map</div>

      <script type="text/javascript">

           map=new ol.Map

           ({

                 target:'map2',

                 layers:[

                      new ol.layer.Tile({source:newol.source.XYZ({

                  projection:ol.proj.get('EPSG:3857'),

                  url:'http://localhost:8080/geoserver/gwc/service/tms/1.0.0/testShp%3Astates@testTms@png/{z}/{x}/{-y}.png'

                      }),

                      opacity: 0.5

                 })],

                 view:new ol.View

                 ({

                      center:ol.proj.transform([-98,40],'EPSG:4326','EPSG:3857'),

                      zoom:3

                 })

           })

      </script>

</body>

</html>

 

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

1.6 显示调试TMS的瓦片编号

参考:canvas-tile.html

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <link rel="stylesheet"href="http://openlayers.org/en/v3.6.0/css/ol.css"type="text/css">

      <style>

           .map2{height:400px;width:100%;}

      </style>

      <scriptsrc="http://openlayers.org/en/v3.6.0/build/ol.js"type="text/javascript"></script>

     

      <title>testOpenLayers</title>

</head>

<body>

      <h2>Head Test OpenLayers</h2>

      <div id="map2"class="map2">Map</div>

      <script type="text/javascript">

           map=new ol.Map

           ({

                 target:'map2',

                 layers:[

                      new ol.layer.Tile({

                  source:new ol.source.TileDebug({

                        projection:'EPSG:3857',

                  tileGrid:ol.tilegrid.createXYZ({maxZoom: 22})})}),

 

                      new ol.layer.Tile({source:new ol.source.XYZ({

                  projection:ol.proj.get('EPSG:3857'),

                  url:'http://localhost:8080/geoserver/gwc/service/tms/1.0.0/testShp%3Astates@testTms@png/{z}/{x}/{-y}.png'

                      }),

                      opacity: 0.5

                 })],

                 view:new ol.View

                 ({

                      center:ol.proj.transform([-98,40],'EPSG:4326','EPSG:3857'),

                      zoom:3

                 })

           })

      </script>

</body>

</html>

 

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

1.7 显示WFS

目标:请求WFS的矢量元素,并显示在页面。

方法:

1.7.1WFS请求  

1)   在geoserver的web.xml中启用jsonp(参见:..\Net\javascript.docx)(参见:GeoServer.docx)。。

2)   构造WFS的JSONP请求:

格式:wfs地址+服务信息+请求信息+输出信息。

wfs地址:http://服务器IP:PORT/geoserver[/工作空间[/图层名]]/WFS。

服务信息:包括服务类型和版本号,格式:service=WFS&version=1.1.0

请求信息:包括请求功能,请求图层,图层SRS和请求范围bbox。格式:request=GetFeature&typename=testShp:states3857&srsname=EPSG:3857&bbox=xMin,yMin,xMax,yMax,SRSName。

输出信息:包括输出格式(jsonp必须使用text/javascript)和其它参数(一般是回调函数的名字)。格式:outputFormat=text/javascript&format_options=callback:loadFeatures。

示例:

http://localhost:8080/geoserver/testShp/states3857/wfs?service=WFS&version=1.1.0&request=GetFeature&typename=testShp:states3857&srsname=EPSG:3857&bbox=-88,40,-80,42,EPSG:4326&outputFormat=text/javascript&format_options=callback:loadFeatures

3)   测试:在浏览器测试WFS的请求,得到相应的输出。

结果:调用以结果Feature的GeoJson格式为参数的回调函数。

在服务器端:服务器将请求进行拆分并根据输出要求返回数据。

1.7.2OpenLayers的显示功能

1)   在ol.source.Vector的loader函数中组织WFS请求,返回结果GeoJSON后调用回调函数。

loader:function(extent,resolution,projection)。

在此函数中组织URL(包含回调函数),然后请求WFS。

2)   回调函数解析返回值并将元素添加到当前数据源中显示。

1.7.3示例

<!DOCTYPE html>

<html>

<head>

<title>WFS example</title>

<scriptsrc="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css"type="text/css">

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js"></script>

 

</head>

<body>

<divclass="container-fluid">

 

<div class="row-fluid">

  <div class="span12">

    <div id="map"class="map"></div>

  </div>

</div>

 

</div>

<script>

// format used to parse WFSGetFeature responses

var geojsonFormat = newol.format.GeoJSON();

 

var vectorSource = newol.source.Vector({

  loader: function(extent, resolution,projection) {

    var url ='http://localhost:8080/geoserver/testShp/wfs?service=WFS&' +

       'version=1.1.0&request=GetFeature&typename=testShp:states3857&'+

        'outputFormat=text/javascript&format_options=callback:loadFeatures'+

        '&srsname=EPSG:3857&bbox=' +extent.join(',') + ',EPSG:3857';

    // use jsonp: false to prevent jQuery fromadding the "callback"

    // parameter to the URL

    $.ajax({url: url, dataType: 'jsonp', jsonp:false});

  },

  strategy:ol.loadingstrategy.tile(ol.tilegrid.createXYZ({

    maxZoom: 19

  }))

});

 

 

/**

 * JSONP WFS callback function.

 * @param {Object} response The responseobject.

 */

window.loadFeatures =function(response) {

  vectorSource.addFeatures(geojsonFormat.readFeatures(response));

};

 

var vector = newol.layer.Vector({

  source: vectorSource,

  style: new ol.style.Style({

    stroke: new ol.style.Stroke({

      color: 'rgba(0, 0, 255, 1.0)',

      width: 2

    })

  })

});

 

var raster = new ol.layer.Tile({

  source: new ol.source.BingMaps({

    imagerySet: 'Aerial',

    key:'Ak-dzM4wZjSqTlzveKz5u0d4IQ4bRzVI309GxmkgSVr1ewS6iPSrOvOKhA-CJlm3'

  })

});

 

var map = new ol.Map({

  layers: [raster, vector],

  target: 'map',

  view: new ol.View({

    center: [-8908887.277395891,5381918.072437216],

    maxZoom: 19,

    zoom: 4

  })

});

 

</script>

</body>

</html>

1.8 编辑WFS:增删改查?

 

2 地图操作

2.1 默认功能:缩放、旋转、数据源。

默认具有缩放(右上角),旋转(右上角,alt+shift+mouse可以旋转,点击回正),数据源信息功能(右下角,显示数据源的属性链接)。

可以通过ol.control.defaults修改其配置。

2.2 缩放:view缩放级别。

使用view的setZoom()设置缩放级别。

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <link rel="stylesheet"href="http://openlayers.org/en/v3.6.0/css/ol.css"type="text/css">

      <style>

           .map2{height:400px;width:100%;}

      </style>

      <scriptsrc="http://openlayers.org/en/v3.6.0/build/ol.js"type="text/javascript"></script>

     

      <title>testOpenLayers</title>

</head>

<body>

      <h2>Head Test OpenLayers</h2>

      <button id="zoom-out">Zoom out</button>

    <button id="zoom-in">Zoomin</button>

      <div id="map2"class="map2">Map</div>

      <script type="text/javascript">

      var attribution = new ol.control.Attribution({

      collapsible:true

      });  

      var tileAttr=new ol.Attribution({

      html: 'All maps © ' + '<ahref="http://www.localhost:8080/">MyTest GeoServer</a>'

    });

           map=new ol.Map

           ({

                 target:'map2',

                 controls: ol.control.defaults({ attribution: false}).extend([attribution]),

                 layers:[

                      new ol.layer.Tile({

                  source:new ol.source.TileDebug({

                        projection:'EPSG:3857',

                  tileGrid:ol.tilegrid.createXYZ({maxZoom: 22})})}),

                      new ol.layer.Tile({source:new ol.source.XYZ({

                      attributions:[tileAttr],

                  projection:ol.proj.get('EPSG:3857'),

                  url:'http://localhost:8080/geoserver/gwc/service/tms/1.0.0/testShp%3Astates@testTms@png/{z}/{x}/{-y}.png'

                      }),

                      opacity: 0.5

                 })],

                 view:new ol.View

                 ({

                      center:ol.proj.transform([-98,40],'EPSG:4326','EPSG:3857'),

                      zoom:3

                 })

           })

          

           document.getElementById('zoom-out').onclick = function() {

             var view =map.getView();

             var zoom =view.getZoom();

            view.setZoom(zoom - 1);

           };

 

           document.getElementById('zoom-in').onclick = function() {

             var view =map.getView();

             var zoom =view.getZoom();

            view.setZoom(zoom + 1);

           };

 

      </script>

</body>

</html>

 

2.3 全图:显示矢量地图的全部范围

获取矢量数据源全部范围,使用view显示此范围。

参考:layer-extent.html

<!DOCTYPE html>

<html>

<head>

<title>WFSexample</title>

<scriptsrc="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<linkrel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css"type="text/css">

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js"></script>

 

</head>

<body>

<divclass="container-fluid">

 

<divclass="row-fluid">

  <div class="span12">

      <buttonid="FullExtent">Zoom to Full Extent</button>

    <div id="map" class="map"></div>

  </div>

</div>

 

</div>

<script>

// format used to parse WFSGetFeature responses

var geojsonFormat = newol.format.GeoJSON();

 

var vectorSource = newol.source.Vector({

  loader: function(extent, resolution,projection) {

    var url = 'http://localhost:8080/geoserver/testShp/wfs?service=WFS&'+

       'version=1.1.0&request=GetFeature&typename=testShp:states3857&'+

       'outputFormat=text/javascript&format_options=callback:loadFeatures'+

        '&srsname=EPSG:3857&bbox=' +extent.join(',') + ',EPSG:3857';

    // use jsonp: false to prevent jQuery fromadding the "callback"

    // parameter to the URL

    $.ajax({url: url, dataType: 'jsonp', jsonp:false});

  },

  strategy:ol.loadingstrategy.tile(ol.tilegrid.createXYZ({

    maxZoom: 19

  }))

});

 

 

/**

 * JSONP WFS callback function.

 * @param {Object} response The responseobject.

 */

window.loadFeatures =function(response) {

 vectorSource.addFeatures(geojsonFormat.readFeatures(response));

};

 

var vector = newol.layer.Vector({

  source: vectorSource,

  style: new ol.style.Style({

    stroke: new ol.style.Stroke({

      color: 'rgba(0, 0, 255, 1.0)',

      width: 2

    })

  })

});

 

var raster = newol.layer.Tile({

  source: new ol.source.OSM()

});

 

var map = new ol.Map({

  layers: [raster, vector],

  target: 'map',

  view: new ol.View({

    center: [-8908887.277395891,5381918.072437216],

    maxZoom: 19,

    zoom: 4

  })

});

 

document.getElementById('FullExtent').onclick= function() {

            var layerVector = map.getLayers().item(1);//get target vector layer

            var fullExtent=layerVector.getSource().getExtent();//get the data sourcefull extent

            map.getView().fitExtent(fullExtent,map.getSize());

             };

 

 

</script>

</body>

</html>

2.4 鹰眼:OverviewMap控件。

参考:overviewmap.html示例。

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <link rel="stylesheet"href="http://openlayers.org/en/v3.6.0/css/ol.css"type="text/css">

      <style>

           .map2{height:400px;width:100%;}

      </style>

      <script src="http://openlayers.org/en/v3.6.0/build/ol.js"type="text/javascript"></script>

     

      <title>testOpenLayers</title>

</head>

<body>

      <h2>Head Test OpenLayers</h2>

      <button id="zoom-out">Zoom out</button>

    <button id="zoom-in">Zoomin</button>

      <div id="map2"class="map2">Map</div>

      <script type="text/javascript">

      var attribution = new ol.control.Attribution({

      collapsible:true

      });  

      var tileAttr=new ol.Attribution({

      html: 'All maps © ' + '<ahref="http://www.localhost:8080/">MyTest GeoServer</a>'

    });

           map=new ol.Map

           ({

                 target:'map2',

                 controls: ol.control.defaults({ attribution: false}).extend([attribution,new ol.control.OverviewMap]),

                 layers:[

                      new ol.layer.Tile({

                  source:new ol.source.TileDebug({

                        projection:'EPSG:3857',

                  tileGrid:ol.tilegrid.createXYZ({maxZoom: 22})})}),

                 /*

                      new ol.layer.Tile({

                  source:new ol.source.OSM()

                  }),*/

                      new ol.layer.Tile({source:new ol.source.XYZ({

                      attributions:[tileAttr],

                  projection:ol.proj.get('EPSG:3857'),

                  url:'http://localhost:8080/geoserver/gwc/service/tms/1.0.0/testShp%3Astates@testTms@png/{z}/{x}/{-y}.png'

                      }),

                      opacity: 0.5

                 })],

                 view:new ol.View

                 ({

                      center:ol.proj.transform([-98,40],'EPSG:4326','EPSG:3857'),

                      zoom:3

                 })

           })

          

           document.getElementById('zoom-out').onclick = function() {

             var view =map.getView();

             var zoom =view.getZoom();

             view.setZoom(zoom- 1);

           };

 

           document.getElementById('zoom-in').onclick = function() {

             var view =map.getView();

             var zoom =view.getZoom();

             view.setZoom(zoom+ 1);

           };

 

      </script>

</body>

</html>

 

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

2.5 绘制:点、线、面等几何类型绘制。

2.5.1向图层中添加几何要素:向ol.source.Vector中添加要素

参考:geojson.html。

1)   添加新图层作为几何要素的图层。

      map.addLayer(gLayer);

2)   向图层的数据源中添加几何要素。

      var gSource= new ol.source.Vector({

      features:(new ol.format.GeoJSON()).readFeatures(gFeatures)

      });

3)   设置图层的样式。

  var styles={

      'Point':[pointStyle],

      'LineString':[lineStyle],

      'Polygon':[polygonStyle]

  };

  varstylesFuntion=function(feature,resolution){

      returnstyles[feature.getGeometry().getType()];

  }; 

 

var gLayer= newol.layer.Vector({

      source:gSource,

      style:stylesFuntion

      });

4)   示例:显示GeoJSON要素。

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <link rel="stylesheet"href="http://openlayers.org/en/v3.6.0/css/ol.css"type="text/css">

      <style>

           .map2{height:400px;width:100%;}

      </style>

      <scriptsrc="http://openlayers.org/en/v3.6.0/build/ol.js"type="text/javascript"></script>

     

      <title>testOpenLayers</title>

</head>

<body>

      <h2>Head Test OpenLayers</h2>

      <button id="zoom-out">Zoom out</button>

    <button id="zoom-in">Zoomin</button>

      <div id="map2"class="map2">Map</div>

     

      <script type="text/javascript">

      var attribution = new ol.control.Attribution({collapsible: true    });  

      var tileAttr=new ol.Attribution({

      html: 'All maps &copy; ' + '<ahref="http://www.localhost:8080/">MyTest GeoServer</a>'

    });

    //map frame

      map=new ol.Map

      ({

           target:'map2',

           controls: ol.control.defaults({ attribution: false}).extend([attribution]),

           layers:[

                 new ol.layer.Tile({source:newol.source.OSM()}),//openstreetmap tms

                 new ol.layer.Tile({//tiledebug grid

                 source:new ol.source.TileDebug({

                 projection:'EPSG:3857',

            tileGrid:ol.tilegrid.createXYZ({maxZoom: 22})})}),

                 new ol.layer.Tile({source:newol.source.XYZ({//geoserver local tms

                 attributions:[tileAttr],

                 projection:ol.proj.get('EPSG:3857'),

                 url:'http://localhost:8080/geoserver/gwc/service/tms/1.0.0/testShp%3Astates3857@testTms3857@png/{z}/{x}/{-y}.png'

                 }),

                 opacity: 0.5

           })],

           view:new ol.View

           ({

                 center:ol.proj.transform([-98,40],'EPSG:4326','EPSG:3857'),

                 zoom:3

           }),

      })

          

  //feature style

  var polygonStyle = new ol.style.Style({

    fill: new ol.style.Fill({

      color: 'rgba(255, 255, 255, 0.2)'

    }),

    stroke: new ol.style.Stroke({

      color: '#ffcc33',

      width: 2

    })

  });

 

  var pointStyle=new ol.style.Style({image:new ol.style.Circle({

            radius:5,

            fill:null,

            stroke:newol.style.Stroke({color:'red',width:4})

            })

      });

     

  var lineStyle=new ol.style.Style({

      stroke:newol.style.Stroke({

            color:'green',

            width:4

      })

  });

  var styles={

      'Point':[pointStyle],

      'LineString':[lineStyle],

      'Polygon':[polygonStyle]

  };

  varstylesFuntion=function(feature,resolution){

      returnstyles[feature.getGeometry().getType()];

  };

 

  //geojson objects

  var gFeatures={

      'type':'FeatureCollection',

      'crs':{

            'type':'name',

            'properties':{'name':'EPSG:3857'}

      },

      'features':[

      {

            'type':'Feature',

            'geometry':{

            'type':'Point',

            'coordinates':ol.proj.transform([-114,38],'EPSG:4326','EPSG:3857')

            }

      },

      {

            'type':'Feature',

            'geometry':{

            'type':'LineString',

            'coordinates':[ol.proj.transform([-114,40],'EPSG:4326','EPSG:3857'),ol.proj.transform([-80,40],'EPSG:4326','EPSG:3857')]

            }

      }]};

 

      //geojson layer source

      var gSource= new ol.source.Vector({

      features:(new ol.format.GeoJSON()).readFeatures(gFeatures)

      });

      //geojson layer

      var gLayer= new ol.layer.Vector({

      source:gSource,

      style:stylesFuntion

      });

 

      map.addLayer(gLayer);

 

      document.getElementById('zoom-out').onclick = function() {

        var view =map.getView();

        var zoom =view.getZoom();

        view.setZoom(zoom - 1);

      };

 

      document.getElementById('zoom-in').onclick = function() {

        var view =map.getView();

        var zoom =view.getZoom();

        view.setZoom(zoom + 1);

      };

      </script>

</body>

</html>

2.5.2 鼠标交互绘制:ol.interactions.Draw

设置绘制的数据源、几何类型、样式等,将其添加到map的交互工具中。

参考:draw-features.html

<!DOCTYPE html>

<metahttp-equiv="Access-Control-Allow-Origin" content="*">

<html>

<head>

<title>WFSexample</title>

<scriptsrc="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css"type="text/css">

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js"></script>

<style>

      .map{height:400px;width:100%;}

</style>

</head>

<body>

<divclass="container-fluid">

 

<divclass="row-fluid">

 <div class="span12">

    <div id="map"class="map"></div>

    <buttonid="point">Point</button>

    <buttonid="line">Line</button>

    <buttonid="polygon">Polygon</button>

 </div>

</div>

 

</div>

<script>

var raster = new ol.layer.Tile({

  source: new ol.source.OSM()

});

 

var rubberStyle= newol.style.Style({

    fill: new ol.style.Fill({

      color: 'rgba(255, 0, 0, 0.2)'

    }),

    stroke: new ol.style.Stroke({

      color: '#ffcc33',

      width: 2

    }),

    image: new ol.style.Circle({

      radius: 7,

      fill: new ol.style.Fill({

        color: '#ffcc33'

      })

      })

});

 

var layerStyle= newol.style.Style({

    fill: new ol.style.Fill({

      color: 'rgba(255, 255, 255, 0.2)'

    }),

    stroke: new ol.style.Stroke({

      color: '#ffcc33',

      width: 2

    }),

    image: new ol.style.Circle({

      radius: 7,

      fill: new ol.style.Fill({

        color: '#ffcc33'

      })

      })

});

 

var rubberLayer=newol.layer.Vector({

      source:new ol.source.Vector({}),

      style:layerStyle

});

 

var map = new ol.Map({

  layers: [raster,rubberLayer],

  target: 'map',

  view: new ol.View({

    center: [-8908887.277395891,5381918.072437216],

    maxZoom: 19,

    zoom: 4

  })

});

 

var drawAction;

$("#point").click(function(){

      map.removeInteraction(drawAction);

      drawAction = new ol.interaction.Draw({

           source:rubberLayer.getSource(),

           type:'Point'

      });

      console.debug("2="+drawAction.getKeys());

      map.addInteraction(drawAction);

});

 

$("#line").click(function(){

      map.removeInteraction(drawAction);

      drawAction = new ol.interaction.Draw({

           source:rubberLayer.getSource(),

           type:'LineString'

      });

      map.addInteraction(drawAction);

});

 

$("#polygon").click(function(){

      map.removeInteraction(drawAction);

      drawAction = new ol.interaction.Draw({

           source:rubberLayer.getSource(),

           type:'Polygon',

           style:rubberStyle

      });

      map.addInteraction(drawAction);

});

 

</script>

</body>

</html>

2.6 点选鼠标坐标:ol.control.MousePosition

通过设置ol.control.MousePosition来设置鼠标位置坐标的显示方式。

<!DOCTYPE html>

<metahttp-equiv="Access-Control-Allow-Origin" content="*">

<html>

<head>

<title>WFSexample</title>

<scriptsrc="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<linkrel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css" type="text/css">

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js"></script>

 

</head>

<body>

<divclass="container-fluid">

 

<divclass="row-fluid">

  <div class="span12">

      <buttonid="FullExtent">Zoom to Full Extent</button>

    <div id="map"class="map"></div>

  </div>

</div>

 

</div>

<script>

 

var raster = newol.layer.Tile({

  source: new ol.source.OSM()

});

 

var map = new ol.Map({

  layers: [raster],

  target: 'map',

  view: new ol.View({

    center: [-8908887.277395891, 5381918.072437216],

    maxZoom: 19,

    zoom: 4

  }),

  controls:ol.control.defaults().extend([newol.control.MousePosition({

      coordinateFormate:ol.coordinate.createStringXY(4),

      projection:'EPSG:4326'

  })])

});

</script>

</body>

</html>

2.7 标签:文本标签和弹出式标签

2.7.1文本标签:ol.style.text指定具体的字段和样式

设置文本显示样式,其中的text属性表示要显示的文本。

在styleFunction中动态设置样式的文本属性。

参考:vector-label.html

<!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.0 Transitional//EN">

 

<html>

<head>

      <link rel="stylesheet"href="http://openlayers.org/en/v3.6.0/css/ol.css" type="text/css">

      <style>

           .map2{height:400px;width:100%;}

      </style>

      <scriptsrc="http://openlayers.org/en/v3.6.0/build/ol.js"type="text/javascript"></script>

     

      <title>testOpenLayers</title>

</head>

<body>

      <h2>Head Test OpenLayers</h2>

      <button id="zoom-out">Zoom out</button>

    <button id="zoom-in">Zoomin</button>

      <div id="map2"class="map2">Map</div>

     

      <script type="text/javascript">

      var attribution = new ol.control.Attribution({collapsible: true    });  

      var tileAttr=new ol.Attribution({

      html: 'All maps &copy; ' + '<ahref="http://www.localhost:8080/">MyTest GeoServer</a>'

    });

    //map frame

      map=new ol.Map

      ({

           target:'map2',

           controls: ol.control.defaults({ attribution: false}).extend([attribution]),

           layers:[

                 new ol.layer.Tile({source:newol.source.OSM()}),//openstreetmap tms

                 new ol.layer.Tile({//tiledebug grid

                 source:new ol.source.TileDebug({

                 projection:'EPSG:3857',

            tileGrid:ol.tilegrid.createXYZ({maxZoom: 22})})}),

                 new ol.layer.Tile({source:new ol.source.XYZ({//geoserverlocal tms

                 attributions:[tileAttr],

                 projection:ol.proj.get('EPSG:3857'),

                 url:'http://localhost:8080/geoserver/gwc/service/tms/1.0.0/testShp%3Astates3857@testTms3857@png/{z}/{x}/{-y}.png'

                 }),

                 opacity: 0.5

           })],

           view:new ol.View

           ({

                 center:ol.proj.transform([-98,40],'EPSG:4326','EPSG:3857'),

                 zoom:3

           }),

      })

          

  //feature style

    var textStyle=new ol.style.Text({

    textAlign: 'Center',

    textBaseline: 'Middle',

    font: 'Arial',

    text: 'Text',

    fill: new ol.style.Fill({color: 'blue'}),

    stroke: new ol.style.Stroke({color: 'red',width: 2}),

    offsetX: 10,

    offsetY: 10,

    rotation: 45

  });

 

  var polygonStyle = new ol.style.Style({

    fill: new ol.style.Fill({

      color: 'rgba(255, 255, 255, 0.2)'

    }),

    stroke: new ol.style.Stroke({

      color: '#ffcc33',

      width: 2

    }),

    text:textStyle

  });

 

  var pointStyle=new ol.style.Style({image:newol.style.Circle({

            radius:5,

            fill:null,

            stroke:newol.style.Stroke({color:'red',width:4})

            }),

       text:textStyle

      });

     

  var lineStyle=new ol.style.Style({

      stroke:newol.style.Stroke({

            color:'green',

            width:4

      }),

      text:textStyle

  });

 

  var styles={

      'Point':[pointStyle],

      'LineString':[lineStyle],

      'Polygon':[polygonStyle],

      'Text':[textStyle]

  };

 

  //create style for every feature

  varstylesFuntion=function(feature,resolution){

      varstyle0 = styles[feature.getGeometry().getType()][0];//get the first style

      varname=feature.get('name');//get the feature property to label

      style0.getText().setText(name);//setlabel text

      return[style0];

  };

 

  //geojson objects

  var gFeatures={

      'type':'FeatureCollection',

      'crs':{

            'type':'name',

            'properties':{'name':'EPSG:3857'}

      },

      'features':[

      {

            'type':'Feature',

            'geometry':{

            'type':'Point',

            'coordinates':ol.proj.transform([-114,38],'EPSG:4326','EPSG:3857')

            },

            "properties":{ "name": "Saguenay" }

      },

      {

            'type':'Feature',

            'geometry':{

            'type':'LineString',

            'coordinates':[ol.proj.transform([-114,40],'EPSG:4326','EPSG:3857'),ol.proj.transform([-80,40],'EPSG:4326','EPSG:3857')]

            },

            "properties":{ "name": "My High Way"}

      }]};

 

      //geojson layer source

      var gSource= new ol.source.Vector({

      features:(new ol.format.GeoJSON()).readFeatures(gFeatures)

      });

      //geojson layer

      var gLayer= new ol.layer.Vector({

      source:gSource,

      style:stylesFuntion

      });

 

      map.addLayer(gLayer);

 

      document.getElementById('zoom-out').onclick = function() {

        var view =map.getView();

        var zoom =view.getZoom();

        view.setZoom(zoom - 1);

      };

 

      document.getElementById('zoom-in').onclick = function() {

        var view =map.getView();

        var zoom =view.getZoom();

        view.setZoom(zoom + 1);

      };

      </script>

</body>

</html>

2.7.2 弹出式标签:ol.Overlay

设置Overlay的样式,构造Overlay对象并将其添加到map中。

在点击map时显示Overlay。在overlay上设置关闭功能。

参考:popup.html。

<!DOCTYPE html>

<metahttp-equiv="Access-Control-Allow-Origin" content="*">

<html>

<head>

<title>WFSexample</title>

<scriptsrc="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css"type="text/css">

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js"></script>

<style>

      .map{height:400px;width:100%;}

      .popup

      {

           position: absolute;

           background-color: white;

           -webkit-filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));

           filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));

           padding: 15px;

           border-radius: 10px;

           border: 1px solid #cccccc;

           bottom: 12px;

           left: -50px;

      }

      .popup:after, .popup:before

      {

           top: 100%;

           border: solid transparent;

           content: " ";

           height: 0;

           width: 0;

           position: absolute;

           pointer-events: none;

      }

      .popup:after

      {

           border-top-color: white;

           border-width: 10px;

           left: 48px;

           margin-left: -10px;

      }

      .popup:before

      {

           border-top-color: #cccccc;

           border-width: 11px;

           left: 48px;

           margin-left: -11px;

      }

      .popup-closer {

           text-decoration: none;

           position: absolute;

           top: 2px;

           right: 8px;

      }

      .popup-closer:after {

           content: "x";

      }

</style>

</head>

<body>

<divclass="container-fluid">

 

<divclass="row-fluid">

  <div class="span12">

    <div id="map"class="map"></div>

      <divid="popup" class="popup">

            <ahref="#" id="popup-closer" class="popup-closer"content="X"></a>

            <divid="popup-content" class="popup-content"></div>

      </div>

 </div>

</div>

 

</div>

<script>

varpopupContainer=$('#popup')[0];

varpopupContent=$('#popup-content')[0];

varpopupCloser=$('#popup-closer')[0];

 

varpopupOverlay=new ol.Overlay({

      element:popupContainer,

      autopan:true,

      autopanAnimation:{duration:250}

});

 

var raster = newol.layer.Tile({

  source: new ol.source.OSM()

});

 

var map = new ol.Map({

  layers: [raster],

  target: 'map',

  view: new ol.View({

    center: [-8908887.277395891,5381918.072437216],

    maxZoom: 19,

    zoom: 4

  }),

  overlays:[popupOverlay]

});

 

map.on('singleclick',function(evt)

{

      var coor3857=evt.coordinate;

      varcoor4326=ol.proj.transform(coor3857,'EPSG:3857','EPSG:4326');

popupContent.innerHTML='<p>HDMS='+ol.coordinate.toStringHDMS(coor4326)+'-XY4326='+ol.coordinate.toStringXY(coor4326,4)+'-XY3857='+ol.coordinate.toStringXY(coor3857)+'</p>';

      popupOverlay.setPosition(evt.coordinate,4);

});

 

popupCloser.onclick=function(){

      popupOverlay.setPosition(undefined);

      popupCloser.blur();

      return false;

};

 

</script>

</body>

</html>

2.8 旋转:ol.View.setRotate()。

使用视图的旋转度。

注意:以弧度为单位。

参考:rotation.html

<!DOCTYPE html>

<metahttp-equiv="Access-Control-Allow-Origin" content="*">

<html>

<head>

<title>WFSexample</title>

<scriptsrc="https://code.jquery.com/jquery-1.11.2.min.js"></script>

<linkrel="stylesheet"href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>

<linkrel="stylesheet"href="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.css"type="text/css">

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/ol3/3.6.0/ol.js"></script>

<style>

      .map{height:400px;width:100%;}

</style>

</head>

<body>

<divclass="container-fluid">

 

<divclass="row-fluid">

  <div class="span12">

    <div id="map"class="map"></div>

 </div>

</div>

 

</div>

<script>

var raster = newol.layer.Tile({

  source: new ol.source.OSM()

});

 

var map = new ol.Map({

  layers: [raster],

  target: 'map',

  view: new ol.View({

    center: [-8908887.277395891,5381918.072437216],

    maxZoom: 19,

    zoom: 4

  })

});

 

map.on('singleclick',function(evt)

{

      view=map.getView();

      console.debug('rotation='+view.getRotation());

      view.setRotation(view.getRotation()+Math.PI/4);

});

 

 

</script>

</body>

</html>

2.9 测量:测量距离和面积

目标:通过在线绘制测量图形,得到图形的距离和面积。

方法:使用ol.Overlay作为信息提示,使用ol.interactoin.Draw绘制测量图形。

在地图的pointermove事件处理中添加实时信息。在Draw的开始结束事件中加入相关的Overlay。

计算图形的距离和面积来设置Overlay的内容。

参见:弹出式标签:ol.Overlay,鼠标交互绘制:ol.interactions.Draw

2.9.1测距:投影后的图形直接计算长度getLength(),球体使用半正矢公式haversineDistance()。

2.9.2测面积:投影后的图形直接计算面积getArea(),球体使用球体公式geodeticArea()。

2.9.3示例:同时测量投影和球体的长度和面积。

对比下图可见结果正确。

 

示例:

<!DOCTYPE html>

<metahttp-equiv="Access-Control-Allow-Origin" content="*">

<html>

<head>

<title>WFSexample</title>

<script src="D:/Data/test/openlayers/jquery-1.11.1.min.js"></script>

<linkrel="stylesheet"href="D:/ProgramData/OpenLayers_SDK_v3.6.0/apidoc/styles/bootstrap.min.css">

<scriptsrc="D:/ProgramData/OpenLayers_SDK_v3.6.0/apidoc/scripts/bootstrap.min.js"></script>

<linkrel="stylesheet"href="D:/ProgramData/OpenLayers_SDK_v3.6.0/css/ol.css"type="text/css">

<scriptsrc="D:/ProgramData/OpenLayers_SDK_v3.6.0/build/ol.js"></script>

<style>

      .map{height:400px;width:100%;}

      .tooltip {/*common tip*/

        position: relative;

        background: rgba(0, 0,0, 0.5);

        border-radius: 4px;

        color: white;

        padding: 4px 8px;

        opacity: 0.7;

        white-space: nowrap;

      }

      .tooltip-measure {/*measure with mouse tip*/

        opacity: 1;

        font-weight: bold;

      }

      .tooltip-static {/*measure result tip*/

        background-color:#ffcc33;

        color: black;

        border: 1px solidwhite;

      }

      .tooltip-measure:before,

      .tooltip-static:before {

        border-top: 6px solidrgba(0, 0, 0, 0.5);

        border-right: 6px solidtransparent;

        border-left: 6px solidtransparent;

        content: "";

        position: absolute;

        bottom: -6px;

        margin-left: -7px;

        left: 50%;

      }

      .tooltip-static:before {

        border-top-color:#ffcc33;

      }

</style>

</head>

<body>

<divclass="container-fluid">

    <div id="map"class="map"></div>

    <buttonid="point">Point</button>

    <buttonid="line">Line</button>

    <buttonid="polygon">Polygon</button>

      <div id="helptip" class="tooltip">

           <div id="helptip-content"></div>

      </div>

      <div id="tooltip-measure"class="tooltip-measure"> </div>

</div>

<script>

$(document).ready(function(){

/***********************************/

//map frame

//base layer

var raster = newol.layer.Tile({

  source: new ol.source.OSM()

});

//drawing interaction style

var drawingStyle= newol.style.Style({

    fill: new ol.style.Fill({

      color: 'rgba(255, 0, 0, 0.2)'

    }),

    stroke: new ol.style.Stroke({

      color: '#00ff00',

      width: 2

    }),

    image: new ol.style.Circle({

      radius: 7,

      fill: new ol.style.Fill({

        color: '#ffcc33'

      })

      })

});

//drawed feature style

var layerStyle= newol.style.Style({

    fill: new ol.style.Fill({

      color: 'rgba(255, 255, 255, 0.2)'

    }),

    stroke: new ol.style.Stroke({

      color: '#ff0000',

      width: 2

    }),

    image: new ol.style.Circle({

      radius: 7,

      fill: new ol.style.Fill({

        color: '#ffcc33'

      })

      })

});

//layer for drawed feature

var rubberLayer=newol.layer.Vector({

      source:new ol.source.Vector({}),

      style:layerStyle

});

 

var map = new ol.Map({

  layers: [raster,rubberLayer],

  target: 'map',

  view: new ol.View({

    center: [-8908887.277395891,5381918.072437216],

    maxZoom: 19,

    zoom: 4

  })

});

 

/***********************************/

//measure help tooltip

var helptip=$("#helptip")[0];

varhelptipContent=$('#helptip-content')[0];

var helpOverlay=newol.Overlay({

      element:helptip,

      autoPan:false,

      autoPanAnimation:{duration:250},

      offset:[7,0]

});

map.addOverlay(helpOverlay);

 

//measure tooltip with mouse

var measuretooltip=$("#tooltip-measure")[0];

var measuretooltipOverlay=newol.Overlay({

      element:measuretooltip,

      autoPan:false,

      autoPanAnimation:{duration:250},

      offset:[0,-10],

      positioning:'bottom-center'

});

map.addOverlay(measuretooltipOverlay);

 

//measure result tooltip

varmeasureOverlay=null;//move with mouse

functioncreateResultOverlay(tip,content,result){

      var resulttip=document.createElement('div');

      resulttip.className="tooltip-measure";

      var resultOverlay=new ol.Overlay({

           element:resulttip,

           autoPan:false,

           autoPanAnimation:{duration:250},

           offset:[0,-15],

           positioning:'bottom-center'

      });

      map.addOverlay(resultOverlay);

      resulttip.innerHTML=result;

      return resultOverlay;

};

functiondisplayMeasureOverlay(overlay){

      console.debug("overlay="+overlay);

      console.debug("arguments="+arguments[0]);

      var geom=drawingFeatrue.getGeometry();

      var pos=geom.getLastCoordinate();

      var result;

      if(geom instanceof ol.geom.LineString){

           console.debug("geom=LineString");

           result=new Number(geom.getLength()/1000);

           result=result.toFixed(2);

           result='<p>result:'+result+' km</p>';

      }

      else if(geom instanceof ol.geom.Polygon){

           console.debug("geom=Polygon");

           result=new Number(geom.getArea()/1000000);

           result=result.toFixed(2);

           result='<p>result:'+result+' km<sup>2</sup></p>';

      }

      overlay.getElement().innerHTML=result;

      overlay.setPosition(pos);

};

 

/***********************************/

//draw measure geometry

var drawingFeatrue=null;

var drawAction;

functionfuncDrawAction(geoType){

      console.debug("draw "+geoType+" Action.");

      map.removeInteraction(drawAction);

      drawAction = new ol.interaction.Draw({

           source:rubberLayer.getSource(),

           type:geoType,

           style:drawingStyle

      });

      //drawing handler

      drawAction.on("drawstart",function(evt){

           drawingFeatrue=evt.feature;

           measrueOverlay=createResultOverlay('resulttip','resulttip-content',"<p>result:0</p>");

      });

      drawAction.on("drawend",function(evt){

           displayMeasureOverlay(measrueOverlay);

           measrueOverlay.getElement().className="tooltip-static";

           drawingFeatrue=null;

           measrueOverlay=null;

           measuretooltipOverlay.setPosition(undefined);

      });

 

      map.addInteraction(drawAction);

};

 

funcDrawAction("LineString");//defaultis linestring

$("#point").click(function(evt){

      funcDrawAction("Point");

});

$("#line").click(function(evt){

      funcDrawAction("LineString");

});

$("#polygon").click(function(evt){

      funcDrawAction("Polygon");

});

 

/***********************************/

//pointermove handler

map.on("pointermove",function(evt){

      var pos=evt.coordinate;

      //console.debug(ol.proj.transform(pos,"EPSG:3857","EPSG:4326"));

      helptipContent.innerHTML="<p>clickto measure</p>";

      if(drawingFeatrue){

           helptipContent.innerHTML="<p>clickto finish</p>";

           displayMeasureOverlay(measuretooltipOverlay);

      }

      helpOverlay.setPosition(pos);

});

 

//ready end

});

</script>

</body>

</html>

 

2.10 查询:地理查询、属性查询

2.10.1地理查询:?????

2.10.2属性查询:?????

3 业务系统

3.1 SSH业务系统:前后台交互

学生位置查询系统:

需求:

 

技术:前台由OpenLayers显示学生位置和信息。后台由SSH构建学生数据库查询系统,由GeoServer构建学生地理数据库。使用世界地图WMS作为底图,学校矢量地图为Tiled WFS。

 

你可能感兴趣的:(开发,Gis,OpenLayers,openlayers3)