Coordinate System Transformation – Why Can’t EPSG:4326 Be Transformed to EPSG:3857

coordinate systemepsggeotoolstransform

My problem is I tried transforming from EPSG:4326 to WGS84, and it worked (just swap the axis order), and I also tried transforming from EPSG:4326 to EPSG:3875, and it worked too (the coordinates changed).

However, when I tried transforming from EPSG:4326 to EPSG:3857 (default CRS of Leaflet's OSM) to generate an image to display as an imageOverlay to the Leaflet's OSM, it did not work.

I have been stuck with this issue for 3 days and still no luck at all.

All I can do is to generate an image which is not matched with the OSM of Leaflet.

Really appreciate if someone can show me the way out of this!

Below is my code:

        CoordinateReferenceSystem sourceCRS = featureSource.getSchema().getCoordinateReferenceSystem();
        CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:3857");
        List<SimpleFeature> transformedFeatures = new ArrayList<>();

        try (SimpleFeatureIterator iterator = featureCollection.features()) {
            while (iterator.hasNext()) {
                SimpleFeature feature = iterator.next();
                Geometry geometry = (Geometry) feature.getAttribute("geom");
                if (targetCRS != null && targetCRS != sourceCRS) {
                    MathTransform transform = CRS.findMathTransform(sourceCRS, targetCRS);
                    Geometry transformedGeometry = JTS.transform(geometry, transform);
                    feature.setDefaultGeometry(transformedGeometry);
                }
                transformedFeatures.add(feature);
            }
        }

        SimpleFeatureCollection transformedFeatureCollection = DataUtilities.collection(transformedFeatures);
        try (FileOutputStream output = new FileOutputStream(
                "C:\\Users\\Admin\\eclipse-workspace\\leaflet-1\\vite-project\\public\\image.png")) {
            Style style = createStyle();
            ReferencedEnvelope envelope = new ReferencedEnvelope(-180, 180, -85, 85, CRS.decode("EPSG:3857"));
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                    imageFromFeatures(transformedFeatureCollection, envelope, style, 1024));
            IOUtils.copy(byteArrayInputStream, output);
        } catch (IOException e) {
            e.printStackTrace();
        }

The error is:

    Possible use of "Popular Visualisation Pseudo Mercator" projection outside its valid area.
    Latitude 117°42.2'N is out of range (±90°).
    Latitude 117°42.2'N is too close to a pole.

This is the image generated when I choose the target CRS as WGS84:
enter image description here

Best Answer

You need to read the GeoTools FAQ on axis order - you are making unwarranted assumptions about axis order.

DefaultGeographicCRS.WGS84 doesn't actually make any promises about axis order. You should always check with CRS.axisOrder()