uniapp 整合 OpenLayer3 - 全图、切换底图、导航、定位

一、全图

主要代码:

// 设置中心点
				this.map.getView().setCenter(transform([125.33,43.90], 'EPSG:4326', 'EPSG:3857'));
// 设置层级
this.map.getView().setZoom(10);

二、切换地图

主要代码 

1、定义全局对象


	    data () {
	        return {
	            map:null,
				yxt:null,// 影像图
				dzt:null,// 电子图
	            view:null,
				count:0
	        }
	    },

2、地图加载

//天地图影像
				const tdtYX = new TileLayer({
				  source: new XYZ({
				    url: 'http://t2.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=cef191b507ff5cb698811cd8a9b11ca0',
				    projection: 'EPSG:3857',
				    crossOrigin: '*',
				  }),
				  visible:true,
				})
                // 全局赋值
				this.yxt = tdtYX;
				
				
				//天地图电子地图
				const tdtDZ = new TileLayer({
				  source: new XYZ({
				    url: 'http://t2.tianditu.gov.cn/DataServer?T=vec_w &x={x}&y={y}&l={z}&tk=cef191b507ff5cb698811cd8a9b11ca0',
				    projection: 'EPSG:3857',
				  }),
				  visible:true,
				})
                // 全局赋值
				this.dzt = tdtDZ;
				
				//天地图标注
				const tdtBZ = new TileLayer({
				  source: new XYZ({
				    url: 'http://t2.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=cef191b507ff5cb698811cd8a9b11ca0',
				    projection: 'EPSG:3857',
				  }),
				   visible:true,
				})
			
				this.map = new Map({
				  target: 'map',
				  layers: [tdtYX,tdtDZ,tdtBZ],//[tdtYX, tdtBZ],
				  view: new View({
				    projection: 'EPSG:3857',
				    center: transform([125.33,43.90], 'EPSG:4326', 'EPSG:3857'),
				    // center: [125.33,43.90],
				    zoom: 10,
				   minZoom: 0,// 最小缩放级别
				   maxZoom: 18, //最大缩放级别
				   constrainResolution: true,// 因为存在非整数的缩放级别,所以设置该参数为true来让每次缩放结束后自动缩放到距离最近的一个整数级别,这个必须要设置,当缩放在非整数级别时地图会糊
					enableRotation: false,// 禁止地图旋转
				  }),
				  controls:defaultControls({
					  zoom:false,//不显示放大放小按钮
					  rotate:false,// 不显示指北针控件
					  attribution:false//不显示右下角的地图信息控件
				  }).extend([
					// 比例尺
					new ScaleLine({
						//设置比例尺单位,degrees、imperial、us、nautical、metric(度量单位)
						units: "metric"
					})
				  ])
				})
				

3、设置图层显隐

valueChange(newValue, oldValue, ownerInstance, instance){
				console.log(newValue, oldValue, ownerInstance, instance);
				
				const olType = newValue.type;// 类型
				const olFlag = newValue.flag;// 布尔值
				// 定位
				this.goToExtent();
				switch(olType){
					case "LAYER_TITLE":// 底图切换
						//console.log("Layer",this.map.getLayers)
						if(olFlag){
							this.yxt.setVisible(true);
							this.dzt.setVisible(false);
						}else{
							this.yxt.setVisible(false);
							this.dzt.setVisible(true);
						}
					break;
				}
				
			},

三、导航

主要代码:

