openlayers的基本使用

1、环境构建

yarn add ol

2、引入文件(按需引入)

import "ol/ol.css";
import { Map, View } from "ol";
import * as olProj from "ol/proj";
import { Vector as VectorLayer, Tile } from "ol/layer";
import Feature from "ol/Feature";
import { Point } from "ol/geom";
import { XYZ, Vector as VectorSource } from "ol/source";
import { Style, Icon, Fill, Stroke, Text } from "ol/style";
import GeoJSON from "ol/format/GeoJSON";

3、初始化地图
    // 初始化一个 openlayers 地图
      let rasterLayer = new Tile({
        source: new XYZ({
          url: "gis2d/terrain/{z}/{x}/{y}.jpg"
        })
      });
      this.map = new Map({
        target: "map",
        layers: [rasterLayer],
        view: new View({
          center: olProj.transform(
            [103.879389, 37.42613],
            "EPSG:4326",
            "EPSG:3857"
          ),
          minZoom: 3,
          zoom: 4,
          maxZoom: 5
        })
      });

openlayers的基本使用_第1张图片

4添加marker图标和文字
zoom可以用来控制层级显示
feature.setStyle 设置marker的样式及图标
this.$http.get("/json/feature.json", {}).then(res => {
   res.data.forEach(item => {
       let feature = new Feature({
        pointType: "station",
        geometry: new Point(olProj.fromLonLat([item.X, item.Y])) // 标签位置
      });
      feature.setStyle([
        new Style({
          image: new Icon({
            anchor: [0.5, 19],
            anchorYUnits: "pixels",
            src: require("@/assets/img/star.png")
          })
        }),
        new Style({
          image: new Icon({
            anchor: [0.5, 36],
            anchorYUnits: "pixels",
            src: require("@/assets/img/down.png")
          })
        }),
        new Style({
          text: new Text({
            text: item.stationName,//marker文本
            font: "14px Microsoft YaHei",
            offsetY: "15",
            fill: new Fill({
              color: "#fff"
            }),
            stroke: new Stroke({
              color: "#000",
              width: 2
            })
          })
        }),
        new Style({
          text: new Text({
            text: item.stationName + "战区",//marker提示
            font: "14px Microsoft YaHei",
            offsetY: "-45",
            padding: [5, 10, 5, 10],
            backgroundFill: new Fill({
              color: "#fff"//提示背景色
            }),
            fill: new Fill({
              color: "#000"
            })
          })
        })
      ]);
      feature.setId(item.id); // 设置ID
      let source = new VectorSource({}); // 初始化矢量数据源
      source.addFeature(feature); // 将标签要素添加至矢量数据源
      let pointLayer = new VectorLayer({
        source: source,
        minZoom: 3,//最小层数
        zoom: 3,
        maxZoom: 4//最大层数
        // name: "pointLayer"
      });
      this.map.addLayer(pointLayer);
   });
});

openlayers的基本使用_第2张图片

你可能感兴趣的:(openlayers)