整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

HTML地理坐标

位基准

说到地理坐标,一定是有一个定位的基准的。在web开发的过程中,它的定位基准一共有那么几种:

第一种是IP,根据当前电脑或者是手机设备它的IP地址来确定当前的地理坐标。IP定位是通过ISP机房,也就是每一个登记的机房位置,比如小区,每一栋大楼都会有一个登记的ISP机房。如果使用IP定位的话,它大约能够精确到小区或者是大楼级别,比如一栋和二栋通过这个IP地址就能准确的区分出来。IP定位的误差大概在十几米。

第二种是GPS,GPS是基于卫星定位的,它相对来说是比较准确的,但是它需要硬件支持。比如电脑一般是不具备GPS定位功能的。它的精确度很高,如果是军方的话可以达到1米甚至以内。

第三种WIFI定位,WiFi定位是通过每一个WiFi地址的Mac地址,特别精确。如果WiFi有登记过的话,它的误差大概在一米左右。WiFi是有一个信号辐射范围的,根据辐射范围的强弱可以确定当前的设备距离这个WiFi有多远。但是它的支持性能不是太好,只能支持室内。

第四种GSM和CDMA是比较常见的,是使用手机卡来定位的,也就是基于设备的基站。比如联通的信号塔电信的信号塔,它的精确度也是比较高的,它一般是用于手机或者是通信设备。不同的信号塔会接到来自不同方位的信号,然后根据这个信号的叠加和它的强弱再来确定当前的位置,它的精确度可以达到10米左右。

最后一种是用户指定,可以手动指定当前的位置,假如当前定位不准,我们需要做一个校正指定当前的位置,最常见的就是我们平常使用打车软件时,如果自动获取的位置不准,那么我们可以通过移动来手动指定我们当前的位置。

2:获取流程

获取定位基准之后,我们需要获取当前的地理坐标,获取是有一个流程的。首先打开web应用,打开之后向浏览器请求地理信息,这时会弹出一个询问窗口,由于位置信息涉及到一个隐私,所以浏览器做了一个双重的保护,询问之后如果同意了,这时浏览器就会从设备或者受信任的服务器获取位置信息并返回。

3:浏览器兼容

browser_map

4:获取用户当前坐标(地理坐标到底是怎么获取的)

getCurrentPosition(onSuccess,onError,options)

onSuccess是一个回调函数,options有三个值:enableHighAccuracy(高精度标识,在设备或者是服务器能达到范围内返回最高精度)、timeout(超出时间,如果在指定时间内获取不到位置信息就会返回Error,默认是0(无穷大))、maximumAge(缓存时间)。

const getLocation = () => {
 const options = {
 enableHighAccuracy: false, 
 maximumAge: 1000
 }
 if(navigator.geolocation) {
 //浏览器支持geolocation
 navigator.geolocation.getCurrentPosition(onSuccess,onError,options);
 } else {
 //浏览器不支持geolocation
 alert('当前浏览器不支持getLocation');
 }
}
​
//成功回调
function onSuccess(position) {
 const longitude = position.coords.longitude;
 //纬度
 const latitude = position.coords.latitude;
 console.log('position', { longitude, latitude });
}
​
//失败回调
function onError(error) {
 switch(error.code){
 case 1:
 alert("位置服务被拒绝");
 break;
 case 2:
 alert("暂时获取不到位置信息");
 break;
 case 3:
 alert("获取信息超时");
 break;
 case 4:
 alert("未知错误");
 break;
 }
}

5:持续获取用户当前位置(科学上网)

watchCurrentPosition(onSuccess, onError, options);

let watchId = undefined;
​
const getLocation = () => {
 const options = {
 enableHighAccuracy: false, 
 maximumAge: 1000
 }
 if(navigator.geolocation) {
 //浏览器支持geolocation
 watchId = navigator.geolocation.watchPosition(showPosition);
 } else {
 //浏览器不支持geolocation
 alert('当前浏览器不支持getLocation');
 }
}
​
function showPosition(position) {
 const longitude = position.coords.longitude;
 const latitude = position.coords.latitude;
 console.log('position', { longitude, latitude });
}
​
const cancel = () => {
 //清除当前持续获取当前位置,可以当做是一个setInterval
 if(watchId) navigator.geolocation.clearWatch(watchId);
}

6:coords

  • coords.latitude - 十进制数的纬度
  • coords.longitude - 十进制数的经度
  • coords.accuracy - 位置精度
  • coords.altitude - 海拔,海平面以上以米计
  • coords.altitudeAccuracy - 位置的海拔精度
  • coords.heading - 方向,从正北开始以度计
  • coords.speed - 速度,以米/每秒计
  • timestamp - 响应的日期/时间