/**
			  * 点击事件-导航
			  * */
			 async navigation(){
				 const _this = this;
				 
				 await _this.mySelfLocation();
				 
				 // 判断系统安装的地图应用有哪些, 并生成菜单按钮
				 let _mapName = [{
				 		title: '高德地图',
				 		name: 'amap',
				 		androidName: 'com.autonavi.minimap',
				 		iosName: 'iosamap://'
				 	},
				 	{
				 		title: '百度地图',
				 		name: 'baidumap',
				 		androidName: 'com.baidu.BaiduMap',
				 		iosName: 'baidumap://'
				 	},
				 	{
				 		title: '腾讯地图',
				 		name: 'qqmap',
				 		androidName: 'com.tencent.map',
				 		iosName: 'qqmap://'
				 	},
				 ]
				 // 根据真机有的地图软件 生成的 操作菜单
				 let buttons = []
				 let platform = uni.getSystemInfoSync().platform
				 platform === 'android' && _mapName.forEach(item => {
				 	if (plus.runtime.isApplicationExist({
				 			pname: item.androidName
				 		})) {
				 		buttons.push(item)
				 	}
				 })
				 if (buttons.length) {
				 	plus.nativeUI.actionSheet({ //选择菜单
				 		title: "选择地图应用",
				 		cancel: "取消",
				 		buttons: buttons
				 	}, function(e) {
				 		let _map = buttons[e.index - 1]
				 		console.log("_map",_map)
						console.log("platform",platform)
				 		_this.openURL(_map, platform)
				 	})
				 } else {
				 	uni.showToast({
				 		title: '请安装地图软件',
				 		icon: 'none'
				 	})
				 	return
				 }
				 
			  },
			  // 打开第三方程序实际应用
			  openURL(map, platform) {
				console.log("2222")
			  	const arr = wgs84_to_gcj02(this.startposition.lng, this.startposition.lat)
			  	let _defaultUrl = {
			  		android: {
			  			"amap": `amapuri://route/plan/?dlat=${this.startposition.lat}&dlon=${this.startposition.lng}&dev=1&t=0`,
			  			'qqmap': `qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=${arr[1]},${arr[0]}&referer=JFNBZ-QLUWZ-MCPXU-76U2T-E5HPQ-AFB2G`,
			  			'baidumap': `baidumap://map/direction?origin=${this.selfLocation.latitude},${this.selfLocation.longitude}&destination=${this.startposition.lat},${this.startposition.lng}&coord_type=wgs84&src=andr.baidu.openAPIdemo`
			  		},
			  	}
			  	let newurl = encodeURI(_defaultUrl[platform][map.name]);
				
			  	console.log("newurl", newurl)
				
			  	plus.runtime.openURL(newurl, function(res) {
			  		console.log(res)
			  		uni.showModal({
			  			content: res.message
			  		})
			  	}, map.androidName ? map.androidName : '');
				
			  },

 四、定位

主要代码:

renderLocation(longitude,latitude){
				const geom = transform([longitude,latitude], 'EPSG:4326', 'EPSG:3857');
				
				// 设置中心点定位
				this.map.getView().setCenter(geom);
				// 设置层级
				this.map.getView().setZoom(18);
				
				// 绘制点
				const locationPoint = new Point(geom);
				// 清除绘制点图层
				this.map.removeLayer(this.locationLayer); 
				
				// 绘制定位点
				// 设置点特征(Feature)
				const pointFeature = new Feature({
					title:"point",
					geometry:locationPoint
				});
				
				// 设置特征样式(style)
				pointFeature.setStyle(
					new Style({
						 // 使用 CircleStyle 创建一个圆形的点
						 image:new CircleStyle({
							 // 点样式
							 fill:new Fill({
								 //color:"red",// 颜色
								 color: 'rgba(255,0,0,0.4)',
							 }),
							 // 点周边样式
							 stroke:new Stroke({
								color: '#3399CC',
								width: 1.25, 
							 }),
							 radius:7,// 半径
						 }),
					})
				);
				// 创建和添加特征到源(Source)
				// VectorSource表示一个矢量要素源,它用于存储和显示地理数据。
				const source = new VectorSource();
				source.addFeature(pointFeature);
				// 创建图层并设置源(Layer)
				// VectorLayer表示一个矢量图层,它由一系列矢量要素(Feature)组成,用于在地图上显示地理数据。
				this.locationLayer = new VectorLayer();
				this.locationLayer.setSource(source);
				this.map.addLayer(this.locationLayer);
				
			},

整体代码:

