微信扫一扫

028-83195727 , 15928970361
business@forhy.com

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

2016-06-28

概述:

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


读取shp

package com.lzugis.web;

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();
                    PropertyType proType =  pro.getType();
                    String dataType = proType.getBinding().getSimpleName();
                    String field = pro.getName().toString();
                    String value = pro.getValue().toString();
                    field = field.equals("the_geom")?"geom":field;
                    value = getValue(field,value,dataType);
                    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-8");
            PrintWriter out = response.getWriter();
            out.println(list.toString());
            out.flush();
            out.close();
        }
        catch(Exception e){
            System.out.println(e.getMessage());
        }
    }
    /**
     * 获取值,是字符串型的加''
     * @param value
     * @param type
     * @return
     */
    private static String getValue(String field, String value,String type){
        String newValue = value;
        if(type.equals("String")){
            newValue = "'"+value+"'";
        }
        if(field.equals("geom")){
            newValue = "st_geomfromtext('"+value+"')";
        }
        if(type.equals("Date")){
            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy",java.util.Locale.US);
            try {
                Date date = sdf.parse(value);
                SimpleDateFormat sdfL = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                newValue = "'"+sdfL.format(date)+"'";
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println(newValue);
        }
        return newValue;
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

返回的数据如下:



展示数据

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>openlayers map</title>
    <link rel="stylesheet" href="http://localhost/olapi/theme/default/style.css" type="text/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;
        }
    </style>
    <script src="../../../plugin/OpenLayers-2.13.1/OpenLayers.js"></script>
    <script src="../../../plugin/jquery/jquery-1.8.3.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);
            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){
                    console.log(data);
                    for(var i= 0,dl=data.length;i<dl;i++){
                        var d = data[i];
                        var geometry = wktFormat.read(d.geom);
                        vectors.addFeatures(geometry);
                    }
                }
            });
        }
    </script>
</head>
<body>
    <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)