国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > web前端 > htmlcss > Geotools读取shp文件并在Ol2中展示

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

来源:程序员人生   发布时间:2016-07-26 13:35:44 阅读次数:5966次

概述:

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


读取shp

package com.lzugis.web;

import net.sf.json.JSONArray;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.opengis.feature.Property;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.type.PropertyType;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@WebServlet(description = "read shape", urlPatterns =  {"/shp"})
public class ReadShape extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String layer = request.getParameter("layer");
        String shpPath = "D:\\data\\china\\"+layer+".shp";
        System.out.println(shpPath);
        ShapefileDataStore shpDataStore = null;
        Calendar startTime = Calendar.getInstance();
        List<Map<String,Object>> list = new ArrayList<Map<String, Object>>();
        try{
            File file = new File (shpPath);
            shpDataStore = new ShapefileDataStore(file.toURL());
            //设置字符编码
            Charset charset = Charset.forName("GBK");
            shpDataStore.setCharset(charset);
            String typeName = shpDataStore.getTypeNames()[0];
            SimpleFeatureSource featureSource = null;
            featureSource =  shpDataStore.getFeatureSource (typeName);
            SimpleFeatureCollection result = featureSource.getFeatures();
            SimpleFeatureIterator itertor = result.features();
            while (itertor.hasNext())
            {
                Map<String,Object> data  = new HashMap<String, Object>();
                SimpleFeature feature = itertor.next();
                Collection<Property> p = feature.getProperties();
                Iterator<Property> it = p.iterator();
                while(it.hasNext()) {
                    Property pro = it.next();
                    String field = pro.getName().toString();
                    String value = pro.getValue().toString();
                    field = field.equals("the_geom")?"wkt":field;
                    data.put(field, value);
                }
                list.add(data);
            }
            Calendar endTime = Calendar.getInstance();
            int day = endTime.get(Calendar.DAY_OF_MONTH) - startTime.get(Calendar.DAY_OF_MONTH);
            int hour = endTime.get(Calendar.HOUR_OF_DAY) - startTime.get(Calendar.HOUR_OF_DAY);
            int minute = endTime.get(Calendar.MINUTE) - startTime.get(Calendar.MINUTE);
            int second = endTime.get(Calendar.SECOND) - startTime.get(Calendar.SECOND);
            itertor.close();
            System.out.println("共写入" + list.size() + "条数据,耗时" + day + "天" + hour + "时" + minute + "分" + second + "秒");
            response.setContentType("text/html;charset=utf⑻");
            PrintWriter out = response.getWriter();
            JSONArray jsonarray = JSONArray.fromObject(list);
            out.println(jsonarray);
            out.flush();
            out.close();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

返回的数据以下:



展现数据

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF⑻">
    <title>openlayers map</title>
    <link rel="stylesheet" type="text/css" href="http://dev.openlayers.org/theme/default/style.css"/>
    <style>
        html, body{
            padding:0;
            margin:0;
            height:100%;
            width:100%;
            overflow: hidden;
            font-size: 12px;
        }
        #map1{
            width: 100%;
            height: 100%;
            float: left;
            border-right: 1px solid #000000;
        }
        .tool{
            position: absolute;
            top:10pt;
            right: 10pt;
            padding: 5px;
            background: #fff;
            border: 1px solid #ff5500;
            z-index: 1000;
        }
    </style>
    <script type="text/javascript" src="http://dev.openlayers.org/OpenLayers.js"></script>
    <script src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js"></script>
    <script>
        var map1, vectors;
        OpenLayers.Feature.Vector.style['default']['strokeWidth'] = '2';
        $(function(){
            var bounds = new OpenLayers.Bounds(
                    73.45100463562233, 18.16324718764174,
                    134.97679764650596, 53.531943152223576
            );
            var options = {
                controls: [],
                maxExtent: bounds,
                maxResolution: 0.2403351289487642,
                projection: "EPSG:4326",
                units: 'degrees'
            };
            map1 = new OpenLayers.Map('map1', options);

            map1.addLayer(getWms("province"));
            map1.addControl(new OpenLayers.Control.Zoom());
            map1.addControl(new OpenLayers.Control.Navigation());
            map1.zoomToExtent(bounds);
            $("#addchart").on("click",function(){
                addShpData();
            });
        });

        function getWms(layer){
            return new OpenLayers.Layer.WMS(
                    "Geoserver layers - Tiled",
                    "http://localhost:8088/geoserver/lzugis/wms",
                    {
                        "LAYERS": layer,
                        "STYLES": '',
                        format: 'image/png'
                    },
                    {
                        buffer: 0,
                        displayOutsideMaxExtent: true,
                        isBaseLayer: true,
                        yx : {'EPSG:4326' : true}
                    }
            );
        }

        function addShpData(){
            var renderer = OpenLayers.Util.getParameters(window.location.href).renderer;
            renderer = (renderer) ? [renderer] : OpenLayers.Layer.Vector.prototype.renderers;
            vectors = new OpenLayers.Layer.Vector("Vector Layer", {
                renderers: renderer
            });
            map1.addLayer(vectors);
            var wktFormat = new OpenLayers.Format.WKT();
            $.ajax({
                type: 'POST',
                url: "http://localhost:8081/lzugis/shp" ,
                data: {
                    layer:"capital"
                } ,
                success: function(data){
                    data = eval("("+data+")");
                    console.log(data);
                    for(var i= 0,dl=data.length;i<dl;i++){
                        var d = data[i];
                        var geometry = wktFormat.read(d.wkt);
                        vectors.addFeatures(geometry);
                    }
                }
            });
        }
    </script>
</head>
<body>
<div class="tool">
    <button id="addchart">读取shp</button>
</div>
<div id="map1"></div>
</body>
</html>

实现后效果以下:



附录

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

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


传播GIS知识 | 交换GIS经验 | 分享GIS价值 | 专注GIS发展

技术博客

http://blog.csdn.net/gisshixisheng

在线教程

http://edu.csdn.net/course/detail/799
Github

https://github.com/lzugis/

联系方式

q       q:1004740957

e-mail:niujp08@qq.com

公众号:lzugis15

Q Q 群:452117357(webgis)
             337469080(Android)



生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生