<template>
	<!-- 监听变量 operation 的变化,operation 发生改变时,调用 openlayers 模块的 loadOperation 方法 -->
	<view :operation="valueChangeSign" :change:operation="ol.valueChange" type="default"></view>
	<view class="map" id="map">
		<!--右侧按钮-->
		<view class="right-vertical-button">
			<!-- 切换图层按钮 -->
			<button @click="switchLayer()" class="btn" type="primary">{{baseLayerTitle}}</button>
			<!-- 全图按钮 -->
			<button @click="allMap()" class="btn" type="primary">全图</button>
			<!-- 导航按钮 -->
			<button @click="navigation()" class="btn" type="primary">导航</button>
		</view>
		<view class="bottom-horizontal-button">
			<button @click="location()" class="btn" type="primary">定位</button>
		</view>
	</view>
</template>
 
<!-- 逻辑层 -->
<script>
import {wgs84_to_gcj02} from '@/utils/coordinate_transformation.js'

	export default {
		data(){
			return {
				valueChangeSign:{
					latitude:null,//当前位置的纬度
					longitude:null,//当前位置的经度
					switchLayerFlag:false,// 切换图层标记
					flag:false,// 标记
					type:""// 类型
				},
				map:null,
				total:0,
				baseLayerTitle:"影像",
				// 要去到地坐标点
				startposition: {
					lng: 125.334145,
					lat: 43.960569
				},
				selfLocation:{
					latitude:null,//当前位置的纬度
					longitude:null//当前位置的经度
				}
			}
		},
		methods:{
			/**
			 * 点击事件-切换底图
			 */
			switchLayer(){
				this.valueChangeSign.type = "LAYER_TITLE"
				this.valueChangeSign.switchLayerFlag = !this.valueChangeSign.switchLayerFlag;
				if(this.valueChangeSign.switchLayerFlag){
					this.baseLayerTitle = "电子"
				}else{
					this.baseLayerTitle = "影像"
				}
			},
			/**
			 * 点击事件-全图
			 * */
			 allMap(){
				this.valueChangeSign.type= "ALL_MAP"
				this.valueChangeSign.flag = !this.valueChangeSign.flag
			 },
			 /**
			  * 获取本机经纬度方法
			  * */
			  mySelfLocation(){
				// 获取经纬度
				uni.getLocation({
					type: 'wgs84 ',
					success: (res) => {
						//console.log(res)
						this.selfLocation.latitude = res.latitude//当前位置的纬度
						this.selfLocation.longitude = res.longitude//当前位置的经度
					}
				});  
			  },
			 /**
			  * 点击事件-导航
			  * */
			 async navigation(){
				 const _this = this;
				 
				 await _this.mySelfLocation();
				 
				 // 判断系统安装的地图应用有哪些, 并生成菜单按钮
				 let _mapName = [{
				 		title: '高德地图',
				 		name: 'amap',
				 		androidName: 'com.autonavi.minimap',
				 		iosName: 'iosamap://'
				 	},
				 	{
				 		title: '百度地图',
				 		name: 'baidumap',
				 		androidName: 'com.baidu.BaiduMap',
				 		iosName: 'baidumap://'
				 	},
				 	{
				 		title: '腾讯地图',
				 		name: 'qqmap',
				 		androidName: 'com.tencent.map',
				 		iosName: 'qqmap://'
				 	},
				 ]
				 // 根据真机有的地图软件 生成的 操作菜单
				 let buttons = []
				 let platform = uni.getSystemInfoSync().platform
				 platform === 'android' && _mapName.forEach(item => {
				 	if (plus.runtime.isApplicationExist({
				 			pname: item.androidName
				 		})) {
				 		buttons.push(item)
				 	}
				 })
				 if (buttons.length) {
				 	plus.nativeUI.actionSheet({ //选择菜单
				 		title: "选择地图应用",
				 		cancel: "取消",
				 		buttons: buttons
				 	}, function(e) {
				 		let _map = buttons[e.index - 1]
				 		console.log("_map",_map)
						console.log("platform",platform)
				 		_this.openURL(_map, platform)
				 	})
				 } else {
				 	uni.showToast({
				 		title: '请安装地图软件',
				 		icon: 'none'
				 	})
				 	return
				 }
				 
			  },
			  // 打开第三方程序实际应用
			  openURL(map, platform) {
				console.log("2222")
			  	const arr = wgs84_to_gcj02(this.startposition.lng, this.startposition.lat)
			  	let _defaultUrl = {
			  		android: {
			  			"amap": `amapuri://route/plan/?dlat=${this.startposition.lat}&dlon=${this.startposition.lng}&dev=1&t=0`,
			  			'qqmap': `qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=${arr[1]},${arr[0]}&referer=JFNBZ-QLUWZ-MCPXU-76U2T-E5HPQ-AFB2G`,
			  			'baidumap': `baidumap://map/direction?origin=${this.selfLocation.latitude},${this.selfLocation.longitude}&destination=${this.startposition.lat},${this.startposition.lng}&coord_type=wgs84&src=andr.baidu.openAPIdemo`
			  		},
			  	}
			  	let newurl = encodeURI(_defaultUrl[platform][map.name]);
				
			  	console.log("newurl", newurl)
				
			  	plus.runtime.openURL(newurl, function(res) {
			  		console.log(res)
			  		uni.showModal({
			  			content: res.message
			  		})
			  	}, map.androidName ? map.androidName : '');
				
			  },
			 /**
			  * 点击事件-定位
			  * */
			  location(){
				  this.valueChangeSign.type= "LOCATION"
				  this.valueChangeSign.flag = !this.valueChangeSign.flag
				  
				  this.mySelfLocation();
				  
				  // 传递给renderj模块
				  this.valueChangeSign.latitude = this.selfLocation.latitude
				  this.valueChangeSign.longitude = this.selfLocation.longitude
				
			  },
			/**
			 * 接受renderjs传过来的数据
			*/
		   reciveMessage(data){
			   this.total = data;
			   console.log("total",this.total);
		   },
		   receiveMethod(){
			   console.log("获取方法");
		   }
		}
	}
