geotools实现wmts服务

/**
     * wmts服务
     * @param params
     */
    @Override
    public void wmts(GeoEntityWmtsParams params) throws IOException, ServiceException, FactoryException {
        HttpServletResponse response = ServletUtils.getResponse();
        // 创建时间格式化对象,指定时间格式
        DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");
        String layerName = params.getLayer();
        String srs = params.getTilematrixset();
        //列 == x
        Integer tilecol = params.getTilecol();
        //行 == y
        Integer tilerow = params.getTilerow();
        String version = params.getVersion();
        String format = params.getFormat();
        //放大倍数
        Integer zoomLevel = params.getTilematrix();
        String tileMatrixSet = params.getTilematrixset();
        URL url = null;
        try {
            url = new URL("http://localhost:8080/geoserver/gwc/service/wmts?REQUEST=GetCapabilities");
        } catch (MalformedURLException e) {
            // will not happen
        }
        WebMapTileServer wmts = new WebMapTileServer(url);
        WMTSCapabilities capabilities = wmts.getCapabilities();
        WMTSLayer layer = capabilities.getLayer(layerName);
        CoordinateReferenceSystem crs = CRS.decode(srs);
        // Find the TileMatrixSet for the specified zoom level
        TileMatrixSet matrixSet = wmts.getCapabilities().getMatrixSet(tileMatrixSet);


        MapContent mapContent = new MapContent();
        try {



            //CoordinateReferenceSystem crs = CRS.decode(srs);
            List res = geoEntityMapper.wms(layer.getTitle(),null,null,null,null);

            //feature
            SimpleFeatureTypeBuilder typeBuilder = new SimpleFeatureTypeBuilder();
            typeBuilder.setName("WMSFeatureType");
            //typeBuilder.setCRS(DefaultGeographicCRS.WGS84);
            typeBuilder.setCRS(crs);
            typeBuilder.add("geom", MultiPolygon.class);
            SimpleFeatureType featureType = typeBuilder.buildFeatureType();
            DefaultFeatureCollection featureCollection = new DefaultFeatureCollection(null, featureType);
            if(res!=null&&res.size()>0){
                Style style = SLD.createSimpleStyle(featureType, Color.GRAY);
                List layerList = new ArrayList<>();
                System.out.println("=====遍历前时间========"+ LocalTime.now().format(timeFormatter));
                res.stream().forEach((a)->{
                    Geometry geometry = a.getGeom();
                    SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);
                    featureBuilder.add(geometry);
                    SimpleFeature feature = featureBuilder.buildFeature(null);
                    featureCollection.add(feature);
                    SimpleFeatureSource featureSource = DataUtilities.source(featureCollection);
                    FeatureLayer featureLayer = new FeatureLayer(featureSource, style);
                    featureLayer.setTitle(layerName);
                    layerList.add(featureLayer);
                });

                ReferencedEnvelope tileEnvelope = getTileEnvelope(tilecol, tilerow, matrixSet,crs,zoomLevel);
                mapContent.setTitle("WMS Image");
                mapContent.addLayers(layerList);

                GTRenderer renderer = new StreamingRenderer();
                renderer.setMapContent(mapContent);
                BufferedImage image = new BufferedImage(256, 256, BufferedImage.TYPE_INT_RGB);

                //根据以上信息渲染图片
                Graphics2D graphics = (Graphics2D) image.getGraphics();
                Rectangle rectangle = new Rectangle(256, 256);
                //ReferencedEnvelope referencedEnvelope = new ReferencedEnvelope(minX, maxX, minY, maxY, crs);
                System.out.println("=====paint前时间========"+ LocalTime.now().format(timeFormatter));
                renderer.paint(graphics, rectangle, tileEnvelope);
                System.out.println("=====paint后时间========"+ LocalTime.now().format(timeFormatter));

                //输出流输出到前端
                System.out.println("=====write前时间========"+ LocalTime.now().format(timeFormatter));
                ImageIO.write(image, "png", response.getOutputStream());
                System.out.println("=====write后时间========"+ LocalTime.now().format(timeFormatter));


            }
        }catch (Exception e){
            String message = e.getMessage();
            if (!message.contains("transform: latitude or longitude exceeded limits (-14)")) {
                log.error("图片输出异常:参数【" + JSON.toJSONString(params) + "】",e);
            } else {
                log.error("图片输出异常:参数【" + JSON.toJSONString(params) + "】" + e.getMessage());
            }
        }finally {
            mapContent.dispose();
        }
    }

    /**
     * 代码从geotools源码中拷贝  col row zoomlevel 转 minx,miny,maxx,maxy
    * @param tileCol
     * @param tileRow
     * @param matrixSet
     * @param crs
     * @return
     */
    private ReferencedEnvelope getTileEnvelope(int tileCol, int tileRow, TileMatrixSet matrixSet,CoordinateReferenceSystem crs,Integer zoomLevel) {
//
        //new WebMapTileServer();
        CoordinateSystem coordinateSystem = crs.getCoordinateSystem();
        Unit unit = (Unit) coordinateSystem.getAxis(0).getUnit();
        Point topLeft = matrixSet.getMatrices().get(17).getTopLeft();
        TileMatrix tileMatrix = matrixSet.getMatrices().get(zoomLevel);
        double denominator =tileMatrix.getDenominator();
        double pixelSpan = denominator * 0.28e-3;
        if (unit.equals(NonSI.DEGREE_ANGLE)) {
            pixelSpan /= 111319;
        }else{
            UnitConverter metersperunit = unit.getConverterTo(SI.METRE);
            pixelSpan /= metersperunit.convert(1);
        }
        double tileSpanY = (tileMatrix.getTileHeight() * pixelSpan);
        double tileSpanX = (tileMatrix.getTileWidth() * pixelSpan);
        double tileMatrixMinX;
        double tileMatrixMaxY;
        boolean longFirst = coordinateSystem.getAxis(0).getDirection().equals(AxisDirection.EAST);
        if (longFirst) {
            tileMatrixMinX = topLeft.getX();
            tileMatrixMaxY = topLeft.getY();
        } else {
            tileMatrixMaxY = topLeft.getX();
            tileMatrixMinX = topLeft.getY();
        }
        ReferencedEnvelope ret = new ReferencedEnvelope(crs);
        double minX = tileCol * tileSpanX + tileMatrixMinX;
        double maxY = tileMatrixMaxY - tileRow * tileSpanY;
        double maxX = minX + tileSpanX;
        double minY = maxY - tileSpanY;
        if (longFirst) {
            ret.expandToInclude(minX, minY);
            ret.expandToInclude(maxX, maxY);
        } else {
            ret.expandToInclude(minY, minX);
            ret.expandToInclude(maxY, maxX);
        }
        return ret;

    }

你可能感兴趣的:(geotools)