1

I want to add the marker on the Openlayer map using React on the center point but I am not able to do so, I tried different solutions but still no luck.

Here is my React code:

import React, { useState, useEffect, useRef } from "react";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import * as proj from "ol/proj";
import Style from "ol/style/Style";
import Icon from "ol/style/Icon";

function MapWrapper(props: any) {
  const [map, setMap] = useState<any>();
  const mapElement = useRef<any>();

  const [center, setCenter] = useState(proj.fromLonLat([-122.335167, 47.608013]));

  var iconStyle = new Style({
    image: new Icon({
      anchor: [0.5, 32],
      anchorXUnits: "fraction",
      anchorYUnits: "pixels",
      src: "marker.jpg",
    }),
  });

  useEffect(() => {
    const initialMap = new Map({
      target: mapElement.current,
      layers: [
        new TileLayer({
          source: new OSM(),
        }),
      ],
      view: new View({
        center: center,
        zoom: 17,
      }),
    });
    setMap(initialMap);
  }, []);

  return (
    <div className="mapRow">
      <div ref={mapElement} className="map-container" />
    </div>
  );
}

export default MapWrapper;

Where and how should I call the iconStyle I am not able to get it and how to show the pointer on the assigned center point?

1 Answers1

1

You should create a vector layer, then create a feature with a Point geometry in this vector layer and then assign the icon style to the feature:

const featureOverlay = new VectorLayer({
  source: new VectorSource(),
  map: map,
  style: <your style goes here>
});
featureOverlay.getSource().addFeature(
  new Feature(new Point(fromLonLan([-122.335167, 47.608013])))
);

Then add this layer to your map.

Also, I strongly advise you to not use useEffect() to create Openlayers components. You should at least return a function that can cancel your operation - otherwise a simple click on a link will render your page unusable.

You are bound to run into very complex problems later on. I am the author of https://github.com/mmomtchev/rlayers - you should probably check it for inspiration - and I can tell you that the only way to have proper React life-cycle handling is reimplement everything as a class component that redefines each basic React hook.

mmomtchev
  • 2,497
  • 1
  • 8
  • 23