uniapp使用render.js和Leaflet进行数据通信和地图加载

1.render.js
render.js 是 Uniapp 框架中用于在视图层运行的JS库,相较于WXS(微信脚本,微信小程序提供的一种基于JavaScript的脚本语言),它更具有易用性和强大的功能。

render.js在Uniapp中的主要作用包括:

  1. 用于高效绘制复杂的用户界面。它能直接在View层进行复杂的操作,这样可以有效降低逻辑层与视图层之间的通信成本,从而提高应用的渲染性能。在处理需要呈现大量动态组件相关的地图类功能时,这一功能尤为有用。

  2. 作为应用程序逻辑层和视图层之间数据传输的"桥梁"。这件事对于保持前端界面的响应性和交互性,同时确保在后端成功执行数据逻辑和操作而言至关重要。你可以使用callMethod从视图传递数据到逻辑层。

值得注意的是,render.js主要支持app-vue和h5,对其它框架或平台可能适应性不强。

2.Leaflet
Leaflet是一个开源的地图JavaScript库,它特别适合用于移动设备,具有互动性强,性能好,可轻松扩展等特点。

以下是Leaflet一些主要的特点:

  1. 轻量级: Leaflet核心库只有约38KB,但却提供了大部分开发地图时所需的特性。

  2. 兼容性: Leaflet完成兼容所有主要的桌面和移动平台,使用HTML5和CSS3的最佳特性提供了各种高级地图特性。

  3. 可扩展性: Leaflet设计上充分考虑了易用性和扩展性,你可以非常容易地创建自己的插件和在地图上实现个性化功能。

如何使用Leaflet:

  1. 首先在HTML中定义一个用来显示地图的div元素,如

    。在Vue等框架中,可以在模板部分定义这个元素。

  2. 然后在脚本部分,通过Leaflet的L.map方法创建一个地图实例,并通过setView方法设置地图的中心位置和初始缩放级别,如var map = L.map(‘map’).setView([51.505, -0.09], 13);。

  3. 接着你可以添加各种图层到地图上,如标题图层,标记,折线,多边形等。如L.marker([51.5, -0.09]).addTo(map).bindPopup(‘A pretty CSS3 popup.
    Easily customizable.’).openPopup();。

  4. 你也可以绑定事件监听器来实现用户交互,如点击,缩放,鼠标悬停等。

注意:

  • 使用Leaflet时需要首先把Leaflet的样式表和脚本文件引入到你的页面。

  • Leaflet创建的地图默认占据其所在元素的整个区域,所以你需要为你的地图div元素设置一个具体的宽度和高度,否则地图将不会显示。
    3.项目代码

<template>
	<view>
		<uni-nav-bar fixed :backgroundColor=bgColor.bg :color="bgColor.color" status-bar :shadow='false' :isRight="true"
		 left-icon="iconmenu" title="地图查看" @clickLeft="showDrawer('showLeft')">
			<view slot="right">
				<view @click="showDrawer('showRight')">
					<uni-icons class="icon" :color="bgColor.color" type="m-icon-layer" size="24" />
				</view>
			</view>
		</uni-nav-bar>
		<uni-drawer ref="showLeft" mode="left" :width="260" @change="change($event,'showLeft')"></uni-drawer>
		<m-drawer ref="showRight" mode="right" :mask-click="true" @change="change($event,'showRight')">
			<view class="scroll-view">
				<scroll-view class="scroll-view-box" scroll-y="true">
					<view class="map-page">
						<view class="top">
							<view>地图:</view>
							<view v-for="(item, index) in controlLayer" :key="index" @click="changeMap(item)">
								<view class="control" :class="{ active: activeLayer === item.layerId }">
									<view class="img">
										<image class="pic" :src="item.picSrc"></image>
									</view>
									<view>{{ item.title }}</view>
								</view>
							</view>
						</view>
						<view class="bottom">
							<view>要素:</view>
							<view class="factor">
								<view class="factor-content">
									<view>
										<uni-icons class="icon" color="#7B8896" type="m-icon-checked" size="24" />
									</view>

									<view class="title">应巡点</view>
									<switch style="transform:scale(0.7)" :checked="hasNotCheckPoint" @change="isOff('notCheckPoint')" />
								</view>
								<view class="factor-content">
									<view>
										<uni-icons class="icon" color="#208BFF" type="m-icon-checked" size="24" />
									</view>
									<view class="title">已巡点</view>
									<switch style="transform:scale(0.7)" :checked="hasCheckPoint" @change="isOff('checkPoint')" />
								</view>
								<view class="factor-content">
									<view>
										<uni-icons class="icon" color="#FF9120" type="m-icon-collection" size="24" />
									</view>
									<view class="title">采集应巡点</view>
									<switch style="transform:scale(0.7)" :checked="hasCollecCheckPoint" @change="isOff('collecCheckPoint')" />
								</view>
								<view class="factor-content">
									<view>
										<uni-icons class="icon" color="#18C26D" type="m-icon-event" size="24" />
									</view>
									<view class="title">采集事件点</view>
									<switch style="transform:scale(0.7)" :checked="hasCollecEventPoint" @change="isOff('collecEventPoint')" />
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</m-drawer>
		<view id="lmap" :style="{ height: height + 'px', width: '100%', marginTop: '10px' }" :prop="sender" :change:prop="changeData" />
		<!-- <view class="flex">
			<button type="default" class="cu-btn" @tap="leafletMap.createMarker">标记</button>
			<button type="default" class="cu-btn" @tap="leafletMap.createLine">路线</button>
			<button type="default" class="cu-btn" @tap="getLocation">定位</button>
			<button type="default" class="cu-btn" @tap="handleChange">传值</button>
		</view> -->
	</view>
