OpenLayers 加载 pbf数据教程

444 阅读1分钟

本文带你使用OpenLayers 加载 pbf数据,话不多说,直接上代码

import "ol/ol.css";
import VectorTileLayer from "ol/layer/VectorTile";
import VectorTileSource from "ol/source/VectorTile";
import MVT from "ol/format/MVT";
import { Fill, Stroke, Style } from "ol/style";

export function initMapWithGeoServer(map) {
  const vectorTileLayer = new VectorTileLayer({
    source: new VectorTileSource({
      format: new MVT(),
      url: "http://你的地址/{z}/{x}/{y}.pbf",
      maxZoom: 14,
      minZoom: 0,
      projection: "EPSG:3857" // 改为 3857,与地图一致
    }),
    style: function (feature) {
      // console.log(feature.properties_);
      const properties = feature.getProperties();
      // 根据属性值设置不同的颜色
      let strokeColor = "#fff";
      let fillColor = "rgba(0, 153, 255, 0.3)";
      console.log(properties);
   
      return new Style({
        fill: new Fill({ color: fillColor }),
        stroke: new Stroke({
          color: strokeColor,
          width: 1 // 根据属性设置线宽
        })
      });
    }
  });

  map.addLayer(vectorTileLayer);
}

踩坑记录

❌ 坑点一:投影不兼容导致图层不显示

通常会看到控制台报这个错误。A VectorTile source can only be rendered if it has a projection compatible with the view projection

✅ 原因分析

OpenLayers 中,VectorTileSourceprojection 必须与 Viewprojection 保持一致,否则无法渲染图层。

❌ 坑点二:PDF文件404

✅ 原因分析

注意看z/x/y有没有错误。在不同坐标系下可能会出现不对的情况。需要调整合适的坐标系去转换