# 地图画路径
<template>
<div id="content">
<div id="map" ref="map" />
</div>
</template>
<script setup>
import { onMounted, ref } from 'vue'
import "ol/ol.css";
import { Map, Feature, View } from "ol";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Stroke, Icon } from "ol/style";
import { LineString, Point, Polygon,MultiPoint } from "ol/geom";
import {
overlay
} from './mapconfig.js'
// 一段经纬度数据
import trackCar from "@/mock/track-car.json";
import marker1 from '../../assets/markers/marker1.png'
import marker from '../../assets/markers/marker.jpg'
import marker2 from '../../assets/markers/marker2.png'
let map = ref(null)
let trackLayer = ref(null)
const addTrack = () => {
// 根据经纬度点位创建线
var routeFeature = new Feature({
type: "route",
geometry: new LineString(trackCar)
});
// 创建开始图标
const startMarker = new Feature({
type: "startMarker",
geometry: new Point(trackCar[0])
});
// 创建中途图标
const centerMarker = new Feature({
type: "centerMarker",
geometry: new MultiPoint([trackCar[1],trackCar[2]])
});
// 创建结束图标
const endMarker = new Feature({
type: "endMarker",
geometry: new Point(trackCar[trackCar.length - 1])
});
// 设置样式
var styles = {
// 如果类型是 route 的样式
route: new Style({
stroke: new Stroke({
width: 2, //线的宽度
color: "#ffc641", //线的颜色
}),
}),
// 如果类型是 geoMarker 的样式
startMarker: new Style({
image: new Icon({
src: marker1,
anchor: [0.5, 1.1], // 设置偏移
scale: .1
}),
}),
centerMarker: new Style({
image: new Icon({
src: marker,
anchor: [0.5, 1.1], // 设置偏移
scale: .1
}),
}),
endMarker: new Style({
image: new Icon({
src: marker2,
anchor: [0.5, 1.1], // 设置偏移
scale: .1
}),
}),
};
// 把小车和线添加到图层
trackLayer.value = new VectorLayer({
source: new VectorSource({
features: [routeFeature, startMarker, centerMarker, endMarker],
}), //线,起点的图标,终点的图标
style: function (feature) {
return styles[feature.get("type")];
},
zIndex: 2, // 图层层级
});
}
/**
* 初始化一个 openlayers 地图
*/
const initMap = () => {
const target = "map"; // 跟页面元素的 id 绑定来进行渲染
map.value = new Map({
target: target, // 绑定dom元素进行渲染
layers: [overlay, trackLayer.value], // 配置地图数据源
view: new View({
projection: "EPSG:4326",
center: [104.03228760, 30.72147313], // 地图中心点
minZoom: 12, // 地图缩放最小级别
maxZoom: 18, // 地图缩放最大级别
zoom: 14, // 地图缩放级别(打开页面时默认级别)
}),
});
map.value.getView().fit(new Polygon([trackCar]), {
padding: [100, 100, 100, 100],
}); //设置地图的缩放距离离屏幕的大小
}
onMounted(() => {
addTrack()
initMap()
})
</script>
<style lang="scss" scoped>
#map {
width: 100vw;
height: 100vh;
}
</style>
[
[
104.033308,
30.673237
],
[
104.034432,
30.672982
],
[
104.037722,
30.671978
],
[
104.037828,
30.670244
]
]