Geotools读取shp文件并在Ol2中展示

概述:

在前面有一篇文章中讲到了GDAL将shp转换为GeoJson的实现,以及ol2、3以及Arcgis for js中GeoJson的加载,今天呢,书接上文,介绍Geotools如何读取shp文件并在ol2中展示。

 

读取shp

  1. <pre code_snippet_id="1732791" snippet_file_name="blog_20160628_1_4602229" name="code" class="java">package com.lzugis.web;  
  2.   
  3. import net.sf.json.JSONArray;  
  4. import org.geotools.data.shapefile.ShapefileDataStore;  
  5. import org.geotools.data.simple.SimpleFeatureCollection;  
  6. import org.geotools.data.simple.SimpleFeatureIterator;  
  7. import org.geotools.data.simple.SimpleFeatureSource;  
  8. import org.opengis.feature.Property;  
  9. import org.opengis.feature.simple.SimpleFeature;  
  10. import org.opengis.feature.type.PropertyType;  
  11.   
  12. import javax.servlet.ServletException;  
  13. import javax.servlet.annotation.WebServlet;  
  14. import javax.servlet.http.HttpServlet;  
  15. import javax.servlet.http.HttpServletRequest;  
  16. import javax.servlet.http.HttpServletResponse;  
  17. import java.io.File;  
  18. import java.io.IOException;  
  19. import java.io.PrintWriter;  
  20. import java.nio.charset.Charset;  
  21. import java.text.ParseException;  
  22. import java.text.SimpleDateFormat;  
  23. import java.util.*;  
  24.   
  25. @WebServlet(description = "read shape", urlPatterns =  {"/shp"})  
  26. public class ReadShape extends HttpServlet {  
  27.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  28.         String layer = request.getParameter("layer");  
  29.         String shpPath = "D:\\data\\china\\"+layer+".shp";  
  30.         System.out.println(shpPath);  
  31.         ShapefileDataStore shpDataStore = null;  
  32.         Calendar startTime = Calendar.getInstance();  
  33.         List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();  
  34.         try{  
  35.             File file = new File (shpPath);  
  36.             shpDataStore = new ShapefileDataStore(file.toURL());  
  37.             //设置字符编码  
  38.             Charset charset = Charset.forName("GBK");  
  39.             shpDataStore.setCharset(charset);  
  40.             String typeName = shpDataStore.getTypeNames()[0];  
  41.             SimpleFeatureSource featureSource = null;  
  42.             featureSource =  shpDataStore.getFeatureSource (typeName);  
  43.             SimpleFeatureCollection result = featureSource.getFeatures();  
  44.             SimpleFeatureIterator itertor = result.features();  
  45.             while (itertor.hasNext())  
  46.             {  
  47.                 Map<String,Object> data  = new HashMap<String, Object>();  
  48.                 SimpleFeature feature = itertor.next();  
  49.                 Collection<Property> p = feature.getProperties();  
  50.                 Iterator<Property> it = p.iterator();  
  51.                 while(it.hasNext()) {  
  52.                     Property pro = it.next();  
  53.                     String field = pro.getName().toString();  
  54.                     String value = pro.getValue().toString();  
  55.                     field = field.equals("the_geom")?"wkt":field;  
  56.                     data.put(field, value);  
  57.                 }  
  58.                 list.add(data);  
  59.             }  
  60.             Calendar endTime = Calendar.getInstance();  
  61.             int day = endTime.get(Calendar.DAY_OF_MONTH) - startTime.get(Calendar.DAY_OF_MONTH);  
  62.             int hour = endTime.get(Calendar.HOUR_OF_DAY) - startTime.get(Calendar.HOUR_OF_DAY);  
  63.             int minute = endTime.get(Calendar.MINUTE) - startTime.get(Calendar.MINUTE);  
  64.             int second = endTime.get(Calendar.SECOND) - startTime.get(Calendar.SECOND);  
  65.             itertor.close();  
  66.             System.out.println("共写入" + list.size() + "条数据,耗时" + day + "天" + hour + "时" + minute + "分" + second + "秒");  
  67.             response.setContentType("text/html;charset=utf-8");  
  68.             PrintWriter out = response.getWriter();  
  69.             JSONArray jsonarray = JSONArray.fromObject(list);  
  70.             out.println(jsonarray);  
  71.             out.flush();  
  72.             out.close();  
  73.         }  
  74.         catch(Exception e){  
  75.             System.out.println(e.getMessage());  
  76.         }  
  77.     }  
  78.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  79.         this.doPost(request,response);  
  80.     }  
  81. }</pre>  

返回的数据如下:

 

