Search code examples
javageotoolsjts

How to Swap Coordinates of jts.geom.Geometry object from Lat, Long to Long,Lat in JTS


I have a geometry object of type (com.vividsolutions.jts.geom.Geometry). it is currently in latitude, longitude form and I'd like to flip the coordinates so that its longitude latitude so that I can have it in GeoJSON format for mongodb.

My constraints that I am seeing are: a) the input that I would like to flip coordinates for is a Geometry object. b) The Geometry object will be either a Polygon type or Multipolygon. c) I would like to flip the coordinates before the type cast to Polygon/multipolygon

I have tried geo.reverse() but it does not work.

As well, I have tried using: CRSAuthorityFactory factory = CRS.getAuthorityFactory(true); CoordinateReferenceSystem crs = factory.createCoordinateReferenceSystem("EPSG:4326");

And another option and I did not see it work.

Thanks!


Solution

  • One potential solution to this is extending the class to provide an additional function that either outputs the data you need in some convenient way:

    public Coordinate[] getReversedCoordinates(){
    
      Coordinate[] original = this.getCoordinates();
      Coordinate[] ret = new Coordinate[original.length];
    
      for(int i =0; i<original.length; i++){
          ret[i] = new Coordinate( original[i].x , original[i].y );
      }
    
      return ret;
    
    }
    

    Alternately you could alter the interpretation of the data. It's a little harder for me to give you a code snippet for that as I'm not sure how you're using the information specifically.

    EDIT:

    Once you have the reversed coordinates,you can create a duplicate Geometry of type linear ring. A means of doing this is to use your factory to use your geometry factory:

    GeometryFactory gf = //However this was instantiated;
    Coordinate[] reversedCoordinates = getReversedCoordinates();
    gf.createLinearRing(reversedCoordinates);
    

    Happy coding and leave a comment if you have any questions!