openlayers添加图标

<template>
  <div style="width: 100vw; height: 100vh">
    <div id="map" style="width: 100%; height: 100%"></div>
    <div class="btn">
      <el-button @click="drawPoint('点')">点</el-button>
      <el-button @click="drawPoint('线')">线</el-button>
      <el-button @click="drawPoint('圆')">圆</el-button>
      <el-button @click="drawPoint('多边形')">先用多边形绘制轨迹</el-button>
      <el-button @click="startPlayback()">再轨迹回放</el-button>
      <el-button @click="claerPlayback()">清除轨迹</el-button>
      <el-button @click="iconPicture()">添加图标</el-button>
      <el-button @click="clearDraw">清除绘画</el-button>
    </div>
  </div>
</template>
<script>
import "ol/ol.css";
import { Map, View } from "ol";
import Tile from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { fromLonLat, toLonLat } from "ol/proj";
import VectorLayer from "ol/layer/Vector"; //新的矢量层
import VectorSource from "ol/source/Vector"; //新的矢量源
import { Fill, Style, Stroke, Circle as CircleStyle } from "ol/style";
import { Draw } from "ol/interaction";
import { Point } from "ol/geom";
import { Icon } from "ol/style";
import { Feature } from "ol";
import { LineString } from "ol/geom";
export default {
  data() {
    return {
      map: null, //地图层
      routeCoords: [
        // [111.82603186264637, 40.710486885237714],
        // [112.52915686264639, 38.061789174504554],
        // [117.14341467514639, 36.52361719898482],
        // [113.62778967514637, 34.7378517903238],
        // [109.05747717514639, 34.48467564264409],
        // [106.46470373764637, 38.33806666287316],
        // [111.82603186264637, 40.710486885237714],
      ], //轨迹点,
      positionFeature: null,
      vectorLayer: null,
      vectorSource: null,
      markerData: [
        [117.02387721845294, 36.64962605644779],
        [113.57081487152016, 34.60863374696412],
        [109.14112883050537, 34.234598491028024],
        [106.62981076000882, 29.406265268189983],
        [104.01385443657489, 30.614360841558195],
        [106.1763783306136, 26.82243703194456],
        [108.33890222465232, 22.73853339936997],
        [112.7685882656671, 27.906586881567918],
        [114.33816205972744, 30.584338459965608],
        [117.30291255961922, 31.6295503813042],
        [119.9886277183447, 30.25347961013422],
        [121.66283976534244, 31.30229647231441],
        [117.02387721845294, 36.64962605644779],
      ],
    };
  },
  methods: {
    //初始化默认地图
    createMap() {
      this.map = new Map({
        target: "map",
        layers: [
          new Tile({
            source: new XYZ({
              url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
            }),
          }),
          this.initDrawLayers(),
        ],
        view: new View({
          center: fromLonLat([116.40387397, 39.91488908]),
          zoom: 5,
          maxZoom: 20,
          minZoom: 3,
          projection: "EPSG:3857",
        }),
      });
    },
    iconPicture() {
      // // 创建一个矢量图层
      // const vectorSource = new VectorSource();

      // // 创建多个标记点的Feature
      // const features = [
      //   new Feature({
      //     geometry: new Point(fromLonLat([0, 0])), // 图标坐标1
      //   }),
      //   new Feature({
      //     geometry: new Point(fromLonLat([10, 10])), // 图标坐标2
      //   }),
      //   new Feature({
      //     geometry: new Point(fromLonLat([20, 20])), // 图标坐标3
      //   }),
      // ];
      // console.log(features,121212)
      // // 设置图标样式
      // features.forEach((feature) => {
      //   feature.setStyle(
      //     new Style({
      //       image: new Icon({
      //         src: require("../assets/img/armyC.png"), // 图标路径
      //         scale: 0.1, // 缩放图标大小
      //         anchor: [0.5, 1], // 锚点
      //       }),
      //     })
      //   );
      //   vectorSource.addFeature(feature);
      // });
      // // 创建矢量图层
      // this.iconVectorLayer = new VectorLayer({
      //   source: vectorSource,
      // });
      const vectorSource = new VectorSource();

      // 遍历markerData数组,动态添加图标
      this.markerData.forEach((marker) => {
        const feature = new Feature({
          geometry: new Point(fromLonLat(marker)),
        });

        feature.setStyle(
          new Style({
            image: new Icon({
              src: require("../assets/img/demo.png"),
              scale: 0.1,
              anchor: [0.5, 1],
            }),
          })
        );

        vectorSource.addFeature(feature);
      });

      this.iconVectorLayer = new VectorLayer({
        source: vectorSource,
      });
      console.log(this.map, 4545);
      this.map.addLayer(this.iconVectorLayer);
      //   this.map.layers.push(this.iconVectorLayer)
    },
    // 增加点
    initDrawLayers() {
      let drawLayers = new VectorLayer({
        source: new VectorSource(),
        style: new Style({
          //填充 设置矢量特征的填充样式
          fill: new Fill({
            color: "rgba(255, 255, 255, 0.2)",
          }),

          //画   线条时的线条的颜色
          stroke: new Stroke({
            color: "blue",
            width: 2,
          }),

          //绘制点的颜色
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: "green",
            }),
          }),
        }),
      });
      return drawLayers;
    },

    //绘制
    drawPoint(drawType) {
      let type = "";
      switch (drawType) {
        case "点":
          type = "Point";
          break;
        case "线":
          type = "LineString";
          break;
        case "圆":
          type = "Circle";
          break;
        case "多边形":
          type = "Polygon";
          break;
        default:
          break;
      }

      if (this.draw) {
        this.map.removeInteraction(this.draw); //removeInteraction 删除交互
      }
      this.draw = new Draw({
        source: this.map.getLayers().array_[1].getSource(),
        type,
      });
      this.map.addInteraction(this.draw); // this.map.addInteraction 设置交互
      // 监听draw事件来获取点的坐标
      this.draw.on("drawend", (event) => {
        // alert(1);
        const geometry = event.feature.getGeometry();
        const coordinates = geometry.getCoordinates()[0];
        console.log(coordinates);
        // 转换所有顶点为经纬度
        const lonLatCoordinates = coordinates.map((coord) => toLonLat(coord));
        console.log("多边形顶点的经纬度:", lonLatCoordinates);

        // 将经纬度存储在数组中
        this.routeCoords = lonLatCoordinates;
        console.log("所有多边形的经纬度:", this.routeCoords);

        // // 清除画笔
        // this.map.removeInteraction(this.draw)
        // this.map.removeInteraction(this.map)
        // const geometry = event.feature.getGeometry();
        // if (geometry instanceof Point) {
        //   const coord = geometry.getCoordinates();
        //   console.log('点的坐标:', coord);
        // }
      });
    },
    //清除轨迹
    claerPlayback() {
      this.routeCoords = [];
      if (this.vectorSource) {
        this.vectorSource.clear();
      }
      if (this.vectorLayer) {
        this.vectorLayer.getSource().clear(); //清除轨迹特征
      }
      if (this.iconVectorLayer) {
        this.iconVectorLayer.getSource().clear(); //清除图标
      }
    },
    // 绘制轨迹
    drawRoute() {
      console.log(this.routeCoords, "thisrouteCoords");
      const route = new LineString(
        this.routeCoords.map((coord) => fromLonLat(coord)) // 转换经纬度为地图坐标
      );
      console.log(route, "route");
      // 设置轨迹样式
      const routeFeature = new Feature({
        geometry: route,
      });

      const routeStyle = new Style({
        stroke: new Stroke({
          width: 3,
          color: [0, 0, 255, 0.8],
        }),
      });

      routeFeature.setStyle(routeStyle);

      this.vectorSource = new VectorSource({
        features: [routeFeature],
      });

      this.vectorLayer = new VectorLayer({
        source: this.vectorSource,
      });

      this.map.addLayer(this.vectorLayer);

      // 创建当前位置的点
      this.positionFeature = new Feature({
        geometry: new Point(fromLonLat(this.routeCoords[0])),
      });

      const positionStyle = new Style({
        image: new Icon({
          src: "https://openlayers.org/en/latest/examples/data/icon.png",
          scale: 0.5,
        }),
      });

      this.positionFeature.setStyle(positionStyle);
      this.vectorSource.addFeature(this.positionFeature);
    },
    // 开始轨迹回放
    startPlayback() {
      this.drawRoute();
      // this.map.getLayers().array_[1].getSource().clear();

      let index = 0;

      const moveFeature = () => {
        if (index < this.routeCoords.length) {
          const newCoords = fromLonLat(this.routeCoords[index]);
          this.positionFeature.getGeometry().setCoordinates(newCoords);
          this.map.getView().setCenter(newCoords);
          index++;
          // 使用定时器或 requestAnimationFrame 实现平滑动画
          setTimeout(moveFeature, 1000); // 每秒移动一次
        }
      };

      moveFeature();
    },
    //清除会话
    clearDraw() {
      //采取链式操作 减少多余代码显示
      this.map.getLayers().array_[1].getSource().clear();
    },
  },
  mounted() {
    this.createMap();
  },
};
</script>

<style scoped>
.btn {
  position: fixed;
  top: 10px;
  right: 10px;
}
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值