微信小程序获取定位显示在百度地图上位置出现偏差

news/2024/7/20 3:38:54 标签: 微信小程序, 小程序, 百度

项目场景:

背景:

  1. 小程序>微信小程序端获取手机定位坐标,以及正确展示位置
  2. 通过详细地址解析为定位坐标显示在小程序端以及PC后台
  3. 小程序获取的地理坐标与百度地图坐标相互转化

相关知识

目前国内主要有以下三种坐标系:

  1. WGS84:为一种大地坐标系,也是目前广泛使用的GPS全球卫星定位系统使用的坐标系。
  2. GCJ02:又称火星坐标系,是由中国国家测绘局制订的地理信息系统的坐标系统。由WGS84坐标系经加密后的坐标系。
  3. BD09:为百度坐标系,在GCJ02坐标系基础上再次加密。其中bd09ll表示百度经纬度坐标,bd09mc表示百度墨卡托米制坐标。
    非中国地区地图,服务坐标统一使用WGS84坐标。
坐标系使用厂商
大地坐标系(WGS84)GPS定位系统及相关设备、谷歌地图
火星坐标(GCJ02)高德地图、阿里云地图、 腾讯搜搜地图 、高德MapABC地图API 、小程序百度地图
百度坐标(BD09)百度地图
图吧坐标图吧MapBar地图

问题描述

小程序端获取的坐标显示在百度地图上地理位置出现偏差:

解决问题

小程序获取的定位坐标可选type 有两种 wgs84 : gps定位坐标, gcj02: 火星定位坐标。

  • type:wgs84返回gps坐标,gcj02 返回可用于wx.openLocation的坐标;
  • altitude:传入 true 会返回高度信息,由于获取高度需要较高精确度,会减慢接口返回速度;
    isHighAccuracy:开启高精度定位;
  • highAccuracyExpireTime:高精度定位超时时间(ms),指定时间内返回最高精度,该值3000ms以上高精度定位才有效果;
wx.getLocation({
  // type: 'wgs84', // gps定位 坐标系
  type: 'gcj02', // 重点就是在这里,最好使用这种,对接百度小程序端地址解析 
  success: function(){},
  fail: function(){}
})
  1. 小程序端使用百度地图api 地址解析为详细地址 ,传入的坐标系需要为 gcj02类型,并不是百度坐标系
const bmap = require("../../utils/bmap-wx.js"); // 引入bmap-wx文件
 var BMap = new bmap.BMapWX({
            ak:  "你申请的小程序百度地图的ak"
 })
 BMap.regeocoding({
      location: res.latitude + ',' + res.longitude,  // 百度api 地址解析,使用的坐标点类型为 gcj02
      success: function (res) {
      		console.log(res.originalData.result.sematic_description)
      },
      fail: function () {}
 })
  1. 小程序端获取的定位需要转化为百度系坐标用于后端展示,则需要通过一定的算法将gcj02转化为百度坐标,这里有写好的算法, 大家直接粘贴

WSCoordinate.js

/**
 *  判断经纬度是否超出中国境内
 */