获取 HTML 元素的位置坐标,可以使用 JavaScript 中的 DOM 操作来实现。下面是一个示例代码,展示如何使用 JavaScript 获取指定类名的元素的位置坐标:

htmlCopy code
<!DOCTYPE html>
<html>
<body>
  <div class="my-element">This is a div element.</div>

  <script>
    // 获取具有指定类名的元素
    var element = document.querySelector('.my-element');

    // 获取元素的位置信息
    var rect = element.getBoundingClientRect();

    // 输出元素的位置坐标
    console.log('元素的左上角坐标:', rect.left, rect.top);
    console.log('元素的右下角坐标:', rect.right, rect.bottom);
    console.log('元素的宽度和高度:', rect.width, rect.height);
  </script>
</body>
</html>

在上述代码中,我们首先使用 querySelector() 方法获取具有指定类名 .my-element 的元素。然后,使用 getBoundingClientRect() 方法获取该元素的位置信息,返回一个包含左上角坐标、右下角坐标、宽度和高度等属性的 DOMRect 对象。

最后,我们使用 console.log() 方法将元素的位置坐标输出到控制台。您可以根据实际需要使用这些坐标信息。

请注意,获取的位置坐标是相对于视口(viewport)的坐标,而不是相对于整个页面的坐标。如果需要获取相对于页面的坐标,可以结合 window.scrollXwindow.scrollY 属性进行计算。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport">
</head>
<body>
<canvas id="canvas" style="border:2px solid red" width="400" height="400"></canvas>
<canvas id="canvas2" style="border:2px solid red" width="400" height="400"></canvas>
<div onclick="Fn()"
     style="border:2px solid red;width:200px;margin-top:10px;height:30px;line-height:30px;text-align: center">
    按钮
</div>
<script type="text/javascript">
    var canvas = document.getElementById('canvas');
    var ctx = canvas.getContext('2d');
    //coordinateRecord 坐标记录;detectionCoordinate检测是否直线坐标
    var coordinateRecord = [], detectionCoordinate = [];
    //是否开始标记区域
    var move = false;

    //检测是不是直线
    function checkIsLine(pointArray) {
        if (pointArray === null || pointArray === undefined || pointArray.length < 3) {
            return false;
        }
        var startX = pointArray[0].x;
        var startY = pointArray[0].y;
        var endX = pointArray[pointArray.length - 2].x;
        var endY = pointArray[pointArray.length - 2].y;
        var tan = Math.atan(endX - startX, endY - startY) * 180 / Math.PI;
        for (let i in pointArray) {
            //每3个点检测是否是直线
            if (i > 3) {
                var x = pointArray[i].x - pointArray[i - 3].x;
                var y = pointArray[i].y - pointArray[i - 3].y;
                var tantemp = Math.atan(y / x) * 180 / Math.PI;
                //允许误差16度
                if (Math.abs(tantemp - tan) > 16) {
                    return false;
                }
            }
        }
        return true;
    }

    canvas.onmousedown = function (e) {
        var x = e.clientX - canvas.offsetLeft;
        var y = e.clientY - canvas.offsetTop;
        //记录开始点,每次开始画,都是一组新的坐标,处理画多个图形时,坐标点记录不准确的问题
        coordinateRecord.push([{
            x: x,
            y:y
        }])
        ctx.moveTo(x, y);
        ctx.lineWidth = 1;
        move = true;
    }

    canvas.onmousemove = function (e) {
        var x = e.clientX - canvas.offsetLeft;
        var y = e.clientY - canvas.offsetTop;
        if (move) {
            ctx.lineTo(x, y);
            ctx.stroke();
            detectionCoordinate.push({
                x: x,
                y: y
            });
            var isLine = checkIsLine(detectionCoordinate);
            //非直线记录该点
            if (!isLine) {
                coordinateRecord[coordinateRecord.length - 1].push({
                    x: x,
                    y:y
                });
            }
        }
    }

    canvas.onmouseup = function (e) {
        var x = e.clientX - canvas.offsetLeft;
        var y = e.clientY - canvas.offsetTop;
        //重置检测坐标数组
        detectionCoordinate = [];
        //记录结束点
        coordinateRecord[coordinateRecord.length - 1].push({
            x: x,
            y:y
        });
        move = false;
    }

    //点击btn,把记录的坐标重新显示,用来检测坐标是否标记正确
    var canvas2 = document.getElementById('canvas2');
    var ctx2 = canvas2.getContext('2d');
    function Fn() {
        for (var i in coordinateRecord) {
            const item = coordinateRecord[i];
            ctx2.moveTo(item[0].x,item[0].y);
            ctx2.lineWidth = 2;
            ctx2.strokeStyle = "green";
            for (var t in item) {
                if (t > 0) {
                    ctx2.lineTo(item[t].x, item[t].y);
                }
            }
            ctx2.stroke();
        }
    }
</script>
</body>
</html>