JS+HTML5取手机经纬度和计算距离。

手机浏览器目前能够支持取得地理位置经纬度功能了。但是兼容性还有点问题。

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 onclick="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

猜你喜欢

转载自blog.csdn.net/rishengcsdn/article/details/87969641