</script>
 
<!-- 视图层 -->
<script module="ol" lang="renderjs" type="module">
//import 'ol/ol.css'// 真机-样式需要放在App.vue下面的style标签中,全局引用
import Map from 'ol/Map.js'  // OpenLayers的主要类,用于创建和管理地图  
import View from 'ol/View.js'  // OpenLayers的视图类,定义地图的视图属性 
import TileLayer from 'ol/layer/Tile.js'// OpenLayers的瓦片图层类   
import olsourceOSM from 'ol/source/OSM.js'
import {get as getProjection} from 'ol/proj.js';
import XYZ from 'ol/source/XYZ.js'
import Feature from 'ol/Feature.js'  // OpenLayers的要素类,表示地图上的一个对象或实体          
import Point from 'ol/geom/Point.js'  // OpenLayers的点几何类,用于表示点状的地理数据        
import { Vector as VectorLayer } from 'ol/layer.js'  // OpenLayers的矢量图层类,用于显示矢量数据        
import { Vector as VectorSource } from 'ol/source.js'  // OpenLayers的矢量数据源类,用于管理和提供矢量数据       
import { Circle as CircleStyle, Style, Stroke, Fill, Icon } from "ol/style.js"  // OpenLayers的样式类,用于定义图层的样式,包括圆形样式、基本样式、边框、填充和图标      
import { ScaleLine, defaults as defaultControls, MousePosition } from 'ol/control.js'// OpenLayers的控件类,包括默认的控件集合和特定的全屏、鼠标位置、比例尺控件
import { transform } from 'ol/proj.js'// OpenLayers的投影转换函数,用于经纬度坐标和投影坐标之间的转换
import LineString from 'ol/geom/LineString.js'  // OpenLayers的线几何类,用于表示线状的地理数据            
import Polygon from "ol/geom/Polygon.js"  // OpenLayers的多边形几何类,用于表示面状的地理数据
import ZoomSlider from 'ol/control/ZoomSlider.js';// 滑动放大缩小按钮
import FullScreen from 'ol/control/FullScreen.js';// 全屏按钮
import ZoomToExtent from 'ol/control/ZoomToExtent.js';// 范围
 
	export default {
	    data () {
	        return {
	            map:null,
				yxt:null,// 影像图
				dzt:null,// 电子图
	            view:null,
				count:0,
				locationLayer:null,// 定位点图层
	        }
	    },
	    mounted(){
		   this.initMap();
	       console.log("mounted方法");
	    },
		methods:{
			/**
			 * @param {*} newValue 新的值或状态
			 * @param {*} oldValue 旧的值或状态
			 * @param {*} ownerInstance 拥有该数据或组件的实例
			 * @param {*} instance 当前操作的具体实例
			 */
			valueChange(newValue, oldValue, ownerInstance, instance){
				console.log(newValue, oldValue, ownerInstance, instance);
				// 下面的方法也好使
				/* // 传递数值
				this.$ownerInstance.callMethod('reciveMessage',this.count++);
				// 传递map
				this.$ownerInstance.callMethod('receiveMethod'); */
				
				// 传递数值
				ownerInstance.callMethod('reciveMessage',this.count++);
				// 传递map
				ownerInstance.callMethod('receiveMethod');
				// 传递过来地值
				const olType = newValue.type;// 类型
				
				switch(olType){
					case "LAYER_TITLE":// 底图切换
						const olFlag = newValue.switchLayerFlag;// 切换图层布尔值
						if(olFlag){
							this.yxt.setVisible(true);
							this.dzt.setVisible(false);
						}else{
							this.yxt.setVisible(false);
							this.dzt.setVisible(true);
						}
					break;
					case "ALL_MAP":
						// 初始范围
						this.goToExtent();
					break;
					case "LOCATION":
						const olLongitude = newValue.longitude;//当前位置的经度
						const olLatitude = newValue.latitude;//当前位置的纬度
						
						this.renderLocation(olLongitude,olLatitude);
					break;
				}
				
			},
			// 初始化天地图
			initMap(){
				//天地图影像
				const tdtYX = new TileLayer({
				  source: new XYZ({
				    url: 'http://t2.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=cef191b507ff5cb698811cd8a9b11ca0',
				    projection: 'EPSG:3857',
				    crossOrigin: '*',
				  }),
				  visible:true,
				})
				this.yxt = tdtYX;
				
				
				//天地图电子地图
				const tdtDZ = new TileLayer({
				  source: new XYZ({
				    url: 'http://t2.tianditu.gov.cn/DataServer?T=vec_w &x={x}&y={y}&l={z}&tk=cef191b507ff5cb698811cd8a9b11ca0',
				    projection: 'EPSG:3857',
				  }),
				  visible:true,
				})
				this.dzt = tdtDZ;
				
				//天地图标注
				const tdtBZ = new TileLayer({
				  source: new XYZ({
				    url: 'http://t2.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=cef191b507ff5cb698811cd8a9b11ca0',
				    projection: 'EPSG:3857',
				  }),
				   visible:true,
				})
			
				this.map = new Map({
				  target: 'map',
				  layers: [tdtYX,tdtDZ,tdtBZ],//[tdtYX, tdtBZ],
				  view: new View({
				    projection: 'EPSG:3857',
				    center: transform([125.33,43.90], 'EPSG:4326', 'EPSG:3857'),
				    // center: [125.33,43.90],
				    zoom: 10,
				   minZoom: 0,// 最小缩放级别
				   maxZoom: 20, //最大缩放级别
				   constrainResolution: true,// 因为存在非整数的缩放级别,所以设置该参数为true来让每次缩放结束后自动缩放到距离最近的一个整数级别,这个必须要设置,当缩放在非整数级别时地图会糊
					enableRotation: false,// 禁止地图旋转
				  }),
				  controls:defaultControls({
					  zoom:false,//不显示放大放小按钮
					  rotate:false,// 不显示指北针控件
					  attribution:false//不显示右下角的地图信息控件
				  }).extend([
					// 比例尺
					new ScaleLine({
						//设置比例尺单位,degrees、imperial、us、nautical、metric(度量单位)
						units: "metric"
					})
				  ])
				})
				
				
                // 事件
				this.map.on("moveend",(e)=>{
					console.log('地图移动', e);
					// 获取当前缩放级别
					var zoomLevel = this.map.getView().getZoom();
					console.log('当前缩放级别:', zoomLevel);
				});
				
				// 渲染完成
				this.map.on('rendercomplete', () => {
					console.log('渲染完成')
				});
				// 点击事件
				this.map.on('click', (e) => {
					console.log('地图点击', e)
					var coordinate = e.coordinate;
					// 将投影坐标转换为经纬度坐标
					var lonLatCoordinate = toLonLat(coordinate);
					// 输出转换后的经纬度坐标
					console.log('经纬度坐标:', lonLatCoordinate);
				});
 
			
			},
			goToExtent(){// 初始范围
				// 获取当前可见视图范围
				//console.log(this.map.getView().calculateExtent());
				// 设置中心点
				this.map.getView().setCenter(transform([125.33,43.90], 'EPSG:4326', 'EPSG:3857'));
				// 设置层级
				this.map.getView().setZoom(10);
			},
			renderLocation(longitude,latitude){
				const geom = transform([longitude,latitude], 'EPSG:4326', 'EPSG:3857');
				
				// 设置中心点定位
				this.map.getView().setCenter(geom);
				// 设置层级
				this.map.getView().setZoom(18);
				
				// 绘制点
				const locationPoint = new Point(geom);
				// 清除绘制点图层
				this.map.removeLayer(this.locationLayer); 
				
				// 绘制定位点
				// 设置点特征(Feature)
				const pointFeature = new Feature({
					title:"point",
					geometry:locationPoint
				});
				
				// 设置特征样式(style)
				pointFeature.setStyle(
					new Style({
						 // 使用 CircleStyle 创建一个圆形的点
						 image:new CircleStyle({
							 // 点样式
							 fill:new Fill({
								 //color:"red",// 颜色
								 color: 'rgba(255,0,0,0.4)',
							 }),
							 // 点周边样式
							 stroke:new Stroke({
								color: '#3399CC',
								width: 1.25, 
							 }),
							 radius:7,// 半径
						 }),
					})
				);
				// 创建和添加特征到源(Source)
				// VectorSource表示一个矢量要素源,它用于存储和显示地理数据。
				const source = new VectorSource();
				source.addFeature(pointFeature);
				// 创建图层并设置源(Layer)
				// VectorLayer表示一个矢量图层,它由一系列矢量要素(Feature)组成,用于在地图上显示地理数据。
				this.locationLayer = new VectorLayer();
				this.locationLayer.setSource(source);
				this.map.addLayer(this.locationLayer);
				
			},
		}
	}
