vue+leaflet+element实现轨迹回放(加可控制的进度条),写一个代码实例
时间: 2024-02-01 11:01:53 浏览: 293
好的,以下是代码示例,希望能对您有所帮助:
<template>
<div class="map-container">
<el-map ref="map" :zoom="zoom" :center="center" style="height: 100%">
<el-tile-layer :url="tileLayerUrl"></el-tile-layer>
<el-polyline :path="polylinePath" :editable="editable" :weight="weight" :color="color"></el-polyline>
</el-map>
<el-slider v-model="progress" :min="0" :max="totalSeconds" :show-input="true" :disabled="!playable"></el-slider>
<el-button @click="togglePlay" :icon="playable ? playing ? 'el-icon-pause' : 'el-icon-caret-right' : 'el-icon-video-play'" :disabled="!playable"></el-button>
</div>
</template>
<script>
import { L, DomEvent } from 'leaflet';
import 'leaflet/dist/leaflet.css';
import 'leaflet-polylinedecorator';
import { ElMap, ElTileLayer, ElPolyline, ElSlider, ElButton } from 'element-ui';
export default {
name: 'TrajectoryPlayback',
components: {
ElMap,
ElTileLayer,
ElPolyline,
ElSlider,
ElButton,
},
props: {
trajectory: {
type: Array,
required: true,
},
speed: {
type: Number,
default: 100,
},
weight: {
type: Number,
default: 5,
},
color: {
type: String,
default: 'red',
},
editable: Boolean,
},
data() {
return {
playing: false,
progress: 0,
zoom: 15,
totalSeconds: 0,
tileLayerUrl: 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
center: L.latLng(30.2741, 120.1551),
};
},
computed: {
playable() {
return this.trajectory.length > 1;
},
polylinePath() {
return this.trajectory.slice(0, this.progress + 1).map((point) => L.latLng(point.lat, point.lng));
},
},
mounted() {
this.totalSeconds = this.trajectory.length - 1;
this.addPolylineDecorator();
},
methods: {
addPolylineDecorator() {
const polyline = this.$refs.map.getLayers()[1];
const arrow = L.polylineDecorator(polyline, {
patterns: [
{
offset: '50%',
repeat: 0,
symbol: L.Symbol.arrowHead({ pixelSize: 15, polygon: false, pathOptions: { stroke: true, color: this.color } })
}
]
});
arrow.addTo(this.$refs.map);
},
togglePlay() {
this.playing = !this.playing;
if (this.playing) {
this.playTrajectory();
} else {
this.pauseTrajectory();
}
},
playTrajectory() {
if (this.progress >= this.totalSeconds) {
this.progress = 0;
}
this.animate(this.trajectory[this.progress], this.trajectory[this.progress + 1]);
},
pauseTrajectory() {
clearTimeout(this.timeout);
},
animate(point1, point2) {
const duration = this.speed * (point1.distance || point1.distanceTo(point2)) / 1000;
this.$refs.map.setView([point2.lat, point2.lng], this.zoom, { animate: true, duration });
this.progress += 1;
if (this.progress < this.totalSeconds && this.playing) {
this.timeout = setTimeout(() => {
this.animate(point2, this.trajectory[this.progress + 1]);
}, duration * 1000);
} else {
this.playing = false;
}
}
},
};
</script>
阅读全文