function isLocationOutOfChina(latitude, longitude) {
	if (longitude < 72.004 || longitude > 137.8347 || latitude < 0.8293 || latitude > 55.8271)
	  return true;
	return false;
  }
  
  
  /**
   *  将WGS-84(国际标准)转为GCJ-02(火星坐标):
   */
  function transformFromWGSToGCJ(latitude, longitude) {
	var lat = "";
	var lon = "";
	var ee = 0.00669342162296594323;
	var a = 6378245.0;
	var pi = 3.14159265358979324;
  
	if (isLocationOutOfChina(latitude, longitude)) {
	  lat = latitude;
	  lon = longitude;
	}
	else {
	  var adjustLat = transformLatWithXY(longitude - 105.0, latitude - 35.0);
	  var adjustLon = transformLonWithXY(longitude - 105.0, latitude - 35.0);
	  var radLat = latitude / 180.0 * pi;
	  var magic = Math.sin(radLat);
	  magic = 1 - ee * magic * magic;
	  var sqrtMagic = Math.sqrt(magic);
	  adjustLat = (adjustLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
	  adjustLon = (adjustLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
	  latitude = latitude + adjustLat;
	  longitude = longitude + adjustLon;
	}
	return { latitude: latitude, longitude: longitude };
  
  }
  
  /**
   *  将GCJ-02(火星坐标)转为百度坐标:
   */
  function transformFromGCJToBaidu(latitude, longitude) {  
	var pi = 3.14159265358979324 * 3000.0 / 180.0;
  
	var z = Math.sqrt(longitude * longitude + latitude * latitude) + 0.00002 * Math.sin(latitude * pi);
	var theta = Math.atan2(latitude, longitude) + 0.000003 * Math.cos(longitude * pi);
	var a_latitude = (z * Math.sin(theta) + 0.006);
	var a_longitude = (z * Math.cos(theta) + 0.0065);
  
	return { latitude: a_latitude, longitude: a_longitude };
  }
  
  /**
   *  将百度坐标转为GCJ-02(火星坐标):
   */
  function transformFromBaiduToGCJ(latitude, longitude) {
	var xPi = 3.14159265358979323846264338327950288 * 3000.0 / 180.0;
  
	var x = longitude - 0.0065;
	var y = latitude - 0.006;
	var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * xPi);
	var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * xPi);
	var a_latitude = z * Math.sin(theta);
	var a_longitude = z * Math.cos(theta);
  
	return { latitude: a_latitude, longitude: a_longitude };
  }
  
  /**
   *  将GCJ-02(火星坐标)转为WGS-84:
   */
  function transformFromGCJToWGS(latitude, longitude) {
	var threshold = 0.00001;
  
	// The boundary
	var minLat = latitude - 0.5;
	var maxLat = latitude + 0.5;
	var minLng = longitude - 0.5;
	var maxLng = longitude + 0.5;
  
	var delta = 1;
	var maxIteration = 30;
  
	while (true) {
	  var leftBottom = transformFromWGSToGCJ(minLat, minLng);
	  var rightBottom = transformFromWGSToGCJ(minLat, maxLng);
	  var leftUp = transformFromWGSToGCJ(maxLat, minLng);
	  var midPoint = transformFromWGSToGCJ((minLat + maxLat) / 2, (minLng + maxLng) / 2);
	  delta = Math.abs(midPoint.latitude - latitude) + Math.abs(midPoint.longitude - longitude);
  
	  if (maxIteration-- <= 0 || delta <= threshold) {
		return { latitude: (minLat + maxLat) / 2, longitude: (minLng + maxLng) / 2 };
	  }
  
	  if (isContains({ latitude: latitude, longitude: longitude }, leftBottom, midPoint)) {
		maxLat = (minLat + maxLat) / 2;
		maxLng = (minLng + maxLng) / 2;
	  }
	  else if (isContains({ latitude: latitude, longitude: longitude }, rightBottom, midPoint)) {
		maxLat = (minLat + maxLat) / 2;
		minLng = (minLng + maxLng) / 2;
	  }
	  else if (isContains({ latitude: latitude, longitude: longitude }, leftUp, midPoint)) {
		minLat = (minLat + maxLat) / 2;
		maxLng = (minLng + maxLng) / 2;
	  }
	  else {
		minLat = (minLat + maxLat) / 2;
		minLng = (minLng + maxLng) / 2;
	  }
	}
  
  }
  
  function isContains(point, p1, p2) {
	return (point.latitude >= Math.min(p1.latitude, p2.latitude) && point.latitude <= Math.max(p1.latitude, p2.latitude)) && (point.longitude >= Math.min(p1.longitude, p2.longitude) && point.longitude <= Math.max(p1.longitude, p2.longitude));
  }
  
  function transformLatWithXY(x, y) {
	var pi = 3.14159265358979324;
	var lat = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
	lat += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
	lat += (20.0 * Math.sin(y * pi) + 40.0 * Math.sin(y / 3.0 * pi)) * 2.0 / 3.0;
	lat += (160.0 * Math.sin(y / 12.0 * pi) + 320 * Math.sin(y * pi / 30.0)) * 2.0 / 3.0;
	return lat;
  }
  
  function transformLonWithXY(x, y) {
	var pi = 3.14159265358979324;
	var lon = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
	lon += (20.0 * Math.sin(6.0 * x * pi) + 20.0 * Math.sin(2.0 * x * pi)) * 2.0 / 3.0;
	lon += (20.0 * Math.sin(x * pi) + 40.0 * Math.sin(x / 3.0 * pi)) * 2.0 / 3.0;
	lon += (150.0 * Math.sin(x / 12.0 * pi) + 300.0 * Math.sin(x / 30.0 * pi)) * 2.0 / 3.0;
	return lon;
  }
  
  
  
  module.exports = {
	isLocationOutOfChina: isLocationOutOfChina,
	transformFromWGSToGCJ: transformFromWGSToGCJ,
	transformFromGCJToBaidu: transformFromGCJToBaidu,
	transformFromBaiduToGCJ: transformFromBaiduToGCJ,
	transformFromGCJToWGS: transformFromGCJToWGS
  }

  1. 直接上代码转化 调用BMapWX.regeocoding方法进行逆地址解析(从经纬度转换为地址信息)
const utils = require("../../utils/WSCoordinate.js")
wx.getLocation({
            // type: 'wgs84', // gps定位 坐标系
            type: 'gcj02', // 重点就是在这里
            success: function (res) {
                // gcj02 转换成百度地图坐标,用于传给PC端 百度地图展示
                const marker = utils.transformFromGCJToBaidu(res.latitude, res.longitude)
                that.setData({
                    locationFlag: false,
                    map_latitude: marker.latitude,
                    map_longitude: marker.longitude
                })
                BMap.regeocoding({
                    location: res.latitude + ',' + res.longitude,
                    success: function (res) {
                        that.setData({
                            desLocation: res.originalData.result.sematic_description
                        })
                    },
                    fail: function () {
                        wx.showToast({
                            title: '请检查位置服务是否开启',
                        })
                    },
                });
            },
            fail: function () {
                console.log('fail:', '授权失败')
                            
            }
        })