展示数据

  1. <pre code_snippet_id="1732791" snippet_file_name="blog_20160628_2_4744716" name="code" class="html"><!DOCTYPE html>  
  2. <html>  
  3. <head lang="en">  
  4.     <meta charset="UTF-8">  
  5.     <title>openlayers map</title>  
  6.     <link rel="stylesheet" type="text/css" href="http://dev.openlayers.org/theme/default/style.css"/>  
  7.     <style>  
  8.         html, body{  
  9.             padding:0;  
  10.             margin:0;  
  11.             height:100%;  
  12.             width:100%;  
  13.             overflow: hidden;  
  14.             font-size: 12px;  
  15.         }  
  16.         #map1{  
  17.             width: 100%;  
  18.             height: 100%;  
  19.             float: left;  
  20.             border-right: 1px solid #000000;  
  21.         }  
  22.         .tool{  
  23.             position: absolute;  
  24.             top:10pt;  
  25.             right: 10pt;  
  26.             padding: 5px;  
  27.             background: #fff;  
  28.             border: 1px solid #ff5500;  
  29.             z-index: 1000;  
  30.         }  
  31.     </style>  
  32.     <script type="text/javascript" src="http://dev.openlayers.org/OpenLayers.js"></script>  
  33.     <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js"></script>  
  34.     <script>  
  35.         var map1, vectors;  
  36.         OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '2';  
  37.         $(function(){  
  38.             var bounds = new OpenLayers.Bounds(  
  39.                     73.45100463562233, 18.16324718764174,  
  40.                     134.97679764650596, 53.531943152223576  
  41.             );  
  42.             var options = {  
  43.                 controls: [],  
  44.                 maxExtent: bounds,  
  45.                 maxResolution: 0.2403351289487642,  
  46.                 projection: "EPSG:4326",  
  47.                 units: 'degrees'  
  48.             };  
  49.             map1 = new OpenLayers.Map('map1', options);  
  50.   
  51.             map1.addLayer(getWms("province"));  
  52.             map1.addControl(new OpenLayers.Control.Zoom());  
  53.             map1.addControl(new OpenLayers.Control.Navigation());  
  54.             map1.zoomToExtent(bounds);  
  55.             $("#addchart").on("click",function(){  
  56.                 addShpData();  
  57.             });  
  58.         });  
  59.   
  60.         function getWms(layer){  
  61.             return new OpenLayers.Layer.WMS(  
  62.                     "Geoserver layers - Tiled",  
  63.                     "http://localhost:8088/geoserver/lzugis/wms",  
  64.                     {  
  65.                         "LAYERS": layer,  
  66.                         "STYLES": '',  
  67.                         format: 'image/png'  
  68.                     },  
  69.                     {  
  70.                         buffer: 0,  
  71.                         displayOutsideMaxExtent: true,  
  72.                         isBaseLayer: true,  
  73.                         yx : {'EPSG:4326' : true}  
  74.                     }  
  75.             );  
  76.         }  
  77.   
  78.         function addShpData(){  
  79.             var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;  
  80.             renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;  
  81.             vectors = new OpenLayers.Layer.Vector("Vector Layer", {  
  82.                 renderers: renderer  
  83.             });  
  84.             map1.addLayer(vectors);  
  85.             var wktFormat = new OpenLayers.Format.WKT();  
  86.             $.ajax({  
  87.                 type: 'POST',  
  88.                 url: "http://localhost:8081/lzugis/shp" ,  
  89.                 data: {  
  90.                     layer:"capital"  
  91.                 } ,  
  92.                 success: function(data){  
  93.                     data = eval("("+data+")");  
  94.                     console.log(data);  
  95.                     for(var i= 0,dl=data.length;i<dl;i++){  
  96.                         var d = data[i];  
  97.                         var geometry = wktFormat.read(d.wkt);  
  98.                         vectors.addFeatures(geometry);  
  99.                     }  
  100.                 }  
  101.             });  
  102.         }  
  103.     </script>  
  104. </head>  
  105. <body>  
  106. <div class="tool">  
  107.     <button id="addchart">读取shp</button>  
  108. </div>  
  109. <div id="map1"></div>  
  110. </body>  
  111. </html></pre>  

实现后效果如下:

 

附录

本实例相关Geotools jar下载地址:链接:http://pan.baidu.com/s/1o8xTUXW 密码:u601

Geotools12.2 jar下载地址:链接:http://pan.baidu.com/s/1pKDkI19 密码:687y

 

posted @ 2016-07-18 15:01  韩慧兵  阅读(1466)  评论(0编辑  收藏  举报