Vector Labels

Points
















Lines
















Polygons
















Example of GeoJSON features with labels.

This example showcases a number of options that can be set on text styles. When "Text/Wrap" is chosen (for example for the line features), the label is wrapped by inserting the character \n, which will create a multi-line label. The "Open Sans" web font will be loaded on demand, to show dynamic font loading.

<!DOCTYPE html>
<html>
  <head>
    <title>Vector Labels</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.6.4/css/ol.css" type="text/css">
    <!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
    <script src=""></script>
    <script src="https://openlayers.org/en/v4.6.4/build/ol.js"></script>
    <style>
      h2 {
        font-size: 1.5em;
        line-height: 15px;
      }

      .scale-cnt {
        margin: 5px;
      }

      .edit-form-ctn {
      }

      .edit-form {
        float: left;
        margin: 5px;
        width: 230px;
        padding: 4px;
        border: 1px solid black;
      }

      .edit-form input[type="button"] {
        float: right;
      }

      .edit-form-elem label {
        display: block;
        float: left;
        width: 85px;
      }

      .edit-form-elem input[type="text"] {
        width: 60px;
      }

      .edit-form-elem select {
        width: 130px;
      }

      .edit-form br {
        clear: left;
      }

      .clearall {
        clear: both;
      }
    </style>
  </head>
  <body>
    <div id="map" class="map"></div>

    <div class="edit-form">
      <input id="refresh-points" type="button" value="Refresh" />
      <h2>Points</h2>
      <div class="edit-form-elem">
        <label>Text: </label>
        <select id="points-text">
          <option value="hide">Hide</option>
          <option value="normal">Normal</option>
          <option value="shorten" selected="selected">Shorten</option>
          <option value="wrap">Wrap</option>
        </select>
        <br />
        <label title="Max Resolution Denominator">MaxReso.:</label>
        <select id="points-maxreso">
          <option value="38400">38,400</option>
          <option value="19200">19,200</option>
          <option value="9600">9,600</option>
          <option value="4800">4,800</option>
          <option value="2400">2,400</option>
          <option value="1200" selected="selected">1,200</option>
          <option value="600">600</option>
          <option value="300">300</option>
          <option value="150">150</option>
          <option value="75">75</option>
          <option value="32">32</option>
          <option value="16">16</option>
          <option value="8">8</option>
        </select>
        <br />
        <label>Align: </label>
        <select id="points-align">
          <option value="center" selected="selected">Center</option>
          <option value="end">End</option>
          <option value="left">Left</option>
          <option value="right">Right</option>
          <option value="start">Start</option>
        </select>
        <br />
        <label>Baseline: </label>
        <select id="points-baseline">
          <option value="alphabetic">Alphabetic</option>
          <option value="bottom">Bottom</option>
          <option value="hanging">Hanging</option>
          <option value="ideographic">Ideographic</option>
          <option value="middle" selected="selected">Middle</option>
          <option value="top">Top</option>
        </select>
        <br />
        <label>Rotation: </label>
        <select id="points-rotation">
          <option value="0">0°</option>
          <option value="0.785398164">45°</option>
          <option value="1.570796327">90°</option>
        </select>
        <br />
        <label>Font: </label>
        <select id="points-font">
          <option value="Arial" selected="selected">Arial</option>
          <option value="'Courier New'">Courier New</option>
          <option value="'Open Sans'">Open Sans</option>
          <option value="Verdana">Verdana</option>
        </select>
        <br />
        <label>Weight: </label>
        <select id="points-weight">
          <option value="bold">Bold</option>
          <option value="normal" selected="selected">Normal</option>
        </select>
        <br />
        <label>Placement: </label>
        <select disabled id="points-placement">
          <option value="line">Line</option>
          <option value="point" selected="selected">Point</option>
        </select>
        <br />
        <label>Max Angle: </label>
        <select disabled id="points-maxangle">
          <option value="0.7853981633974483" selected="selected">45°</option>
          <option value="2.0943951023931953">120°</option>
          <option value="6.283185307179586">360°</option>
        </select>
        <br />
        <label>Exceed Len: </label>
        <select disabled id="points-overflow">
          <option value="true">True</option>
          <option value="false" selected="selected">False</option>
        </select>
        <br />
        <label>Size: </label>
        <input type="text" value="12px" id="points-size" />
        <br />
        <label>Offset X:</label>
        <input type="text" value="0" id="points-offset-x" />
        <br />
        <label>Offset Y:</label>
        <input type="text" value="0" id="points-offset-y" />
        <br />
        <label>Color :</label>
        <input type="text" value="#aa3300" id="points-color" />
        <br />
        <label title="Outline Color">O. Color:</label>
        <input type="text" value="#ffffff" id="points-outline" />
        <br />
        <label title="Outline Width">O. Width :</label>
        <input type="text" value="3" id="points-outline-width" />
      </div>
    </div>

    <div class="edit-form">
      <input id="refresh-lines" type="button" value="Refresh" />
      <h2>Lines</h2>
      <div class="edit-form-elem">
        <label>Text: </label>
        <select id="lines-text">
          <option value="hide">Hide</option>
          <option value="normal">Normal</option>
          <option value="shorten">Shorten</option>
          <option value="wrap" selected="selected">Wrap</option>
        </select>
        <br />
        <label title="Max Resolution Denominator">MaxReso.:</label>
        <select id="lines-maxreso">
          <option value="38400">38,400</option>
          <option value="19200">19,200</option>
          <option value="9600">9,600</option>
          <option value="4800">4,800</option>
          <option value="2400">2,400</option>
          <option value="1200" selected="selected">1,200</option>
          <option value="600">600</option>
          <option value="300">300</option>
          <option value="150">150</option>
          <option value="75">75</option>
          <option value="32">32</option>
          <option value="16">16</option>
          <option value="8">8</option>
        </select>
        <br />
        <label>Align: </label>
        <select id="lines-align">
          <option value="" selected="selected"></option>
          <option value="center">Center</option>
          <option value="end">End</option>
          <option value="left">Left</option>
          <option value="right">Right</option>
          <option value="start">Start</option>
        </select>
        <br />
        <label>Baseline: </label>
        <select id="lines-baseline">
          <option value="alphabetic">Alphabetic</option>
          <option value="bottom">Bottom</option>
          <option value="hanging">Hanging</option>
          <option value="ideographic">Ideographic</option>
          <option value="middle" selected="selected">Middle</option>
          <option value="top">Top</option>
        </select>
        <br />
        <label>Rotation: </label>
        <select id="lines-rotation">
          <option value="0">0°</option>
          <option value="0.785398164">45°</option>
          <option value="1.570796327">90°</option>
        </select>
        <br />
        <label>Font: </label>
        <select id="lines-font">
          <option value="Arial">Arial</option>
          <option value="'Courier New'" selected="selected">Courier New</option>
          <option value="'Open Sans'">Open Sans</option>
          <option value="Verdana">Verdana</option>
        </select>
        <br />
        <label>Weight: </label>
        <select id="lines-weight">
          <option value="bold" selected="selected">Bold</option>
          <option value="normal">Normal</option>
        </select>
        <br />
        <label>Placement: </label>
        <select id="lines-placement">
          <option value="line">Line</option>
          <option value="point" selected="selected">Point</option>
        </select>
        <br />
        <label>Max Angle: </label>
        <select id="lines-maxangle">
          <option value="0.7853981633974483" selected="selected">45°</option>
          <option value="2.0943951023931953">120°</option>
          <option value="6.283185307179586">360°</option>
        </select>
        <br />
        <label>Exceed Len: </label>
        <select id="lines-overflow">
          <option value="true">True</option>
          <option value="false" selected="selected">False</option>
        </select>
        <br />
        <label>Size: </label>
        <input type="text" value="12px" id="lines-size" />
        <br />
        <label>Offset X:</label>
        <input type="text" value="0" id="lines-offset-x" />
        <br />
        <label>Offset Y:</label>
        <input type="text" value="0" id="lines-offset-y" />
        <br />
        <label>Color :</label>
        <input type="text" value="green" id="lines-color" />
        <br />
        <label title="Outline Color">O. Color:</label>
        <input type="text" value="#ffffff" id="lines-outline" />
        <br />
        <label title="Outline Width">O. Width :</label>
        <input type="text" value="3" id="lines-outline-width" />
      </div>
    </div>

    <div class="edit-form">
      <input id="refresh-polygons" type="button" value="Refresh" />
      <h2>Polygons</h2>
      <div class="edit-form-elem">
        <label>Text: </label>
        <select id="polygons-text">
          <option value="hide">Hide</option>
          <option value="normal" selected="selected">Normal</option>
          <option value="shorten">Shorten</option>
          <option value="wrap">Wrap</option>
        </select>
        <br />
        <label title="Max Resolution Denominator">MaxReso.:</label>
        <select id="polygons-maxreso">
          <option value="38400">38,400</option>
          <option value="19200">19,200</option>
          <option value="9600">9,600</option>
          <option value="4800">4,800</option>
          <option value="2400">2,400</option>
          <option value="1200" selected="selected">1,200</option>
          <option value="600">600</option>
          <option value="300">300</option>
          <option value="150">150</option>
          <option value="75">75</option>
          <option value="32">32</option>
          <option value="16">16</option>
          <option value="8">8</option>
        </select>
        <br />
        <label>Align: </label>
        <select id="polygons-align">
          <option value="" selected="selected"></option>
          <option value="center">Center</option>
          <option value="end">End</option>
          <option value="left">Left</option>
          <option value="right">Right</option>
          <option value="start">Start</option>
        </select>
        <br />
        <label>Baseline: </label>
        <select id="polygons-baseline">
          <option value="alphabetic">Alphabetic</option>
          <option value="bottom">Bottom</option>
          <option value="hanging">Hanging</option>
          <option value="ideographic">Ideographic</option>
          <option value="middle" selected="selected">Middle</option>
          <option value="top">Top</option>
        </select>
        <br />
        <label>Rotation: </label>
        <select id="polygons-rotation">
          <option value="0">0°</option>
          <option value="0.785398164">45°</option>
          <option value="1.570796327">90°</option>
        </select>
        <br />
        <label>Font: </label>
        <select id="polygons-font">
          <option value="Arial">Arial</option>
          <option value="'Courier New'">Courier New</option>
          <option value="'Open Sans'">Open Sans</option>
          <option value="Verdana" selected="selected">Verdana</option>
        </select>
        <br />
        <label>Weight: </label>
        <select id="polygons-weight">
          <option value="bold" selected="selected">Bold</option>
          <option value="normal">Normal</option>
        </select>
        <br />
        <label>Placement: </label>
        <select id="polygons-placement">
          <option value="line">Line</option>
          <option value="point" selected="selected">Point</option>
        </select>
        <br />
        <label>Max Angle: </label>
        <select id="polygons-maxangle">
          <option value="0.7853981633974483" selected="selected">45°</option>
          <option value="2.0943951023931953">120°</option>
          <option value="6.283185307179586">360°</option>
        </select>
        <br />
        <label>Exceed Len: </label>
        <select id="polygons-overflow">
          <option value="true">True</option>
          <option value="false" selected="selected">False</option>
        </select>
        <br />
        <label>Size: </label>
        <input type="text" value="10px" id="polygons-size" />
        <br />
        <label>Offset X:</label>
        <input type="text" value="0" id="polygons-offset-x" />
        <br />
        <label>Offset Y:</label>
        <input type="text" value="0" id="polygons-offset-y" />
        <br />
        <label>Color :</label>
        <input type="text" value="blue" id="polygons-color" />
        <br />
        <label title="Outline Color">O. Color:</label>
        <input type="text" value="#ffffff" id="polygons-outline" />
        <br />
        <label title="Outline Width">O. Width :</label>
        <input type="text" value="3" id="polygons-outline-width" />
      </div>
    </div>
    <div class="clearall"></div>
    <script>
      var openSansAdded = false;

      var myDom = {
        points: {
          text: document.getElementById('points-text'),
          align: document.getElementById('points-align'),
          baseline: document.getElementById('points-baseline'),
          rotation: document.getElementById('points-rotation'),
          font: document.getElementById('points-font'),
          weight: document.getElementById('points-weight'),
          size: document.getElementById('points-size'),
          offsetX: document.getElementById('points-offset-x'),
          offsetY: document.getElementById('points-offset-y'),
          color: document.getElementById('points-color'),
          outline: document.getElementById('points-outline'),
          outlineWidth: document.getElementById('points-outline-width'),
          maxreso: document.getElementById('points-maxreso')
        },
        lines: {
          text: document.getElementById('lines-text'),
          align: document.getElementById('lines-align'),
          baseline: document.getElementById('lines-baseline'),
          rotation: document.getElementById('lines-rotation'),
          font: document.getElementById('lines-font'),
          weight: document.getElementById('lines-weight'),
          placement: document.getElementById('lines-placement'),
          maxangle: document.getElementById('lines-maxangle'),
          overflow: document.getElementById('lines-overflow'),
          size: document.getElementById('lines-size'),
          offsetX: document.getElementById('lines-offset-x'),
          offsetY: document.getElementById('lines-offset-y'),
          color: document.getElementById('lines-color'),
          outline: document.getElementById('lines-outline'),
          outlineWidth: document.getElementById('lines-outline-width'),
          maxreso: document.getElementById('lines-maxreso')
        },
        polygons: {
          text: document.getElementById('polygons-text'),
          align: document.getElementById('polygons-align'),
          baseline: document.getElementById('polygons-baseline'),
          rotation: document.getElementById('polygons-rotation'),
          font: document.getElementById('polygons-font'),
          weight: document.getElementById('polygons-weight'),
          placement: document.getElementById('polygons-placement'),
          maxangle: document.getElementById('polygons-maxangle'),
          overflow: document.getElementById('polygons-overflow'),
          size: document.getElementById('polygons-size'),
          offsetX: document.getElementById('polygons-offset-x'),
          offsetY: document.getElementById('polygons-offset-y'),
          color: document.getElementById('polygons-color'),
          outline: document.getElementById('polygons-outline'),
          outlineWidth: document.getElementById('polygons-outline-width'),
          maxreso: document.getElementById('polygons-maxreso')
        }
      };

      var getText = function(feature, resolution, dom) {
        var type = dom.text.value;
        var maxResolution = dom.maxreso.value;
        var text = feature.get('name');

        if (resolution > maxResolution) {
          text = '';
        } else if (type == 'hide') {
          text = '';
        } else if (type == 'shorten') {
          text = text.trunc(12);
        } else if (type == 'wrap' && dom.placement.value != 'line') {
          text = stringDivider(text, 16, '\n');
        }

        return text;
      };


      var createTextStyle = function(feature, resolution, dom) {
        var align = dom.align.value;
        var baseline = dom.baseline.value;
        var size = dom.size.value;
        var offsetX = parseInt(dom.offsetX.value, 10);
        var offsetY = parseInt(dom.offsetY.value, 10);
        var weight = dom.weight.value;
        var placement = dom.placement ? dom.placement.value : undefined;
        var maxAngle = dom.maxangle ? parseFloat(dom.maxangle.value) : undefined;
        var overflow = dom.overflow ? (dom.overflow.value == 'true') : undefined;
        var rotation = parseFloat(dom.rotation.value);
        if (dom.font.value == '\'Open Sans\'' && !openSansAdded) {
          var openSans = document.createElement('link');
          openSans.href = 'https://fonts.googleapis.com/css?family=Open+Sans';
          openSans.rel = 'stylesheet';
          document.getElementsByTagName('head')[0].appendChild(openSans);
          openSansAdded = true;
        }
        var font = weight + ' ' + size + ' ' + dom.font.value;
        var fillColor = dom.color.value;
        var outlineColor = dom.outline.value;
        var outlineWidth = parseInt(dom.outlineWidth.value, 10);

        return new ol.style.Text({
          textAlign: align == '' ? undefined : align,
          textBaseline: baseline,
          font: font,
          text: getText(feature, resolution, dom),
          fill: new ol.style.Fill({color: fillColor}),
          stroke: new ol.style.Stroke({color: outlineColor, width: outlineWidth}),
          offsetX: offsetX,
          offsetY: offsetY,
          placement: placement,
          maxAngle: maxAngle,
          overflow: overflow,
          rotation: rotation
        });
      };


      // Polygons
      function polygonStyleFunction(feature, resolution) {
        return new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'blue',
            width: 1
          }),
          fill: new ol.style.Fill({
            color: 'rgba(0, 0, 255, 0.1)'
          }),
          text: createTextStyle(feature, resolution, myDom.polygons)
        });
      }

      var vectorPolygons = new ol.layer.Vector({
        source: new ol.source.Vector({
          url: 'https://openlayers.org/en/v4.6.4/examples/data/geojson/polygon-samples.geojson',
          format: new ol.format.GeoJSON()
        }),
        style: polygonStyleFunction
      });


      // Lines
      function lineStyleFunction(feature, resolution) {
        return new ol.style.Style({
          stroke: new ol.style.Stroke({
            color: 'green',
            width: 2
          }),
          text: createTextStyle(feature, resolution, myDom.lines)
        });
      }

      var vectorLines = new ol.layer.Vector({
        source: new ol.source.Vector({
          url: 'https://openlayers.org/en/v4.6.4/examples/data/geojson/line-samples.geojson',
          format: new ol.format.GeoJSON()
        }),
        style: lineStyleFunction
      });


      // Points
      function pointStyleFunction(feature, resolution) {
        return new ol.style.Style({
          image: new ol.style.Circle({
            radius: 10,
            fill: new ol.style.Fill({color: 'rgba(255, 0, 0, 0.1)'}),
            stroke: new ol.style.Stroke({color: 'red', width: 1})
          }),
          text: createTextStyle(feature, resolution, myDom.points)
        });
      }

      var vectorPoints = new ol.layer.Vector({
        source: new ol.source.Vector({
          url: 'https://openlayers.org/en/v4.6.4/examples/data/geojson/point-samples.geojson',
          format: new ol.format.GeoJSON()
        }),
        style: pointStyleFunction
      });

      var map = new ol.Map({
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          }),
          vectorPolygons,
          vectorLines,
          vectorPoints
        ],
        target: 'map',
        view: new ol.View({
          center: [-8161939, 6095025],
          zoom: 8
        })
      });

      document.getElementById('refresh-points')
          .addEventListener('click', function() {
            vectorPoints.setStyle(pointStyleFunction);
          });

      document.getElementById('refresh-lines')
          .addEventListener('click', function() {
            vectorLines.setStyle(lineStyleFunction);
          });

      document.getElementById('refresh-polygons')
          .addEventListener('click', function() {
            vectorPolygons.setStyle(polygonStyleFunction);
          });


      /**
       * @param {number} n The max number of characters to keep.
       * @return {string} Truncated string.
       */
      String.prototype.trunc = String.prototype.trunc ||
          function(n) {
            return this.length > n ? this.substr(0, n - 1) + '...' : this.substr(0);
          };


      // http://stackoverflow.com/questions/14484787/wrap-text-in-javascript
      function stringDivider(str, width, spaceReplacer) {
        if (str.length > width) {
          var p = width;
          while (p > 0 && (str[p] != ' ' && str[p] != '-')) {
            p--;
          }
          if (p > 0) {
            var left;
            if (str.substring(p, p + 1) == '-') {
              left = str.substring(0, p + 1);
            } else {
              left = str.substring(0, p);
            }
            var right = str.substring(p + 1);
            return left + spaceReplacer + stringDivider(right, width, spaceReplacer);
          }
        }
        return str;
      }
    </script>
  </body>
</html>