前言:在使用百度地图的时候,根据经纬度地址逆解析的时候,获取的位置不是很精确,只能获取到省、市县、路名、街道、号,有时只能获取省市县,位置不是很精确。所以使用百度地图位置纠偏方法获取比较精确的实际位置。
1、项目结构
2、复制jquery-3.2.1.js到项目中,编写map.html文件
<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><meta name="viewport" content="initial-scale=1.0, user-scalable=no" /><link rel="stylesheet" href="map.css"/><title>地图</title></head><body><div id="map"></div><script type="text/javascript" src="http://api./api?v=2.0&ak=密钥"></script><script type="text/javascript" src="jquery-3.2.1.js"></script><script type="text/javascript" src="map.js"></script></body></html>
3、编写map.css文件
body, html, #map {width: 100%;height: 100%;overflow: hidden;margin: 0;font-family: "微软雅黑";}
4、编写map.js文件
var App = function () {this.Setup = function () {this.InitMap();this.GetPosition(118.3823, 31.313); // 普通地址this.BaiDuMapRectifyDeviation(118.3823, 31.313); // 纠偏之后的地址};this.InitMap = function () {this.Map = new BMap.Map("map");this.Map.centerAndZoom(new BMap.Point("118.38", "31.33"), 11);this.Map.addControl(new BMap.ScaleControl());this.Map.addControl(new BMap.MapTypeControl({mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP] }));this.Map.enableScrollWheelZoom();};this.BaiDuMapRectifyDeviation = function(longitude, latitude) {$.ajax({type: "POST",url: "http://api./ag/coord/convert?from=0&to=4&x="+longitude+"&y="+latitude+"",async: false,data: [],cache: false,dataType: "jsonp",success: function (data) {this.GetPosition(data.x, data.y);}.bind(this)});};this.GetPosition = function (longitude, latitude) {var geocoder = new BMap.Geocoder();var point = new BMap.Point(longitude, latitude);geocoder.getLocation(point, function(address){console.log(address);});};this.Base64Decode = function (code) {return decodeURIComponent(atob(code).split('').map(function(c) {return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);}).join(''));};}$(document).ready(function () {var app = new App();app.Setup();});
说明:map.js中是通过ajax请求百度提供的纠偏接口,this.GetPosition()方法是传入经度、纬度获取实际位置,this.BaiDuMapRectifyDeviation()方法传入经度、纬度,经度、纬度是经过纠偏接口处理过的数据,ajax请求成功之后,使用this.Base64Decode()解码,然后调用this.GetPosition()方法获取实际位置。
纠偏接口:
"http://api./ag/coord/convert?from=0&to=4&x=113.540124&y=23.517846,
参数解释:
from=0:代表传入的是真实经纬度
to=4:代表返回是百度纠偏后,能在百度地图上正确显示出该地址的经纬度
x:经度
y:纬度
返回数据:
{err:0,“x”:“MTEzj1MjlyMjUxOTg1”,“y”:“MjMuODIwNjM5MTEyNDgy”}
返回的数据是经过Base64加密。
5、测试结果