1.H5地理位置定位功能
首先判断用户浏览器是否支持该功能,目前大多数现代浏览器均支持,获取位置信息需用户授权同意
function getLocation(){ if (navigator.geolocation){ navigator.geolocation.getCurrentPosition(showPosition,showError); } else { alert( "浏览器不支持地理定位。" ); } }
2.showPosition()获取用户经度纬度
function showPosition(position){ console.log(position); var lat = position.coords.latitude; //纬度 var lag = position.coords.longitude; //经度 console.log ( '纬度:' +lat+ ',经度:' +lag); }
3.执行函数getLocation(),如果调用成功即可显示经度纬度,简单吧!!!
4.补充showError(),这个函数是报错信息
showError(error){
console.log(error.code)
}
引用一个博客主的代码哈哈:
function showError(error){ switch (error.code) { case error.PERMISSION_DENIED: alert( "定位失败,用户拒绝请求地理定位" ); break ; case error.POSITION_UNAVAILABLE: alert( "定位失败,位置信息是不可用" ); break ; case error.TIMEOUT: alert( "定位失败,请求获取用户位置超时" ); break ; case error.UNKNOWN_ERROR: alert( "定位失败,定位系统失效" ); break ; } }
接下来用百度和谷歌提供的接口,利用获取到的经纬度查看具体的地址信息
用到了jq的ajax封装,所以得引用jq,
百度的:
function showPosition(position){ //将我们获取到的经纬度保存到变量中 var latlon = position.coords.latitude+ ',' +position.coords.longitude; //baidu接口 var url = "http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b&callback=renderReverse&location="+latlon+"&output=json&pois=0" $.ajax({ type: "GET" , dataType: "jsonp" , url: url, beforeSend: function (){ $( "#baidu" ).html( '正在定位...' ); }, success: function (data) { if (data.status==0){ $( "#baidu" ).html(data.result.formatted_address); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { $( "#baidu" ).html(latlon+ "地址位置获取失败" ); } }); });
谷歌
谷歌同上,接口如下;
var url='http://maps.google.cn/maps/api/geocode/json?latlng='+latlon+'&language=CN';
成功回调:
success: function (data) { if (data.status== 'OK' ){ var results = data.results; $.each(results, function (index,array){ if (index==0){ $( "#google_geo" ).html(array[ 'formatted_address' ]); } }); } }