一 、首先在uni-app项目的工作台install mapboxgl.
npm install --save mapbox-gl
二 、在场景地图页面使用mapbox,代码如下:
<template>
<view class="map-wrap">
<!-- #ifdef APP-PLUS || H5 -->
<view id="map-box"></view>
<!-- #endif -->
</view>
</template>
<script module="mapbox" lang="renderjs">
import 'mapbox-gl/dist/mapbox-gl.css';
const mapboxgl = require('!mapbox-gl/dist/mapbox-gl.js');
export default {
data() {
return {
map: null, //地图实例
timer: null,
layerServer: '',
layerUrl: {
routeLine: ''
},
routePoint: [{
title: "巡检起点",
position: [120.467024677679, 36.2589831422648],
},
{
title: "巡检终点",
position: [120.517906717829, 36.2407259217614],
}
]
}
},
mounted() {
this.initMap()
this.timer = setInterval(() => {
this.getRTP()
}, 5000)
},
onUnload() {
//注销定时器
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
},
methods: {
// 场景地图初始化
initMap() {
mapboxgl.accessToken = 'token';
this.map = new mapboxgl.Map({
container: 'map-box', // container ID
style: 'mapbox://styles/mapbox/satellite-v9', // style URL
center: [120.4890512, 36.2491455], // starting position [lng, lat]
zoom: 12 // starting zoom
});
this.map.on("load", () => {
this.imageAdd()
this.layerAdd()
});
},
// 添加图层
layerAdd() {
// 巡检轨迹路线图层
this.map.addLayer({
id: "mainPipeDown",
type: "line",
source: {
type: "geojson",
data: this.layerServer + this.layerUrl.routeLine,
},
layout: {
"line-cap": "round",
"line-join": "round",
},
paint: {
"line-color": "#2BFF09",
"line-width": 4,
},
});
// 巡检起/终点图层
this.map.addLayer({
"id": "routePoints",
"type": "symbol",
"source": {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": this.routePoint[0].position
},
"properties": {
"title": "巡检起点",
"icon": "route_start"
}
}, {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": this.routePoint[1].position
},
"properties": {
"title": "巡检终点",
"icon": "route_end"
}
}]
}
},
"layout": {
"icon-allow-overlap": true,
"icon-image": ["get", "icon"],
"icon-size": 0.4,
}
});
},
// 添加图层图片
imageAdd() {
// 巡检起点icon
this.map.loadImage("/static/Image/workbench/route_start.png", (error, image) => {
this.map.addImage("route_start", image);
});
// 巡检终点icon
this.map.loadImage("/static/Image/workbench/route_end.png", (error, image) => {
this.map.addImage("route_end", image);
});
},
// 获取当前位置的经纬度
getRTP() {
uni.getLocation({
type: 'wgs84',
success: (res) => {
console.log('当前位置的经度:' + res.longitude);
console.log('当前位置的纬度:' + res.latitude);
}
});
}
}
}
</script>
<style lang="scss">
.map-wrap {
position: relative;
min-width: 100vw;
min-height: 100vh;
}
#map-box {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
</style>
三 、页面成功加载地图,页面效果如下:
四 、这里需要注意的是:
由于mapbox中大量操作dom元素,不能直接在uni-app中直接使用,会报错误,所以必须使用uni-app提供的render.js模式。