Search code examples
openlayers

How to create custom marker on openLayers?


I want to create a marker with an image inside and a stroke shape like this. I don't understand how to do this? Maybe I need to somehow add a css class and edit it through styles?

enter image description here

 const style = new Style({
        image: new Icon({
          anchor: [0.5, 46],
          anchorXUnits: "fraction",
          anchorYUnits: "pixels",
          width: 30,
          height: 30,
          src: "src/avatar.png",
        }),
      })

This is how I create a marker with an image. But how to make a white background and corner for it?

 const style = new Style({
        image: new Icon({
          anchor: [0.5, 46],
          anchorXUnits: "fraction",
          anchorYUnits: "pixels",
          width: 30,
          height: 30,
          src: "src/avatar.png",
        }),
      })

Solution

  • Create whatever you need in a canvas then use it as the icon

    For example

    const canvas = document.createElement('canvas');
    const radius = 24;
    canvas.width = radius * 2;
    canvas.height = canvas.width;
    const context = canvas.getContext('2d');
    context.beginPath();
    context.arc(radius, radius, radius, -Math.PI, Math.PI / 2);
    context.lineTo(0, radius * 2);
    context.closePath();
    context.clip();
    context.fillStyle = 'white';
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.beginPath();
    context.arc(radius, radius, radius * 0.75, 0, Math.PI * 2);
    context.clip();
    context.fillStyle = 'blue';
    context.fillRect(0, 0, canvas.width, canvas.height);
    

    the either

    const iconStyle = new Style({
      image: new Icon({
        anchor: [0, 1],
        src: canvas.toDataURL(),
      }),
    });
    

    or

    const iconStyle = new Style({
      image: new Icon({
        anchor: [0, 1],
        img: canvas
      }),
    });
    

    https://codesandbox.io/s/icon-forked-gh4h3j?file=/main.js