Search code examples
labelstylesopenlayersoffsetlabeling

Assign label/text to icon using offset -OpenLayers


I want to assign text or label using OpenLayers to Icons. I am able to assign the label to the icon but it places text on the icon .but I want to display label at offset so icon and label both display properly. I have tried using offsetY but it is not working and does not change the placement. enter image description here

var styleToponimiFunction = function(feature,resolution) {
      console.log(feature);
      var iconName;
     
      if (feature.get("remark")=='Daerah Istimewa') {
        iconName='daerah_istimewa2.png';  
      }
      else if (feature.get("remark")=='Kecamatan'){
        iconName='kecamatan.png';  
      }
      iconStyle = [new ol.style.Style({
        
          image: new ol.style.Icon(({
              anchor: [0.5, 46], 
              anchorXUnits: "fraction",
              anchorYUnits: "pixel",              
              scale:0.03,
              opacity:1,
              src: "icons/" + iconName,
             })),
          text: new ol.style.Text({
                text: feature.get('namobj'),
                font: '12px Calibri,sans-serif',
                fill: new ol.style.Fill({ color: 'black' }),
                stroke: new ol.style.Stroke({
                color: '#fff', 
                width: 2,
                textAlign: 'center',
                Baseline: 'hanging',               
                offsetX : 0,
                offsetY : -12,           
                          
                }),
                declutter: true,
                overflow: true
             }),           
             })
             ]
      return iconStyle;
    }      


Solution

  • The text options should not be inside the Stroke constructor, also Baseline should be textBaseline

                stroke: new ol.style.Stroke({
                  color: '#fff', 
                  width: 2,
                }),
                textAlign: 'center',
                textBaseline: 'hanging',               
                offsetX : 0,
                offsetY : -12,