使用html5获取当前手机的经纬度,并接入百度地图API,查询出当前位置

最近项目需要,稍微研究一下html5获取当前地理位置的问题。

获取当前位置的经纬度很简单,一句代码就搞定

navigator.geolocation.getCurrentPosition(function (position) {
longitude = position.coords.longitude;
latitude = position.coords.latitude;
});

然后查阅百度地图API,很easy,也是几句代码就搞定的事

var map = new BMap.Map("allmap");
var point = new BMap.Point(longitude,latitude);
var geoc = new BMap.Geocoder();
geoc.getLocation(point, function(rs){
var addComp = rs.addressComponents;
alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
});

好的,本以为到此结束,结果实际测试发现有点问题,显示的位置与我的真正位置偏差大约两三公里左右。

一开始以为是html5获取经纬度的偏差问题,然而并不是

然后开始查资料,求助强大的度娘,然后无意中发现了一个叫做 坐标转换 的东西,一搜索才知道,原来百度地图对坐标进行了深度封装,必须通过他提供的接口进行坐标转换才行

(当然了,还是因为我以前没接触过百度地图,所以不知道这点知识,常用百度地图api的应该对这个很熟悉的吧)

好了,废话不多说,上最终代码吧

            var map = new BMap.Map("allmap");
var longitude, latitude;
navigator.geolocation.getCurrentPosition(function (position) {
longitude = position.coords.longitude;
latitude = position.coords.latitude;
});
setTimeout(function () {
var gpsPoint = new BMap.Point(longitude, latitude);
BMap.Convertor.translate(gpsPoint, 0, function (point) {
var geoc = new BMap.Geocoder();
geoc.getLocation(point, function (rs) {
var addComp = rs.addressComponents;
alert(addComp.province + ", " + addComp.city + ", " + addComp.district + ", " + addComp.street + ", " + addComp.streetNumber);
});
});
}, 3000);

这段代码依赖两个包

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=秘钥"></script>
<script type="text/javascript" src="http://developer.baidu.com/map/jsdemo/demo/convertor.js"></script>

convertor.js 源码

//2011-7-25
(function(){ //闭包
function load_script(xyUrl, callback){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = xyUrl;
//借鉴了jQuery的script跨域方法
script.onload = script.onreadystatechange = function(){
if((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")){
callback && callback();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
head.insertBefore( script, head.firstChild );
}
function translate(point,type,callback){
var callbackName = 'cbk_' + Math.round(Math.random() * 10000); //随机函数名
var xyUrl = "http://api.map.baidu.com/ag/coord/convert?from="+ type + "&to=4&x=" + point.lng + "&y=" + point.lat + "&callback=BMap.Convertor." + callbackName;
//动态创建script标签
load_script(xyUrl);
BMap.Convertor[callbackName] = function(xyResult){
delete BMap.Convertor[callbackName]; //调用完需要删除改函数
var point = new BMap.Point(xyResult.x, xyResult.y);
callback && callback(point);
}
} window.BMap = window.BMap || {};
BMap.Convertor = {};
BMap.Convertor.translate = translate;
})();
上一篇:iOS 10 因苹果健康导致闪退 crash


下一篇:《Linux及安全》期中总结&《Linux内核分析》期终总结