Search code examples
typescriptopenlayersgeojson

How to translate coordinates at loading GeoJSON objects for OpenLayers VectorlLayer?


I have an image map with X Y coordinates and load Objects from GeoJSON source. The coordinates in the JSON file need to be translated with a X and Y offset. For this the geometry is taken and translated: geometry.translate(162, 435), like in the below example. But instead of translating the coordinates of the object once, the translating (adding the offsets) loops infinitly till the object moves out of the map.

objectsLayer = new VectorLayer({
    visible: true,
    source: new VectorSource({
      url: 'assets/objects.json',
      format: new GeoJSON(),
    }),
    style: function (feature) {
      console.log('style: function');
      let geometry = feature.getGeometry();
      if (geometry instanceof Geometry) {
        geometry.translate(162, 435);
      }
      return new Style({
        image: new CircleStyle({
          radius: 5,
          stroke: new Stroke({ color: 'cyan', width: 1 }),
          fill: new Fill({ color: 'magenta' }),
        }),
      });
    },
  });

How to apply the translate function only once to each object?


Solution

  • Either

    objectsLayer = new VectorLayer({
        visible: true,
        source: new VectorSource({
          url: 'assets/objects.json',
          format: new GeoJSON(),
        }),
        style: function (feature) {
          let geometry = feature.getGeometry();
          if (geometry instanceof Geometry) {
            geometry = geometry.clone();
            geometry.translate(162, 435);
          }
          return new Style({
            geometry: geometry,
            image: new CircleStyle({
              radius: 5,
              stroke: new Stroke({ color: 'cyan', width: 1 }),
              fill: new Fill({ color: 'magenta' }),
            }),
          });
        },
      });
    

    or

    objectsLayer = new VectorLayer({
        visible: true,
        source: new VectorSource({
          url: 'assets/objects.json',
          format: new GeoJSON(),
        }),
        style: new Style({
          geometry: function (feature) {
            let geometry = feature.getGeometry();
            if (geometry instanceof Geometry) {
              geometry = geometry.clone();
              geometry.translate(162, 435);
            }
            return geometry;
          },
          image: new CircleStyle({
            radius: 5,
            stroke: new Stroke({ color: 'cyan', width: 1 }),
            fill: new Fill({ color: 'magenta' }),
          }),
        }),
      });
    

    should work.