</template>

<script module="leafletMap" lang="renderjs">
	import Storage from '@/common/Storage.js';
	import locationUtils from '@/common/locationUtils.js';
	import loadjs from '@/plugins/loadjs/loadjs.js'
	import {getSqliteData} from "@/common/sqlite.js"
	import {getCheckingPoint} from "@/service/getData.js"
	// import L from '@/plugins/leaflet/leaflet-src'
	// import '@/plugins/leaflet/leaflet.ChineseTmsProviders.js'
	// import '@/plugins/leaflet/leaflet-locatecontrol/src/L.Control.Locate.js'

	import {
		SENDER_EVENT
	} from './constant'
	const mapConfig = {
		MapName: "a4map", // 地图名称
		Token: '1d016abc-cf17-4801-9b5b-b43304e5bfe1', //"1d016abc-cf17-4801-9b5b-b43304e5bfe1", // 令牌
		host: 'http://a5.petrochina.com.cn:88' || '.',
		//MapUrl: "您的地图服务地址" // 地图服务地址
	};

	let map = null,
	    locateControl=null, // 地图定位控制
		notCheckPointLayer = null,
		checkPointLayer = null,
		collecCheckPointLayer = null,
		collecEventPointLayer = null
	export default {
		data() {
			return {
				mapLayer: {

				},
				marker: null,
				iconNotCheckPoint: null,
				iconCheckPoint: null,
				iconCollecCheckPoint: null,
				iconCollecEventPoint: null,
				checkPatrolPoint:[],
				notcheckPatrolPoint:[]
			}
		},
		mounted() {
			if (typeof window.L === 'object') {
				console.log('window.L')
				this.initLeaflet()
			} else {
				let _this = this
				loadjs(['static/plugins/leaflet/leaflet.js'], 'L')
				loadjs.ready('L', function() {
					loadjs(['static/plugins/leaflet/leaflet.ChineseTmsProviders.js',
					'static/plugins/leaflet/leaflet.mapCorrection.js',
					'static/plugins/leaflet/leaflet-locatecontrol/src/L.Control.Locate.js',
					'static/plugins/leaflet/markers/leaflet.iconfont-markers.js'
					], 'plugins')

					/* foo.js & bar.js loaded */
				});
				loadjs.ready('plugins', function() {
					_this.initLeaflet()
				})
				// this.loadJS("plugins/leaflet/leaflet-src.js",this.initLeaflet.bind(this))
				// // 动态引入较大类库避免影响页面展示
				// const script = document.createElement('script')
				// // view 层的页面运行在 www 根目录,其相对路径相对于 www 计算
				// script.src = 'plugins/leaflet/leaflet-src.js'
				// script.onload = this.initLeaflet.bind(this)
				// document.head.appendChild(script)
			}
			 
		},
		methods: {
			async initLeaflet() {
			   await	this.handleCreateMap()
			},
			async dealSqliteData(data,flag=false){
				try{
					let sqliteData = await getSqliteData(data)  
					if(flag === true){
						return this.dealWithPointsData(sqliteData)
					}else{
						return  this.handleIncomingData(sqliteData)
					}
				}catch(e){
					 console.log(e,'查询失败')
				} 
			},
			shouldOrcheckPatrolPoint(){
				    let self =this
				    let onGoingKey = plus.storage.getItem('eventId')
					let key = JSON.parse(onGoingKey).data.data || '' 
					if(key){
						let data ={ 
							checkRecordId:key
						}
						getCheckingPoint(data)
						.then((res)=>{   
							let data = res.result
							let dataList = data.checkPoints ||[]  
						    self.dealData(dataList) 
						}).catch((err)=>{ 
							console.log(err)
						}) 
					}else{
						uni.showToast({
							icon:'none',
							title:'当前没有正在进行的任务'
						})
					} 
			}, 
			dealData(data){ 
				let notcheckPatrolPoint =[] , checkPatrolPoint = []
				data.forEach((curr)=>{
					if(curr[2].status == "3"){
						delete curr.status
						checkPatrolPoint.push(curr)
						
					}else{
						delete curr.status
						notcheckPatrolPoint.push(curr)
						
					}
				})  
				this.checkPatrolPoint =  checkPatrolPoint 
				this.notcheckPatrolPoint =  notcheckPatrolPoint 
			},
			dealWithPointsData(sqliteData){
				let arr =[] 
				let name = ''
				if(!sqliteData ||  sqliteData.length == 0) {return arr} 
				sqliteData.forEach((curr)=>{   
					if(curr.pointName){
						name = curr.pointName  
					}
					arr.push([curr.y,curr.x,{status:curr.status,name:name}])  
				})   
				return arr
			},
			handleIncomingData(sqliteData){
				let arr =[]  
				let name = ''
				if(!sqliteData ||  sqliteData.length == 0) {return arr}
				sqliteData.forEach((curr)=>{
					if(curr.name){
						name = curr.name
					}
					if(curr.pointsName){
						name = curr.pointsName
					}
				    arr.push([curr.longitude,curr.latitude,name]) 
					// arr.push([curr.latitude,curr.longitude])
				})  
				return arr
			},
			loadSheet(path) {
				let e = document.createElement('link');
				e.rel = 'stylesheet';
				e.href = path;
				e.onload = function(ev) { 
					console.log(path + ': ' + ev.type);
					try {
						console.log('sheet.cssText.length: ' + e.sheet.cssText.length);
					} catch (err) {
						console.log('error code: ' + err.code);
					}
					console.log(ev);
				};
				e.onerror = function(ev) {
					console.log('onerror: ' + ev.type);
				};
				document.head.appendChild(e);
			},
			async handleCreateMap() {
				map = L.map('lmap', {attributionControl: false})
				map.setView([39.932873, 116.432415], 13);
				const VECMIX = L.tileLayer.chinaProvider('A4Map.VECMIX.Map', {
					key:mapConfig.Token,
					maxZoom: 18,
					// attribution:"A4Map",
				})

				const IMGMIX = L.tileLayer.chinaProvider('A4Map.IMGMIX.Map', {
					key:mapConfig.Token,
					maxZoom: 18,
					// minZoom: 5
				})
				const TERMIX = L.tileLayer.chinaProvider('A4Map.TERMIX.Map', {
					key:mapConfig.Token,
					maxZoom: 18,
					// minZoom: 5
				})
				//设置默认图层
				// this.activeLayer = "线画图";
				VECMIX.addTo(map)

				//初始化底图图层
				this.mapLayer["VECMIX"] = VECMIX
				this.mapLayer["IMGMIX"] = IMGMIX
				this.mapLayer["TERMIX"] = TERMIX
				// 初始化定位
				this.initLocate()
				//添加
				//初始化图标
				this.initIcon();
				this.initLayer();  
				this.taskEvent() 
				this.otherEvent() 
				// L.marker([ 39.905530,116.391305]).addTo(map).bindPopup('<p>我是WGS84坐标下,天安门广场国旗所在位置</p>').openPopup().flay;
				// map.flyTo([39.932991,116.430328])
			}, 
			async taskEvent(){
				let onGoingKey = plus.storage.getItem('eventId')
				let key = JSON.parse(onGoingKey).data.data || '' 
				let ponitsList= await this.dealSqliteData( SENDER_EVENT.DETAIL_POINTS + key ,true  ) 
				this.dealData(ponitsList)    
				this.initNotCheckPointLayer(this.notcheckPatrolPoint ||[])
				this.initcheckPointLayer(this.checkPatrolPoint ||[]) 
			},
			async otherEvent(){
				let pionts=  await this.dealSqliteData(SENDER_EVENT.COLLEC_BY_PATROL_DATA)
				let events= await this.dealSqliteData(SENDER_EVENT.EVENT_UPLOAD_DATA)
				this.initcollecCheckPointLayer(pionts ||[])
				this.initcollecEventPointLayer(events ||[])
			},
			initIcon() {
				this.iconNotCheckPoint = L.IconfontMarkers.icon({
					icon: 'm-icon-checked', 
					iconColor: '#7B8896'
				});
				this.iconCheckPoint = L.IconfontMarkers.icon({
					icon: 'm-icon-checked',
					iconColor: '#208BFF'
				});
				this.iconCollecCheckPoint = L.IconfontMarkers.icon({
					icon: 'm-icon-collection',
					iconColor: '#FF9120'
				});
				this.iconCollecEventPoint = L.IconfontMarkers.icon({
					icon: 'm-icon-event',
					iconColor: '#18C26D'
				});

			},
			initLayer(){
				//初始化图层
				notCheckPointLayer = L.layerGroup().addTo(map);
				checkPointLayer = L.layerGroup().addTo(map);
				collecCheckPointLayer = L.layerGroup().addTo(map);
				collecEventPointLayer = L.layerGroup().addTo(map);
				console.log(notCheckPointLayer, checkPointLayer, collecCheckPointLayer, collecEventPointLayer) 
			},
			initLocate(){
				locateControl = L.control.locate({
				    strings: {
				        title: "显示我的位置"
				    },
					icon:"m-icon m-icon-position",
					iconLoading:"m-icon m-icon-positioning",
					locateOptions: {
					    enableHighAccuracy: true
					}
				}).addTo(map);
				map.on('locationfound', function(e) { 
					console.log('locationfound',e,e.latlng)
					// console.debug(e)
				    // var radius = e.accuracy / 2;
				    // L.marker(e.latlng).addTo(map).bindPopup("你就在这个圈内");
				    // L.circle(e.latlng, radius).addTo(map);
				});
				
				map.on('locationerror', function(e) {
				  console.log('定位出错=====>', e);
				});
				// 开启定位功能
				locateControl.start();
			},  
			initNotCheckPointLayer(data){
				for (let l of data) { 
					let maker = L.marker(l, {
						icon: this.iconNotCheckPoint
					});
					notCheckPointLayer.addLayer(maker);  
					maker.openTooltip()
					maker.bindTooltip(l[2].name) 
				}
			},
			initcheckPointLayer(data){ 
				for (let l of data) { 
					let maker = L.marker(l, {
						icon: this.iconCheckPoint
					});
					checkPointLayer.addLayer(maker);
					maker.openTooltip()
					maker.bindTooltip(l[2].name)  
				}
			},
			initcollecCheckPointLayer(data){
				for (let l of data) { 
					let maker = L.marker(l, {
						icon: this.iconCollecCheckPoint
					});
					collecCheckPointLayer.addLayer(maker);
					maker.openTooltip()
					maker.bindTooltip(l[2])
				}
			},
			initcollecEventPointLayer(data){
				for (let l of data) { 
					let maker = L.marker(l, {
						icon: this.iconCollecEventPoint
					});
					collecEventPointLayer.addLayer(maker);
					maker.openTooltip()
					maker.bindTooltip(l[2])
				}
			},
			/**
			 * 切换图层
			 * */
			changeMapControl(layerId) {
				let addedLayers = [],
					removedLayers = [];
				let mapLayerKey = Object.keys(this.mapLayer)
				for (let key = mapLayerKey.length - 1; key >= 0; key--) {
					const layer = this.mapLayer[mapLayerKey[key]];
					(layerId === mapLayerKey[key]) ? addedLayers.push(layer): removedLayers.push(layer);
				}
				// Bugfix issue 2318: Should remove all old layers before readding new ones
				for (let i = 0; i < removedLayers.length; i++) {
					if (map.hasLayer(removedLayers[i])) {
						map.removeLayer(removedLayers[i]);
					}
				}
				for (let i = 0; i < addedLayers.length; i++) {
					if (!map.hasLayer(addedLayers[i])) {
						map.addLayer(addedLayers[i]);
					}
				}
				// this.activeLayer=item.title
			},
			//创建标注
			createMarker(event, ownerInstance) {  
				const pos = {
					lat: 39.93009600,
					lng: 116.42757000 
				}
				// 116.42852000    39.92897000
				if (this.marker) {
					this.marker.remove()
				}
				this.marker = L.marker({
					lat: pos.lat,
					lng: pos.lng
				})
				this.marker.addTo(map)
				map.flyTo(pos)
				this.marker.bindTooltip('测试标记')
				this.marker.openTooltip()
				this.marker.on('click', () => {
					ownerInstance.callMethod('showToast', '您点击了测试标记')
				})
			},
			//创建线
			async createLine(event, ownerInstance) {      
			     //
                const list =[[ 0.00,   0.00 ] ]
				const polyline = L.polyline(list, {
					color: 'red',
					weight: 6
				}).addTo(map);

				polyline.bindTooltip('测试路线')
				polyline.openTooltip()
				polyline.on('click', () => {
					ownerInstance.callMethod('showToast', '您点击了测试路线')
				})
				map.fitBounds(polyline.getBounds());
			},
			getLocationControl(data, ownerInstance) {
				console.log('getLocationControl 当前位置的经度:' + JSON.stringify(data));
				const {location}=data
				console.log('location',location)
				// const pos = [location.latitude,location.longitude] 
				const coordArray=locationUtils.gcj02Towgs84 (location.longitude,location.latitude)
				const pos = {
					lat: coordArray[1],
					lng: coordArray[0]
				} 
				if(!window.L){
					return
				} 
				// const pos=locationUtils.gcj02Towgs84(location.latitude,location.longitude)
				// console.log('定位转换后坐标location',pos)
				if (this.marker) {
					this.marker.remove()
				}
				let circleStyle= {
                className:   'leaflet-control-locate-circle',
                color:       'red',
                fillColor:   'red',
                fillOpacity: 0.15,
                weight:      0
				}
				this.marker=L.circle(pos, 15, circleStyle)
				// this.marker = L.marker({
				// 	lat: pos.lat,
				// 	lng: pos.lng
				// })
				this.marker.addTo(map)
				map.flyTo(pos)
				this.marker.bindTooltip('我的位置')
				this.marker.openTooltip()
				this.marker.on('click', () => {
					// "address": {
					// 	"country": "中国",
					// 	"province": "广东省",
					// 	"city": "广州市",
					// 	"district": "天河区",
					// 	"street": "渔兴路",
					// 	"streetNum": "325号",
					// 	"poiName": "广东食品药品职业学院",
					// 	"cityCode": "020"
					// }
					const {
						province,
						city,
						district,
						street,
						streetNum,
						poiName
					} = data.address
					ownerInstance.callMethod('showToast', `${province}${city}${district}${street}${streetNum}${poiName}`)
				})

			}, 
			/**
			 * @description  当页面切换时候 销毁地图定位
			 * */
			stopLoationControl(data, ownerInstance){
				console.log('stopLoationControl 取消定位')
				if(locateControl){
					locateControl.stop()
				}
				
			},
			/**
			 * 应巡点
			 * */
			async notCheckPointControl(data, ownerInstance) {
				// const {iconNotsCheckPoint}=this.this
				console.log('应巡点2', data, ownerInstance)
				console.log("应巡点2获取存储", Storage.getSync(`has${SENDER_EVENT.NOT_CHECK_POINT}`))
				data.location ? '' : data.location = this.notcheckPatrolPoint
				let {
					has,
					data: location
				} = data 
				
				if (!has) {
					notCheckPointLayer.clearLayers();
					return
				}
				//二维数组存储经纬度数据
				location = [[0.00,0.00]]  
				for (let l of data.location) {
					console.log(l)
					let maker = L.marker(l, {
						icon: this.iconNotCheckPoint
					});
					notCheckPointLayer.addLayer(maker);
				}
			 
				//清除
				// markerGroup.clearLayers();
			},
			/**
			 * 已巡点
			 * */
			checkPointControl(data, ownerInstance) {
				console.log('已巡点2', data, ownerInstance)
				data.location ? '' : data.location = this.checkPatrolPoint 
				let { has, data: location } = data  
				//二维数组存储经纬度数据
				location = [[0.00,0.00]] 
				if (!has) {
					checkPointLayer.clearLayers();
					return
				}
				for (let l of data.location) {
					console.log(l)
					let maker = L.marker(l, {
						icon: this.iconCheckPoint
					});
					checkPointLayer.addLayer(maker);
				}
			},
			/**
			 * 采集应巡点
			 * */
			async collecCheckPointControl(data, ownerInstance) {  
				data.location ? '' : data.location =  await this.dealSqliteData(SENDER_EVENT.COLLEC_BY_PATROL_DATA)
				let { has, data: location } = data  
				//二维数组存储经纬度数据
				location = [[0.00,0.00]] 
				if (!has) {
					collecCheckPointLayer.clearLayers();
					return
				}
				for (let l of  data.location) {
					console.log(l)
					let maker = L.marker(l, {
						icon: this.iconCollecCheckPoint
					});
					collecCheckPointLayer.addLayer(maker);
					maker.bindTooltip('测试标记')
				}
			},
			/**
			 * 采集事件点
			 * */
			async collecEventPointControl(data, ownerInstance) { 
				data.location ? '' : data.location =  await this.dealSqliteData(SENDER_EVENT.EVENT_UPLOAD_DATA)
				let { has, data: location } = data  
				//二维数组存储经纬度数据
				location = [[0.00,0.00]] 
				if (!has) {
					collecEventPointLayer.clearLayers();
					return
				}
				for (let l of data.location) {
					console.log(l)
					let maker = L.marker(l, {
						icon: this.iconCollecEventPoint
					});
					collecEventPointLayer.addLayer(maker);
				}
			},
			async getNewListControl(data, ownerInstance){ 
				let onGoingKey = plus.storage.getItem('eventId')
				let key = JSON.parse(onGoingKey).data.data || '' 
				let ponitsList= await this.dealSqliteData( SENDER_EVENT.DETAIL_POINTS + key ,true  ) 
				this.dealData(ponitsList)   
				this.notCheckPointControl()
				this.checkPointControl()
			},
			changeData(newValue, oldValue, ownerInstance, instance) {
				// ownerInstance.callMethod('showToast', '监测到Vue中的数据发生改变:' + JSON.stringify(newValue))
				console.log('changeData', newValue, oldValue, ownerInstance, instance)
				const {
					event,
					data
				} = newValue
				this[`${event}Control`] ? this[`${event}Control`](data, ownerInstance) : console.log("暂无该方法");
			}
		}
	}
	 
