目前,google在國內需要翻牆才能上,翻不了牆的話,只能獲取到經緯度信息。
*調用navigator.geolocation對象時,首先要獲取用戶同意。
navigator.geolocation.getCurrentPosition(callback()); 獲取用戶的當前位置
navigator.geolocation.watchPosition(callback()); 獲取當前位置,並不斷監視當前位置,一旦位置改變,則調用回調函數。
navigator.geolocation.clearWatch() 停止見識用戶位置,參數為watchPosition()的返回值
*獲取經緯度
navigator.geolocation.getCurrentPosition(function(pos,error){ if(!navigator.geolocation) throw "geolocation not support"; var latitude=pos.coords.latitude; var longitude=pos.coords.longitude; var accuracy=pos.coords.accuracy; console.log("當前位置:經度:"+latitude+" 緯度:"+longitude+" 精度:"+accuracy); });
*在google地圖上靜態顯示當前位置(能翻牆的才能顯示出圖片)
function getMap(){ if(!navigator.geolocation) throw "geolocation not supported"; var posImg=document.createElement("img"); navigator.geolocation.getCurrentPosition(setMap); return posImg; function setMap(pos){ var latitude=pos.coords.latitude; var longitude=pos.coords.longitude; var accuracy=pos.coords.accuracy; //請求的url var url="http://maps.google.com/maps/api/staticmap"+"?center="+latitude+","+longitude+"&size=640*640&sensor=true"; var zoomlevel=20; ///設置初始精度 ///低精度情況下放大 if(accuracy>80) zoomlevel-=Math.round(Math.log(accuracy/50)/Math.LN2); url+="&zoom="+zoomlevel; posImg.src=url; } } var img=getMap(); document.body.appendChild(img);
喜歡請點擊右下角推薦,如有疑問可以留言。轉載請標明出處。