Vue 3 + OpenLayers 的简单使用

在前端开发中,地图展示是一个常见的需求。OpenLayers 是一个功能强大的开源地图库,可以帮助我们在 Web 应用程序中展示地图并且进行交互。本文将介绍如何在 Vue 3 项目中使用 OpenLayers,让您能够轻松实现地图展示功能

步骤一:安装 OpenLayers

首先,我们需要在 Vue 3 项目中安装 OpenLayers:

npm install ol

步骤二:创建地图组件

在 Vue 3 项目中创建一个地图组件,例如Map.vue
在vue文件中创建两个图层,显示地图和地点

const tdtVectorLayer = new TileLayer({
        title: "天地图矢量图层",
        source: new XYZ({
          url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=天地图申请的key",
        })
      });
      const tdtVectorLabelLayer = new TileLayer({
        title: "天地图矢量注记图层",
        source: new XYZ({
          url: "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=天地图申请的key",
        })
      });

然后将图层添加到openlayers提供map方法中

map = new Map({
        layers: [tdtVectorLayer,tdtVectorLabelLayer],
        target: mapCon.value,
        view: new View({
          center: beijing,
          minZoom: 4,
          zoom: 8,
        }),
      });

openlayers提供有修改地图样式的方法:

geoMarker.setStyle(styles.geoMarker)
      const iconFeature = new Feature({
        geometry: new Point(beijing),
      });
      iconFeature.setStyle(createLabelStyle(iconFeature));

完整的代码:

<template>
  <div ref="mapCon" id="mapCon"></div>
</template>

<script>
import "ol/ol.css";
import { ref, onMounted } from "vue";
import { Map, View } from "ol";
import TileLayer from "ol/layer/Tile";
import XYZ from "ol/source/XYZ";
import { fromLonLat } from "ol/proj";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Feature from "ol/Feature";
import {LineString,Point } from 'ol/geom';
import { Icon, Style,Stroke,Circle,Fill } from "ol/style";
import yzm from '@/assets/stationicon.png'

export default {
  setup() {
    const mapCon = ref(null);
    const speed = ref(null);
    const animating = ref(false);
    let routeCoords;
    let routeLength;

    const beijing = fromLonLat([116.28, 39.54]);
    let map;
    let clickedPoints = [fromLonLat([116.28, 39.54])];
    const styles = {
        geoMarker: new Style({
          image: new Circle({
            radius: 7,
            snapToPixel: false,
            fill: new Fill({ color: 'black' }),
            stroke: new Stroke({
              color: 'white',
              width: 2
            })
          })
        }),
      };
    const geoMarker = new Feature({
      type: 'geoMarker',
      geometry: new Point(beijing)
    });

    onMounted(() => {
      const tdtVectorLayer = new TileLayer({
        title: "天地图矢量图层",
        source: new XYZ({
          url: "http://t0.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=天地图申请的key",
        })
      });
      const tdtVectorLabelLayer = new TileLayer({
        title: "天地图矢量注记图层",
        source: new XYZ({
          url: "http://t0.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=天地图申请的key",
        })
      });
      map = new Map({
        layers: [tdtVectorLayer,tdtVectorLabelLayer],
        target: mapCon.value,
        view: new View({
          center: beijing,
          minZoom: 4,
          zoom: 8,
        }),
      });

      const createLabelStyle = function (feature) {
        return new Style({
          image: new Icon({
            anchor: [0.5, 60],
            anchorOrigin: "top-right",
            anchorXUnits: "fraction",
            anchorYUnits: "pixels",
            offsetOrigin: "top-right",
            opacity: 0.75,
            src: yzm,
          }),
        });
      };
      geoMarker.setStyle(styles.geoMarker)
      const iconFeature = new Feature({
        geometry: new Point(beijing),
      });
      iconFeature.setStyle(createLabelStyle(iconFeature));

      const vectorSource = new VectorSource({
        features: [iconFeature,geoMarker],
      });

      const vectorLayer = new VectorLayer({
        source: vectorSource,
      });
      map.addLayer(vectorLayer);

      map.on("click", function (evt) {
        const point = evt.coordinate;
        addVectorLabel(point);
      });

      function addVectorLabel(coordinate) {
        const newFeature = new Feature({
          geometry: new Point(coordinate),
        });
        newFeature.setStyle(createLabelStyle(newFeature));
        vectorSource.addFeature(newFeature);
        clickedPoints.push(coordinate);
        const route = new LineString([clickedPoints[clickedPoints.length - 2], coordinate]);
        routeCoords = route.getCoordinates();
        routeLength = routeCoords.length;
        if (clickedPoints.length > 1) {
          // 创建折线特征,连接点击的点
          const lineStyle = new Style({
            stroke: new Stroke({
              width: 6,
              color: [237, 212, 0, 0.8]
            }),
          });
          const lineFeature = new Feature({
            geometry: route,
          });
          lineFeature.setStyle(lineStyle);
          vectorSource.addFeature(lineFeature);
        }
      }
    });
    
    


   

    return { mapCon,animating,startAnimation };
  },
};
</script>

<style>
  #menu{
    margin-bottom: 20px;
  }
 
  #mapCon {
    width: 70vw;
    height: 500px;
  }

  
</style>

本段代码主要实现在地图点击时,添加标注并给两点间连线

总结

通过以上步骤,我们成功地在 Vue 3 项目中使用 OpenLayers 来展示地图。您也可以根据自己的需求来配置地图的样式和功能,OpenLayers 提供了丰富的 API 和组件来满足各种地图展示的需求。希望本文对您有所帮助!如有任何问题或疑问,请随时联系我。祝您的地图展示功能开发顺利!🌍🚀👨‍💻

### 集成和使用OpenLayersVue3项目 #### 安装依赖库 为了能够在Vue3项目中集成并使用OpenLayers,需要安装相应的npm包。通过命令行工具执行如下指令来完成必要的软件包安装: ```bash npm install ol @types/ol vue-class-component vue-property-decorator ``` 上述命令会下载`ol`(即OpenLayers),以及TypeScript定义文件和其他辅助开发的vue组件装饰器[^1]。 #### 创建地图容器 在HTML模板内创建一个用于容纳地图显示区域的DOM元素,并赋予特定ID以便后续操作引用该节点对象: ```html <div id="map-container" style="width: 100%; height: 400px;"></div> ``` 此段代码片段展示了如何设置一个具有固定宽度和高度的地图容器样式属性[^2]。 #### 初始化Map实例 利用JavaScript初始化一个新的Map实例并与之前准备好的DOM元素关联起来,在Vue单文件组件(SFC)中的<script setup>标签下编写逻辑代码实现这一过程: ```javascript import { ref, onMounted } from &#39;vue&#39;; import Map from &#39;ol/Map.js&#39;; import View from &#39;ol/View.js&#39;; import TileLayer from &#39;ol/layer/Tile.js&#39;; import OSM from &#39;ol/source/OSM.js&#39;; export default { name: "MyComponent", setup() { let mapContainer = ref(null); const initMap = () => { new Map({ target: document.getElementById(&#39;map-container&#39;), layers: [ new TileLayer({ source: new OSM() }) ], view: new View({ center: [0, 0], zoom: 2 }) }); }; onMounted(() => { initMap(); }); return { mapContainer, }; }, }; ``` 这段脚本说明了怎样构建基本的地图视图配置参数,包括指定底图层类型(OSM在线街道地图服务), 设置初始视角位置(经纬度坐标为中心点)[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值