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

Geotools读取shp文件并在Ol2中展示,第1张

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

概述:

在前面有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,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:[email protected]

公众号:lzugis15

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



总结

以上是内存溢出为你收集整理的Geotools读取shp文件并在Ol2中展示全部内容,希望文章能够帮你解决Geotools读取shp文件并在Ol2中展示所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1016056.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-22
下一篇 2022-05-22

发表评论

登录后才能评论

评论列表(0条)

保存