Ahmed Gaafer
Ahmed Gaafer

Reputation: 1661

open layers only draw features around 0,0

I have an application that I can upload csv, kml, geojson, etc... files too and I am supposed to draw the features that are included within this file to the map.

I validated that the file content is valid and that the projection of all points is the global projection "EPSG:4326";

Now I have this react code.

import { useContext, useEffect } from "react";
import MapContext from "../Map/MapContext";
import { GeoJSON } from "ol/format";

import { Vector as OlVectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";

const VectorLayer = ({ featureCollection, style, zIndex = 0 }) => {
    const { map } = useContext(MapContext);

    useEffect(() => {
        if (!map || !featureCollection || !style) return;

        const geoJsonFormat = new GeoJSON();
        const features = geoJsonFormat.readFeatures(featureCollection);

        const vectorLayer = new OlVectorLayer({
            source: new VectorSource({
                features: features,
            }),
            style: (feat) => {
                const geomType = feat.getGeometry().getType();
                if (geomType === "Point") return style.Icon;
                if (geomType === "Polygon") return style.Polygon;
                if (geomType === "MultiPolygon") return style.MultiPolygon;
            },
            zIndex: zIndex,
        });

        //zoom to extent

        map.getView().fit(vectorLayer.getSource().getExtent(), map.getSize());

        map.addLayer(vectorLayer);
        vectorLayer.setZIndex(zIndex);

        return () => {
            if (map) {
                map.removeLayer(vectorLayer);
            }
        };
    }, [map, featureCollection, style]);

    return null;
};

export default VectorLayer;

this code simply takes a feature collection and a set of ol styles

1 - convert the feature collection to the features array

2 - create a new OlVectorLayer

3 - create a new VectorSource with my converted features

4- apply style based on the feature type

5- zoom to the extent of the new added layer

6- add this layer to the map

The issue is that the features are added around map position 0,0 and not in their correct geometry.

faulty features image

How can I place them in the correct place?

Upvotes: 1

Views: 322

Answers (1)

Mike
Mike

Reputation: 17897

You need to read the feature into the view projection (which is probably EPSG:3857, not EPSG:4326).

const features = geoJsonFormat.readFeatures(featureCollection, {
  dataProjection: 'EPSG:4326',
  featureProjection: map.getView().getProjection()
});

Or you could use a data url as in https://stackoverflow.com/a/70778142/10118270

Upvotes: 2

Related Questions