[GIS] GeoTools, convert CRS for Google Maps

coordinate systemepsggeotoolsgoogle maps

I'm trying to use GeoTools to convert coordinates from EPSG:3857 to various CRS, in order to display WMS layers on a Google Map.

For example, I want to display a layer in the EPSG:4326 CRS. I have the coordinates in EPSG:3857, and I need to convert them in EPSG:4326 to ask the server.

Here is what I'm doing :

// The coordinates are in meters in the EPSG:3857 CRS
double[] lowerLeft = new double[] { longitudeMin, latitudeMin};
double[] upperRight = new double[] { longitudeMax, latitudeMax };

CoordinateReferenceSystem srcCrs = CRS.decode("EPSG:3857", true);
CoordinateReferenceSystem destCrs = CRS.decode("EPSG:4326", true);

MathTransform transform = CRS.findMathTransform(srcCrs, destCrs, true);

transform.transform(lowerLeft, 0, lowerLeft, 0, 1);
transform.transform(upperRight, 0, upperRight, 0, 1);

// Check if axis order is NORTH_EAST (= LAT_LON) or EAST_NORTH (= LON_LAT) :
String bbox;
if(CRS.getAxisOrder(_crs) == CRS.AxisOrder.NORTH_EAST) {

    bbox = lowerLeft[0] + "," + lowerLeft[1] + "," + upperRight[0] + "," + upperRight[1];
}
else {

    bbox = lowerLeft[1] + "," + lowerLeft[0] + "," + upperRight[1] + "," + upperRight[0];
}

I have no error and it seems to be working, but the map is not displayed correctly, as you can see on the image below (on the left, the correctly displayed Google Maps, on the right, my WMS layer) :

Google Maps vs WMS layer

So, the question is, what am I doing wrong ? Is everything working properly, and I just can't display a WMS in EPSG:4326 (or any other CRS) on my EPSG:3857 Google Maps ?

Best Answer

For what you are trying to do you could use the WMS datastore in GeoTools to import the layers you need:

see https://gitlab.com/snippets/6355 for a full example.