GeoCastUtil.java 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package com.sysu.admin.utils.shape;
  2. import org.geotools.geojson.geom.GeometryJSON;
  3. import org.geotools.geometry.jts.WKTWriter2;
  4. import org.locationtech.jts.geom.*;
  5. import org.opengis.feature.type.GeometryDescriptor;
  6. import java.io.IOException;
  7. import java.io.StringReader;
  8. public class GeoCastUtil {
  9. private static WKTWriter2 wktReader2 = new WKTWriter2();
  10. public static String geomToWkt(Geometry geometry){
  11. return wktReader2.write(geometry);
  12. }
  13. private static GeometryCollection castGeometryCollection2(GeometryJSON fjson, GeometryCollection geometryCollection) throws IOException {
  14. if (geometryCollection.getGeometryType().equals("GeometryCollection")) {
  15. return geometryCollection;
  16. }
  17. String[] geometriesJsonArray = new String[geometryCollection.getNumGeometries()];
  18. int length = 0;
  19. for(int i=0; i< geometryCollection.getNumGeometries(); i++){
  20. Geometry geometry = geometryCollection.getGeometryN(i);
  21. geometriesJsonArray[i] = fjson.toString(geometry);
  22. length += geometriesJsonArray[i].length();
  23. }
  24. StringBuffer result = new StringBuffer(length + 100);
  25. result.append("{\"type\": \"GeometryCollection\",\"geometries\": [");
  26. result.append(geometriesJsonArray[0]);
  27. for(int i=1;i< geometriesJsonArray.length;i++){
  28. result.append(",").append(geometriesJsonArray[i]);
  29. }
  30. result.append("]}");
  31. return fjson.readGeometryCollection(new StringReader(result.toString()));
  32. }
  33. public static GeometryCollection castGeometryCollection(GeometryJSON fjson, Geometry geometry) throws IOException {
  34. if (geometry.getGeometryType().equals("GeometryCollection")) {
  35. return (GeometryCollection)geometry;
  36. }
  37. if (geometry instanceof GeometryCollection) {
  38. return castGeometryCollection2(fjson, (GeometryCollection)geometry);
  39. }
  40. String geometryJson = fjson.toString(geometry);
  41. StringBuffer result = new StringBuffer(geometryJson.length() + 100);
  42. result.append("{\"type\": \"GeometryCollection\",\"geometries\": [");
  43. result.append(geometryJson);
  44. result.append("]}");
  45. return fjson.readGeometryCollection(new StringReader(result.toString()));
  46. }
  47. public static Geometry readGeometry(Object input, String type, GeometryJSON gjson) throws IOException {
  48. switch(type){
  49. case "Point":
  50. return gjson.readPoint(input);
  51. case "MultiPoint":
  52. return gjson.readMultiPoint(input);
  53. case "LineString":
  54. return gjson.readLine(input);
  55. case "MultiLineString":
  56. return gjson.readMultiLine(input);
  57. case "Polygon":
  58. return gjson.readPolygon(input);
  59. case "MultiPolygon":
  60. return gjson.readMultiPolygon(input);
  61. }
  62. return null;
  63. }
  64. }