</script>

<script>
	import {mapState} from 'vuex'  
	import Storage from '@/common/Storage.js';
	import uniIcons from '@/components/uni-icons/uni-icons.vue';
	import {getSqliteData} from "@/common/sqlite.js"
	import {
		SENDER_EVENT
	} from './constant.js';
	export default {
		components: {
			uniIcons
		},
		data() {
			return {
				bgColor: {
					bg: '#208BFF',
					color: 'white'
				},
				activeLayer: 'VECMIX',
				// map: null
				controlLayer: [{
						picSrc: '/static/img/mp1.png',
						title: '线画图',
						layerId: 'VECMIX'
						// id: L.tileLayer.chinaProvider('A4Map.VECMIX.Map')
					},
					{
						picSrc: '/static/img/mp2.png',
						title: '影像图',
						layerId: 'IMGMIX'
						// id:L.tileLayer.chinaProvider('A4Map.IMGMIX.Map')
					},
					{
						picSrc: '/static/img/mp3.png',
						title: '高程图',
						layerId: 'TERMIX'
						// id:L.tileLayer.chinaProvider('A4Map.TERMIX.Map')
					}
				],
				showRight: false,
				// 是否显示应巡点
				hasNotCheckPoint: false,
				// 是否显示已巡点
				hasCheckPoint: false,
				// 是否显示采集应巡点
				hasCollecCheckPoint: false,
				// 是否显示采集事件点
				hasCollecEventPoint: false,
				height: 400,
				sender: {
					event: 'click',
					data: null
				}, 
			};
		},
		watch:{
			informListUpdate(val,newVal){ 
			     this.handleChange({
			     	event: SENDER_EVENT.GET_NEW_LIST,
			     	data: { 
			     		random: Math.round(Math.random() * 100)
			     	}
			     });
			}  
		},
		computed:{
			...mapState(['informListUpdate']), 
		}, 
		onLoad(opt) {
			console.log(opt,'页面传递值')
			// 获取屏幕高度
			const {
				windowHeight
			} = uni.getSystemInfoSync();
			this.height = windowHeight - 100;
		 // this.height = windowHeight
			//获取当前位置
			// this.getLocation();
			// 初始化数据
			this.initLocalValues(); 
		},
		onHide(opt){
			console.log('页面隐藏')
			// 取消定位
			this.handleChange({
				event: SENDER_EVENT.STOP_LOATION,
				data: { 
					// 加个随机数,使得发生改变
					random: Math.round(Math.random() * 100)
				}
			}); 
		},
		methods: { 
			getLocation() {
				// const {sender}=this
				uni.getLocation({
					geocode: true,
					type:"gcj02",
					success: res => { 
						this.handleChange({
							event: SENDER_EVENT.GET_LOCATION,
							data: {
								// title:'测试数据:' + Math.round( Math.random()* 100)
								location:res,
								// 加个随机数,使得发生改变
								random: Math.round(Math.random() * 100)
							}
						}); 
						console.log('当前位置的经度:' + res.longitude,res);
						console.log('当前位置的纬度:' + res.latitude);
					},
					fail: err => {
						// #ifdef MP-BAIDU
						if (err.errCode === 202 || err.errCode === 10003) {
							// 202模拟器 10003真机 user deny
							this.showConfirm();
						}
						// #endif
						// #ifndef MP-BAIDU
						if (err.errMsg.indexOf('auth deny') >= 0) {
							uni.showToast({
								title: '访问位置被拒绝'
							});
						} else {
							uni.showToast({
								title: err.errMsg
							});
						}
						// #endif
					}
				});
			},
			showToast(text) {
				uni.showToast({
					icon: 'none',
					title: text
				});
			},
			/**
			 * @description  消息传值发生改变
			 * @param {String} event 传递类型事件
			 * @param {Object} data 传递要发生改变的数据,注意对象设置个随机数使得它发生改变触发事件
			 * */
			handleChange({
				event = 'click',
				data = {
					title: '测试数据:' + Math.round(Math.random() * 100)
				}
			}) {
				this.sender.event = event;
				this.sender.data = data;
				console.log('handleChange', this.sender);
			},
			//切换图层
			changeMap(item) {
				this.activeLayer = item.layerId;
				this.handleChange({
					event: SENDER_EVENT.CHANGE_MAP,
					data: item.layerId
				});
			},
			// 抽屉状态发生变化触发
			change(e, type) {
				console.log((type === 'showLeft' ? '左窗口' : '右窗口') + (e ? '打开' : '关闭'));
				this[type] = e;
			},
			/**
			 * 初始化获取本地存储
			 * */
			async initLocalValues() { 
				this.hasNotCheckPoint = Storage.getSync(`has${SENDER_EVENT.NOT_CHECK_POINT}`) || true;
				this.hasCheckPoint = Storage.getSync(`has${SENDER_EVENT.CHECK_POINT}`) || true;
				this.hasCollecCheckPoint = Storage.getSync(`has${SENDER_EVENT.COLLEC_CHECK_POINT}`) || true;
				this.hasCollecEventPoint = Storage.getSync(`has${SENDER_EVENT.COLLEC_EVENT_POINT}`) || true;
			},
			async dealSqliteData(data,flag=false){
				try{
					let sqliteData = await getSqliteData(data)   
					if(flag === true){
						return this.dealWithPointsData(sqliteData)
					}else{
						return  this.handleIncomingData(sqliteData)
					}
				}catch(e){
					 console.log(e,'查询失败')
				} 
			},
			dealWithPointsData(sqliteData){
				let arr =[] 
				if(!sqliteData ||  sqliteData.length == 0) {return arr}
				sqliteData.forEach((curr)=>{  
					arr.push([curr.y,curr.x,curr.status])  
				}) 
				return arr
			},
			handleIncomingData(sqliteData){
				let arr =[]  
				if(!sqliteData ||  sqliteData.length == 0) {return arr}
				sqliteData.forEach((curr)=>{  
				    arr.push([curr.longitude,curr.latitude]) 
					// arr.push([curr.latitude,curr.longitude])
				}) 
				return arr
			},
			dealData(data){ 
				let notcheckPatrolPoint =[] , checkPatrolPoint = []
				data.forEach((curr)=>{
					if(curr[2] == "3"){
						delete curr.status
						checkPatrolPoint.push(curr)
						
					}else{
						delete curr.status
						notcheckPatrolPoint.push(curr)
						
					}
				})  
				// this.checkPatrolPoint =  checkPatrolPoint 
				// this.notcheckPatrolPoint =  notcheckPatrolPoint 
			},
			/**
			 * 应巡点
			 * */
			notCheckPoint() {
				console.log('应巡点');
				//获取应巡点数据
				let data = [{
					lat: 39.93199843306927,
					lng: 116.41083335874629
				}];  
				this.hasNotCheckPoint = !this.hasNotCheckPoint
				data = this.notcheckPatrolPoint
				this.setChangeLayer({
					has: this.hasNotCheckPoint,
					event: SENDER_EVENT.NOT_CHECK_POINT,
					data
				});
			},
			/**
			 * 已巡点
			 * */
		    async checkPoint() {
				console.log('已巡点');
				let data = [];
				this.hasCheckPoint = !this.hasCheckPoint
				data = this.checkPatrolPoint
				console.log('sqlitedata',data)
				this.setChangeLayer({
					has: this.hasCheckPoint,
					event: SENDER_EVENT.CHECK_POINT,
					data
				});
				
			},
			/**
			 * 采集应巡点
			 * */
			collecCheckPoint() {
				console.log('采集应巡点');
				//二维数组存储经纬度数据
				let data = [[0.00,0.00]] 
				this.hasCollecCheckPoint = !this.hasCollecCheckPoint
				this.setChangeLayer({
					has: this.hasCollecCheckPoint,
					event: SENDER_EVENT.COLLEC_CHECK_POINT,
					data
				});
			},
			/**
			 * 采集事件点
			 * */
			collecEventPoint() {
				console.log('采集事件点');
				let data = [];
				this.hasCollecEventPoint = !this.hasCollecEventPoint
				this.setChangeLayer({
					has: this.hasCollecEventPoint,
					event: SENDER_EVENT.COLLEC_EVENT_POINT,
					data
				});
			},
			setChangeLayer({
				has,
				event = SENDER_EVENT.NOT_CHECK_POINT,
				data = []
			}) {
				console.log("setChangeLayer", event, has, data)
				this.handleChange({
					event: event,
					data: {
						data,
						has,
						random: Math.round(Math.random() * 100)
					}
				});
				Storage.set(`has${event}`, has);
			},
			isOff(method) {
				this[method]();
			},
			showDrawer(e) {
				this.$refs[e].open();
			},
			closeDrawer(e) {
				this.$refs[e].close();
			},
			closeDrawer() {}
		},
	 
		// app端拦截返回事件 ,仅app端生效
		onBackPress() {
			if (this.showRight) {
				this.$refs.showRight.close();
				return true;
			}
		}
	};
