手機浏覽器目前能夠支援取得地理位置經緯度功能了。但是相容性還有點問題。
HTML代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<p id="demo">點選這個按鈕,獲得您的坐标:</p>
<button οnclick="getLocation()">試一下</button>
你好!
</body>
<script >
var latB=39.92; //北京緯度
var lonB=116.46; //北京經度
var x=document.getElementById("demo");
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition,showError);
}else{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function showPosition(position){
var dis=GetDistance(latB,lonB,position.coords.latitude,position.coords.longitude);
x.innerHTML="緯度: " + position.coords.latitude + "<br />經度: " + position.coords.longitude+"<br />距離北京: " +dis+"公裡";
}
function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
x.innerHTML="User denied the request for Geolocation.";
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML="Location information is unavailable.";
break;
case error.TIMEOUT:
x.innerHTML="The request to get user location timed out.";
break;
case error.UNKNOWN_ERROR:
x.innerHTML="An unknown error occurred.";
break;
}
}
function Rad(d){
return d * Math.PI / 180.0;//經緯度轉換成三角函數中度分表形式。
}
//計算距離,參數分别為第一點的緯度,經度;第二點的緯度,經度
function GetDistance(lat1,lng1,lat2,lng2){
var radLat1 = Rad(lat1);
var radLat2 = Rad(lat2);
var a = radLat1 - radLat2;
var b = Rad(lng1) - Rad(lng2);
var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
s = s *6378.137 ;// EARTH_RADIUS;
s = Math.round(s * 10000) / 10000; //輸出為公裡
//s=s.toFixed(4);
return s;
}
</script>
</html>
=========================================
效果如下圖:
測試手機小米MAX2,浏覽器版本自帶浏覽器V10.5.1可以,用微信内置流覽器不行。
圖1
圖2