5 地址解析(从地址转换为坐标)

const bmap = require("../../lib/bmap-wx.js"); // 引入bmap-wx文件
const util = require('../../lib/WSCoordinate.js')  
 // 新建百度地图对象
        var BMap = new bmap.BMapWX({
            ak: "你的ak", // 你的ak
        });
         // 发起geocoding检索请求
        BMap.geocoding({
            address: address, // 输入详细地址            
            success: (data) => {  // 获取的坐标为 gcj02坐标,并不是百度坐标,需要转换为百度坐标
            const wxMarkerData = data.wxMarkerData[0]
            // 将GCJ-02(火星坐标)转为百度坐标
            let resultMarker = util.transformFromGCJToBaidu( wxMarkerData.latitude, wxMarkerData.longitude)
            // console.log(resultMarker, 'resultMarker')
            this.setData({
                latitude: resultMarker.latitude, // 纬度
                longitude: resultMarker.longitude // 经度
            })
        },
        fail: (error) => { 
            console.log('error:', error)
        },
})
       
       
    


http://www.niftyadmin.cn/n/5232215.html

相关文章

ipa应用测试平台怎么开开具发票

控制台-个人中心-发票管理 ●点击申请发票可以开具发票 ●申请发票-填写资料-勾选订单 ●个人发票开具以及公司发票开具 ●提交发票申请 ●等待申请成功开具发票 ●发票开具成功&#xff0c;我们可以开具或者查看发票

【PyTorch】(五)模型训练

文章目录 1. 基本步骤 1. 基本步骤 for epoch in range(num_epochs):for _X, _y in dataloader:# 将数据转移到GPU_X, _y _X.to(device), _y.to(device)# 前向传播计算损失loss criterion(model(_X).reshape(_y.shape), _y)# 清空优化器梯度缓存optimizer.zero_grad()# 误差…

服务器数据恢复—服务器断电导致XenServer数据文件丢失的数据恢复案例

服务器数据恢复环境&#xff1a; 某品牌720服务器搭配该品牌某型号RAID卡&#xff0c;使用4块STAT硬盘组建了一组RAID10阵列。服务器上部署XenServer虚拟化平台&#xff0c;系统盘 数据盘两个虚拟机磁盘。虚拟机上安装的是Windows Server操作系统&#xff0c;作为Web服务器使用…

[HTML]Web前端开发技术6(HTML5、CSS3、JavaScript )DIV与SPAN,盒模型,Overflow——喵喵画网页

希望你开心&#xff0c;希望你健康&#xff0c;希望你幸福&#xff0c;希望你点赞&#xff01; 最后的最后&#xff0c;关注喵&#xff0c;关注喵&#xff0c;关注喵&#xff0c;佬佬会看到更多有趣的博客哦&#xff01;&#xff01;&#xff01; 喵喵喵&#xff0c;你对我真的…

深度学习及其基本原理

深度学习的 Ups and Downs概念区分神经网络的构成深度学习基本原理深度学习的普遍近似定理扩展&#xff1a;反卷积网络——可视化每一层提取的特征 深度学习的 Ups and Downs 1958&#xff1a;感知机&#xff08;线性模型&#xff09;1969&#xff1a;感知机有局限性1980s&…

图书馆座位预约时间冲突提示(前后端全) 前端elementUI 时间选择器只显示时和分,SQL实现时间冲突判断

背景 帮客户定制项目&#xff0c;要实现图书馆预约座位的功能。 功能描述如下&#xff1a;学生选择开始时间和结束时间&#xff0c;只选择小时和分钟&#xff0c;提交预约后&#xff0c;如果该时间有冲突提示学生修改预约时间。 问题 前端样式选择的是elmentUI&#xff0c;但…

《微信小程序开发从入门到实战》学习三十八

4.2 云开发JSON数据库 4.2.9 条件查询与查询指令 在查询数据时&#xff0c;有时需要对查找的数据添加一些限定条件&#xff0c;只获取满足给定条件的数据&#xff0c;这样的查询称为条件查询。 可以在集合引用上使用where方法指定查询条件&#xff0c;再用get方法&#xff0…

深入理解Servlet(上)

作者简介&#xff1a;大家好&#xff0c;我是smart哥&#xff0c;前中兴通讯、美团架构师&#xff0c;现某互联网公司CTO 联系qq&#xff1a;184480602&#xff0c;加我进群&#xff0c;大家一起学习&#xff0c;一起进步&#xff0c;一起对抗互联网寒冬 为什么要了解Servlet …