</script>

<style scoped>
	/* @import '/plugins/leaflet/leaflet.css'; */

	.flex {
		margin-top: 10px;
		display: flex;
		flex-wrap: wrap;
		justify-content: flex-start;
	}

	.map_detail {
		flex: 1;
	}

	.top {
		display: flex;
		// align-items: center;
		justify-content: center;
		flex-direction: column;
		padding: 48rpx;
	}

	.control {
		margin: 16rpx 0;
		display: flex;
		align-items: center;
		justify-content: space-around;
		/* width: 424rpx; */
		height: 174rpx;
		background: #eaf3ff;
		border: 1px solid #dbdfe2;
		box-shadow: 0 3px 6px 0 rgba(32, 139, 255, 0.08);
		border-radius: 10px;
		border-radius: 10px;
	}

	.control.active {
		border: 1px solid #208bff;
	}

	.img {
		width: 194rpx;
		height: 120rpx;
	}

	.pic {
		width: 100%;
		height: 100%;
	}

	.bottom {
		display: flex;
		// align-items: center;
		justify-content: center;
		flex-direction: column;
		padding: 48rpx;
	}

	.factor-content {
		margin: 24rpx 0;
		display: flex;
		align-items: center;
		justify-content: space-around;
	}

	.title {
		width: 166rpx;
		height: 48rpx;
	}

	.leaflet-control-locate a {
		font-size: 1.4em;
		color: #444;
		cursor: pointer;
	}

	.leaflet-control-locate.active a {
		color: #2074b6;
	}

	.leaflet-control-locate.active.following a {
		color: #fc8428;
	}

	.leaflet-control-locate-location circle {
		animation: leaflet-control-locate-throb 4s ease infinite;
	}

	@keyframes leaflet-control-locate-throb {
		0% {
			stroke-width: 1;
		}

		50% {
			stroke-width: 3;
			transform: scale(0.8, 0.8);
		}

		100% {
			stroke-width: 1;
		}
	}
 
