Simplest example of adding text to an openlayers map?

Viewed 124

I would like to add a text label to an OpenLayers map at a specific latitude and longitude.

I've struggled to find a succinct example that doesn't involve pulling in data from files etc. I've been able to add polygons, icons and all sorts of mouse events to my map and contents; but for some reason, just adding a simple bit of text seems to be eluding me.

Please could someone make my Friday, and post a simple example?

1 Answers

You can create a feature with a style that only contains text (no geometry).

var labelFeature = new Feature({
  geometry: new Point([0, 0]),
});

var labelonly = new Style({
    text: new Text({
        font: '14px sans-serif',
        text: 'hello',
        fill: new Fill({
            color: 'black'
        }),
    })
});


labelFeature.setStyle(labelonly);

var vectorSource = new VectorSource({
  features: [labelFeature]
});

var vectorLayer = new VectorLayer({
  source: vectorSource
});


var map = new Map({
  layers: [vectorLayer],
  target: document.getElementById('map'),
  view: new View({
    center: [0, 0],
    zoom: 3
  })
});
Related