</script>
 
<style scoped lang="scss">
	/*去除顶部导航栏*/
	*{margin:0;padding:0}
	.map{
	  width:100vw;
	  height: 100vh;
	  position: relative;
	  z-index: 1;
	  
	  .ol-zoomslider {
	  		top: 7.5em;
	  		left: .5em;
	  		height: 200px;
	  }
	  
	   .right-vertical-button{
		  position: absolute;
		  right: 0;
		  margin-top: 60rpx;
		  width: 80rpx;
		  z-index: 10;
		  
		  .btn {
				width: auto;
				height: auto;
				margin: 5px; /* 按钮间距 */
				padding: 10px; /* 按钮内部填充 */
				width: 80%; /* 按钮宽度 */
				text-align: center; /* 按钮文字居中 */
		   }
	    }	
		
		.bottom-horizontal-button{
			  position: absolute;
			  bottom: 0;
			  right: 0;
			  margin-bottom: 30rpx;
			  width: 80rpx;
			  z-index: 10;
			.btn {
				width: auto;
				height: auto;
				margin: 5px; /* 按钮间距 */
				padding: 10px; /* 按钮内部填充 */
				width: 80%; /* 按钮宽度 */
				text-align: center; /* 按钮文字居中 */
			 }
		}
		  
	}
 
	
