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 }) });
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); });});