移动设备GPS坐标的获取以及向百度坐标的转换
JS文件中定义一下函数,在html页面中调用loadPosition()函数就可直接进行执行。
入口函数:
functionloadPosition() {
if (navigator.geolocation) {
//alert("HTML5 Geolocation is supported in your browser.");检测浏览器是否支持定位
navigator.geolocation.getCurrentPosition(updateLocation, handleLocationError, { timeout: 50000, maximumAge: 20000 });
}
else {
alert("HTML5 Geolocation is not supported in your browser.");
}
}
调用成功后的回调函数
functionupdateLocation(position) {
var latitude = position.coords.latitude;//纬度
var longitude = position.coords.longitude;//经度
// var accuracy = position.coords.accuracy;定位精度
// var timestamp = position.timestamp;
// alert("获取的GPS坐标经度:"+longitude+"。纬度:"+latitude);
var gpsPoint = new BMap.Point(longitude, latitude);
BMap.Convertor.translate(gpsPoint, 0, translateCallback); //调用百度接口将GPS坐标转换成百度坐标
}
调用失败后的回调函数
functionhandleLocationError(error) {
switch (error.code) {
case 0:
alert("There was an error while retrieving your location: " + error.message);
break;
case 1:
alert("The user prevented this page from retrieving a location.");
break;
case 2:
alert("The browser was unable to determine your location: " + error.message);
break;
case 3:
alert("The browser timed out before retrieving the location.");
break;
}
}
//坐标转换完之后的回调函数
translateCallback = function (point) {
$("#longitude").val(point.lng);
$("#latitude").val(point.lat);
alert("转化为百度坐标为经度:" + point.lng + "。纬度:" + point.lat);
}
调用坐标转换函数时要用到以下两个js文件,将其制成js文件包含进去就可以。我做项目时用的是mvc框架,直接将下面两个js文件丢到Scripts文件夹,然后在用到这两个文件的页面用@Scripts.Render("~/scripts/api.map.baidu.js")
@Scripts.Render("~/scripts/convertor.js")//以上两个js文件名是自己随便起的
包含进去就可以
api.map.baidu.js
(function(){ window.BMap_loadScriptTime = (new Date).getTime(); document.write(' |
convertor.js
//2011-7-25 (function(){ //闭包 function load_script(xyUrl, callback){ var head = document.getElementsByTagName_r('head')[0]; var script = document_createElement_x_x('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 a 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; })(); |