</style>

备注:坐标转换工具 -- coordinate_transformation.js

代码:

//wgs84_to_gcj02.js文件

//地标 转 国测 常量
var x_PI = (3.14159265358979324 * 3000.0) / 180.0;
var PI = 3.1415926535897932384626;
var a = 6378245.0; //卫星椭球坐标投影到平面地图坐标系的投影因子。  
var ee = 0.00669342162296594323; //椭球的偏心率。


//判断是否在国内,在中国国内的经纬度才需要做偏移
function out_of_china(lng, lat) {
	return (
		lng < 72.004 ||
		lng > 137.8347 ||
		(lat < 0.8293 || lat > 55.8271 || false)
	);
}

//转化经度
function transformlng(lng, lat) {
	var ret =
		300.0 +
		lng +
		2.0 * lat +
		0.1 * lng * lng +
		0.1 * lng * lat +
		0.1 * Math.sqrt(Math.abs(lng));
	ret +=
		((20.0 * Math.sin(6.0 * lng * PI) +
				20.0 * Math.sin(2.0 * lng * PI)) *
			2.0) /
		3.0;
	ret +=
		((20.0 * Math.sin(lng * PI) +
				40.0 * Math.sin((lng / 3.0) * PI)) *
			2.0) /
		3.0;
	ret +=
		((150.0 * Math.sin((lng / 12.0) * PI) +
				300.0 * Math.sin((lng / 30.0) * PI)) *
			2.0) /
		3.0;
	return ret;
}

