Geotools中蜂巢的实现

概述

本文讲述如何在geotools中实现蜂巢效果。

效果

实现

1.扩展类IntersectionBuilder

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import java.io.IOException;
import java.util.Map;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.grid.GridElement;
import org.geotools.grid.GridFeatureBuilder;
import org.geotools.grid.PolygonElement;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.Filter;
import org.opengis.filter.FilterFactory2;

public class IntersectionBuilder extends GridFeatureBuilder {
    final FilterFactory2 ff2 = CommonFactoryFinder.getFilterFactory2();
    final GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();

    final SimpleFeatureSource source;
    int id = 0;

    public IntersectionBuilder(SimpleFeatureType type, SimpleFeatureSource source) {
        super(type);
        this.source = source;
    }

    public void setAttributes(GridElement el, Map<String, Object> attributes) {
        attributes.put("id", ++id);
    }

    @Override
    public boolean getCreateFeature(GridElement el) {
        Coordinate c = ((PolygonElement) el).getCenter();
        Geometry p = gf.createPoint(c);
        Filter filter = ff2.intersects(ff2.property("the_geom"), ff2.literal(p));
        boolean result = false;

        try {
            result = !source.getFeatures(filter).isEmpty();
        } catch (IOException ex) {
            throw new IllegalStateException(ex);
        }

        return result;
    }
}

2.实现类HexGrid

import com.lzugis.geotools.utils.IntersectionBuilder;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.Point;
import com.vividsolutions.jts.geom.Polygon;
import org.geotools.data.FeatureWriter;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.Transaction;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.grid.Envelopes;
import org.geotools.grid.GridFeatureBuilder;
import org.geotools.grid.Grids;
import org.geotools.grid.hexagon.HexagonOrientation;
import org.geotools.grid.hexagon.Hexagons;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;

import java.io.File;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HexGrid {
    /**
     * 保存为shp文件
     * @param filepath
     * @param sfsGrid
     */
    public void writeShape(String filepath, SimpleFeatureSource sfsGrid) {
        try {
            //创建shape文件对象
            File file = new File(filepath);
            Map<String, Serializable> params = new HashMap<String, Serializable>();
            params.put( ShapefileDataStoreFactory.URLP.key, file.toURI().toURL() );
            ShapefileDataStore ds = (ShapefileDataStore) new ShapefileDataStoreFactory().createNewDataStore(params);
            //定义图形信息和属性信息
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
            tb.setCRS(DefaultGeographicCRS.WGS84);
            tb.setName("shapefile");
            tb.add("the_geom", Polygon.class);
            tb.add("id", Integer.class);
            ds.createSchema(tb.buildFeatureType());
            //设置编码
            Charset charset = Charset.forName("GBK");
            ds.setCharset(charset);
            //设置Writer
            FeatureWriter<SimpleFeatureType, SimpleFeature> writer = ds.getFeatureWriter(ds.getTypeNames()[0], Transaction.AUTO_COMMIT);
            SimpleFeatureCollection resultgrid = sfsGrid.getFeatures();
            SimpleFeatureIterator itertorgrid = resultgrid.features();
            while (itertorgrid.hasNext()) {
                SimpleFeature feature = itertorgrid.next();
                SimpleFeature featureBuf = writer.next();
                featureBuf.setAttributes(feature.getAttributes());
            }
            writer.write();
            writer.close();
            ds.dispose();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成蜂巢
     * @param shpfile
     * @param sideLen
     * @return
     */
    public SimpleFeatureSource createGrid(String shpfile, float sideLen){
        try {
            File file = new File(shpfile);
            ShapefileDataStore shpDataStore = null;
            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);
            // Set the grid size (1 degree) and create a bounding envelope
            // that is neatly aligned with the grid size
            ReferencedEnvelope gridBounds = Envelopes.expandToInclude(featureSource.getBounds(), sideLen);
            // Create a feature type
            SimpleFeatureTypeBuilder tb = new SimpleFeatureTypeBuilder();
            tb.setName("grid");
            tb.add(
                    GridFeatureBuilder.DEFAULT_GEOMETRY_ATTRIBUTE_NAME,
                    Polygon.class,
                    gridBounds.getCoordinateReferenceSystem());
            tb.add("id", Integer.class);
            SimpleFeatureType TYPE = tb.buildFeatureType();

            // Build the grid the custom feature builder class
            GridFeatureBuilder builder = new IntersectionBuilder(TYPE, featureSource);
            SimpleFeatureSource grid =
                    Hexagons.createGrid(gridBounds, sideLen, HexagonOrientation.ANGLED, builder);
            return grid;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception{
        long start = System.currentTimeMillis();
        HexGrid hexGrid = new HexGrid();
        String path = "D:\\data\\beijing\\";
        String shpfile = path+"beijing.shp";
        String gridFile = path+"bj_grid.shp";
        float sideLen = 0.03f;
        hexGrid.writeShape(gridFile, hexGrid.createGrid(shpfile, sideLen));
        System.out.println("共耗时"+(System.currentTimeMillis() - start)+"ms");
    }
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏编舟记

Java内部类的异常处理

最近遇到一个问题,使用Java写某个DSL标记语言X的parser(解析器)Maven插件的时候,对外暴露一个名为Callback的接口和一个待实现的方法get...

802
来自专栏漫漫深度学习路

pytorch学习笔记(十四): DataLoader源码阅读

pytorch 数据加载部分的 接口可以说是现存 深度学习框架中设计的最好的, 给了我们足够的灵活性。本博文就对 pytorch 的多线程加载 模块(Data...

1.9K8
来自专栏Java帮帮-微信公众号-技术文章全总结

第二十一天 IO-递归&字节流&字符流【悟空教程】

递归就是“在一个方法内可以再次调用自身”,如下,method方法又调用了method方法。

1033
来自专栏大内老A

ASP.NET MVC是如何运行的(4): Action的执行

作为Controller基类ControllerBase的Execute方法的核心在于对Action方法的执行和作为方法返回的ActionResult的执行,两...

1968
来自专栏北京马哥教育

AWK处理日志入门

前言 这两天自己挽起袖子处理日志,终于把AWK给入门了。其实AWK的基本使用,学起来也就半天的时间,之前总是靠同事代劳,惰性呀。 此文仅为菜鸟入门,运维们请勿...

3594
来自专栏coolblog.xyz技术专栏

Spring IOC 容器源码分析 - 填充属性到 bean 原始对象

本篇文章,我们来一起了解一下 Spring 是如何将配置文件中的属性值填充到 bean 对象中的。我在前面几篇文章中介绍过 Spring 创建 bean 的流程...

1412
来自专栏蓝天

sed 学习笔记(转)

声明:这些代码只是为了学习和理解sed命令而为之,并不代表问题的唯一解或最佳解,希望各位拍砖

802
来自专栏GIS讲堂

用GeoTools实现shp+sld导出图片

2153
来自专栏机器人网

只会G代码不会宏,就别说你是数控师傅

一、变量 普通加工程序直接用数值指定G代码和移动距离;例如,GO1和X100.0。使用用户宏程序时,数值可以直接指定或用变量指定。当用变量时,变量值可用程序或用...

2864
来自专栏数据结构与算法

cf444E. DZY Loves Planting(并查集)

然后cf正解居然是网络流??出给NOIP模拟赛T1???¥%……&((……%&((

1273

扫码关注云+社区

领取腾讯云代金券