</style>

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
UniApp是一个基于Vue.js开发的跨平台应用框架,可以同时开发iOS、Android和Web应用。要在UniApp使用pdf.js,可以按照以下步骤进行操作: 1. 首先,需要在UniApp项目中安装pdf.js库。你可以使用npm来安装pdf.js,具体命令如下: ``` npm install pdfjs-dist ``` 2. 安装完成后,在你的Vue组件中引入pdf.js库: ```javascript import pdfjsLib from 'pdfjs-dist' ``` 3. 接下来,你可以使用pdf.js提供的API来和显示PDF文件。以下是一个简单的示例: ```javascript export default { data() { return { pdf: null, currentPage: 1, totalPages: 0 } }, mounted() { // PDF文件 this.loadPDF() }, methods: { async loadPDF() { const pdfUrl = 'path/to/your/pdf/file.pdf' // 使用pdf.jsPDF文件 const loadingTask = pdfjsLib.getDocument(pdfUrl) const pdf = await loadingTask.promise this.pdf = pdf this.totalPages = pdf.numPages // 显示第一页 this.showPage(this.currentPage) }, async showPage(pageNumber) { if (!this.pdf) return // 获取指定页的渲染对象 const page = await this.pdf.getPage(pageNumber) // 创建一个canvas元素用于渲染PDF内容 const canvas = document.createElement('canvas') const context = canvas.getContext('2d') // 设置canvas的大小 const viewport = page.getViewport({ scale: 1 }) canvas.width = viewport.width canvas.height = viewport.height // 渲染PDF内容到canvas const renderContext = { canvasContext: context, viewport: viewport } await page.render(renderContext).promise // 将canvas添到页面中显示 document.body.appendChild(canvas) } } } ``` 上述示例代码中,`loadPDF()`方法用于PDF文件,`showPage(pageNumber)`方法用于显示指定页的内容。你可以根据自己的需求进行修改和扩展。 这样,你就可以在UniApp使用pdf.js和显示PDF文件了。记得确保你已经在项目中添了对应的PDF文件,并使用正确的路径来引用它。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小纯洁w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值