openlayers学习笔记

四章-37-矢量标签的显示控制

2020-04-21  本文已影响0人  彩云飘过

本文基于腾讯课堂老胡的课《跟我学Openlayers--基础实例详解》做的学习笔记,使用的openlayers 5.3.x api。

源码 见 1037.html ,对应的 官网示例

image.png
<!DOCTYPE html>
<html>

<head>
  <title>矢量标签显示控制</title>
  <link rel="stylesheet" href="../include/ol.css" type="text/css" />
  <script src="../include/ol.js"></script>
</head>

<body>
  <div id="map" class="map"></div>

  <script>
    var map = new ol.Map({
      target: "map",
      view: new ol.View({
        center: [0, 0],
        zoom: 1
      })
    });

    //文字标签样式
    var labelStyle = new ol.style.Style({
      geometry: function (feature) {
        var geometry = feature.getGeometry();
        //关键代码,找到最宽的多边形,然后显示字体标签
        if (geometry.getType() == "MultiPolygon") {
          // 多个多边形要素集合中仅渲染最宽的那个
          var polygons = geometry.getPolygons();
          var widest = 0;
          for (var i = 0, ii = polygons.length; i < ii; ++i) {
            var polygon = polygons[i];
            var width = ol.extent.getWidth(polygon.getExtent());
            if (width > widest) {
              widest = width;
              geometry = polygon;
            }
          }
        }
        
        return geometry;
      },
      text: new ol.style.Text({
        font: "14px Calibri,sans-serif",
        overflow: true,
        fill: new ol.style.Fill({
          color: "#000"
        }),
        stroke: new ol.style.Stroke({
          color: "#fff",
          width: 3
        })
      })
    });
    
    //国家边界样式
    var countryStyle = new ol.style.Style({
      fill: new ol.style.Fill({
        color: "rgba(255, 255, 255, 0.6)"
      }),
      stroke: new ol.style.Stroke({
        color: "#319FD3",
        width: 1
      })
    });
    
    var style = [countryStyle, labelStyle];

    var vectorLayer = new ol.layer.Vector({
      source: new ol.source.Vector({
        url: "../data/lands.geojson",
        format: new ol.format.GeoJSON()
      }),
      style: function (feature) {
        labelStyle.getText().setText(feature.get("name"));
        return style;
      },
      declutter: true
    });

    map.addLayer(vectorLayer);


  </script>
</body>

</html>
上一篇 下一篇

猜你喜欢

热点阅读