//转化纬度
function transformlat(lng, lat) {
	var ret = -100.0 +
		2.0 * lng +
		3.0 * lat +
		0.2 * lat * lat +
		0.1 * lng * lat +
		0.2 * Math.sqrt(Math.abs(lng));
	ret +=
		((20.0 * Math.sin(6.0 * lng * PI) +
				20.0 * Math.sin(2.0 * lng * PI)) *
			2.0) /
		3.0;
	ret +=
		((20.0 * Math.sin(lat * PI) +
				40.0 * Math.sin((lat / 3.0) * PI)) *
			2.0) /
		3.0;
	ret +=
		((160.0 * Math.sin((lat / 12.0) * PI) +
				320 * Math.sin((lat * PI) / 30.0)) *
			2.0) /
		3.0;
	return ret;
}

//wgs84 to gcj02   地球坐标系 转 火星坐标系
export function wgs84_to_gcj02(lng, lat) {
	if (out_of_china(lng, lat)) {
		return [lng, lat];
	} else {
		var dlat = transformlat(lng - 105.0, lat - 35.0);
		var dlng = transformlng(lng - 105.0, lat - 35.0);
		var radlat = (lat / 180.0) * PI;
		var magic = Math.sin(radlat);
		magic = 1 - ee * magic * magic;
		var sqrtmagic = Math.sqrt(magic);
		dlat =
			(dlat * 180.0) /
			(((a * (1 - ee)) / (magic * sqrtmagic)) * PI);
		dlng =
			(dlng * 180.0) / ((a / sqrtmagic) * Math.cos(radlat) * PI);
		var mglat = lat + dlat;
		var mglng = lng + dlng;

		return [mglng, mglat];
	}
}


//gcj02 to wgs84  火星坐标系 转 地球坐标系
export function gcj02_to_wgs84(lng, lat) {
	if (out_of_china(lng, lat)) {
		return [lng, lat]
	} else {
		var dlat = transformlat(lng - 105.0, lat - 35.0);
		var dlng = transformlng(lng - 105.0, lat - 35.0);
		var radlat = lat / 180.0 * PI;
		var magic = Math.sin(radlat);
		magic = 1 - ee * magic * magic;
		var sqrtmagic = Math.sqrt(magic);
		dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
		dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
		mglat = lat + dlat;
		mglng = lng + dlng;
		return [lng * 2 - mglng, lat * 2 - mglat]
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值