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']); } }); } }