百度地图实时轨迹画线

版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!


恰饭广告




注意:

1.百度地图ak换成自己在百度地图官网申请

2.建议使用firefox浏览器,google被墙无法调用gps

3.发布到服务器必须使用https,对于localhost和本地测试不用

4.电脑开启位置服务,手机打开gps定位

5.百度地图坐标和gps坐标不一致,要在百度地图正确显示位置必须把gps坐标转为百度坐标

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport"
    content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>百度地图的动态行驶轨迹</title>
  <script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=自己去申请"></script>
</head>

<body>
  <div>走一段距离打个点,两个点连成一条线</div>
  <button onclick="getLocation()">打点</button>
  <div id="message"></div>
  <div id="mapId" style="height: 500px;"></div>
  <script>
    var map = new BMap.Map("mapId");
    map.enableScrollWheelZoom(); // 开启鼠标滚轮缩放
    getMyLocation();
    //获取现在的经纬度
    function getMyLocation() {
      if (navigator.geolocation) {
        //判断是否有这个对象
        navigator.geolocation.getCurrentPosition(function (pos) {
          var bd = GpsToBaiduPoint(pos.coords);//转换为百度坐标
          var place = new BMap.Point(bd.lng, bd.lat);
          map.centerAndZoom(place, 15);// 根据经纬度显示地图的范围
          //map.setViewport([new BMap.Point(place.lng, place.lat)]);// 根据提供的地理区域或坐标设置地图视野
          addStartMarker(new BMap.Point(place.lng, place.lat), '起点', map);
        })
      } else {
        console.log("当前系统不支持GPS API")
      }
    }

    var carMk;
    //小车行驶图标
    var drivingPoint = new BMap.Icon('car.png', new BMap.Size(52, 26), {
      anchor: new BMap.Size(27, 13),
      imageSize: new BMap.Size(52, 26)
    });
    //终点图标
    var terminalPoint = new BMap.Icon('endMap.png', new BMap.Size(45, 45), {
      anchor: new BMap.Size(20, 45),
      imageSize: new BMap.Size(45, 45)
    });


    // 划线
    function drowLine(map, PointArr, PointArrNext) {
      if (PointArrNext != undefined) {
        var polyline = new BMap.Polyline(
          [
            new BMap.Point(PointArr[0], PointArr[1]),
            new BMap.Point(PointArrNext[0], PointArrNext[1])
          ],
          {
            strokeColor: "red",
            strokeWeight: 7,
            strokeOpacity: 1
          });   //创建折线
        map.addOverlay(polyline);
        addMarkerEnd(new BMap.Point(PointArrNext[0], PointArrNext[1]), '小车行驶', map, PointArrNext, new BMap.Point(PointArr[0], PointArr[1]));//添加图标
      } else {
        addMarkerEnd(new BMap.Point(PointArr[0], PointArr[1]), '终点', map);//添加终点图标
      }
    }
    //添加起始图标
    function addStartMarker(point, name, mapInit) {
      if (name == "起点") {
        var myIcon = new BMap.Icon("startMap.png", new BMap.Size(45, 45), {
          anchor: new BMap.Size(20, 45),//这句表示图片相对于所加的点的位置mapStart
          imageSize: new BMap.Size(45, 45),//图标所用的图片的大小,此功能的作用等同于CSS中的background-size属性。可用于实现高清屏的高清效果
          //offset: new BMap.Size(-10, 45), // 指定定位位置
          //imageOffset: new BMap.Size(0, 0 - 10 * 25) // 设置图片偏移
        });
        window.marker = new BMap.Marker(point, { icon: myIcon });  // 创建标注
        mapInit.addOverlay(marker);               // 将标注添加到地图中
        marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
      }
    }
    //添加行驶和终点图标
    function addMarkerEnd(point, name, mapInit, trackUnit, prePoint) {
      if (name == "小车行驶") {
        if (carMk) {//先判断第一次进来的时候这个值有没有定义,有的话就清除掉上一次的。然后在进行画图标。第一次进来时候没有定义也就不走这块,直接进行画图标
          mapInit.removeOverlay(carMk);
        }
        carMk = new BMap.Marker(point, { icon: drivingPoint });  // 创建标注
        carMk.setRotation(trackUnit.route);//trackUnit.route
        //getAngle(point,prePoint);// js求解两点之间的角度
        carMk.setRotation(getAngle(point, prePoint) - 90);// 旋转的角度
        mapInit.addOverlay(carMk);               // 将标注添加到地图中
        //carMk.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
      } else {
        mapInit.removeOverlay(carMk);
        carMk = new BMap.Marker(point, { icon: terminalPoint });  // 创建标注
        mapInit.addOverlay(carMk);
      }
    }
    //获得角度的函数
    function getAngle(n, next) {
      var ret
      var w1 = n.lat / 180 * Math.PI
      var j1 = n.lng / 180 * Math.PI

      var w2 = next.lat / 180 * Math.PI
      var j2 = next.lng / 180 * Math.PI

      ret = 4 * Math.pow(Math.sin((w1 - w2) / 2), 2) - Math.pow(Math.sin((j1 - j2) / 2) * (Math.cos(w1) - Math.cos(w2)), 2);
      ret = Math.sqrt(ret);

      // var temp = Math.sin(Math.abs(j1 - j2) / 2) * (Math.cos(w1) + Math.cos(w2));
      var temp = Math.sin((j1 - j2) / 2) * (Math.cos(w1) + Math.cos(w2));
      console.log(temp)
      ret = ret / temp;

      ret = Math.atan(ret) / Math.PI * 180;
      ret += 90;

      // 这里用如此臃肿的if..else是为了判定追踪单个点的具体情况,从而调整ret的值
      if (j1 - j2 < 0) {
        // console.log('j1<j2')
        if (w1 - w2 < 0) {
          // console.log('w1<w2')
          ret;
        } else {
          // console.log('w1>w2')
          ret = -ret + 180;
        }
      } else {
        // console.log('j1>j2')
        if (w1 - w2 < 0) {
          // console.log('w1<w2')
          ret = 180 + ret;
        } else {
          // console.log('w1>w2')
          ret = -ret;
        }
      }
      return ret;
    }

    function getLocation() {
      var options = {
        enableHighAccuracy: true,
        maximumAge: 1000
      }
      if (navigator.geolocation) {
        //浏览器支持geolocation
        // alert("浏览器支持geolocation");
        navigator.geolocation.getCurrentPosition(onSuccess, onError, options);

      } else {
        //浏览器不支持geolocation
        alert("浏览器不支持geolocation");
      }
    }
    var lng = "";
    var lat = "";
    var str = "";
    var count = 1;
    function onSuccess(pos) {
      var bd = GpsToBaiduPoint(pos.coords);
      document.getElementById('message').innerHTML += '经度变化:' + Math.abs(bd.lng - lng) + '纬度变化:' + Math.abs(bd.lat - lat) + '<br/>';
      if (Math.abs(bd.lng - lng) <= 0.000001 && Math.abs(bd.lat - lat) <= 0.000001) {
        console.log("位置未移动或者变化不大");
      }
      else {
        lat = bd.lat;
        lng = bd.lng;
        str += bd.lng + "|" + bd.lat + ",";
        var poin = str.substr(0, str.length - 1).split(",");
        if (count > 1) {
          drowLine(map, poin[count - 2].split("|"), poin[count - 1].split("|"));//画线调用
          map.setViewport([new BMap.Point(poin[count - 1].split("|")[0], poin[count - 1].split("|")[1])]); //根据提供的地理区域或坐标设置地图视野
        }
        count += 1;
      }

      lng = pos.coords.longitude;
      lat = pos.coords.latitude;
    }
    function onError(error) {
      switch (error.code) {

        case 1:
          alert("位置服务被拒绝");
          break;

        case 2:
          alert("暂时获取不到位置信息");
          break;

        case 3:
          alert("获取信息超时");
          break;

        case 4:
          alert("未知错误");
          break;
      }

    }

    function GpsToBaiduPoint(point) {
      var _t = wgs2bd(point.latitude, point.longitude);
      var _BPoint = new BMap.Point(_t[1], _t[0]);
      return _BPoint;
    }

    var pi = 3.14159265358979324;
    var a = 6378245.0;
    var ee = 0.00669342162296594323;
    var x_pi = 3.14159265358979324 * 3000.0 / 180.0;


    //世界大地坐标转为百度坐标
    function wgs2bd(lat, lon) {
      var wgs2gcjR = wgs2gcj(lat, lon);
      var gcj2bdR = gcj2bd(wgs2gcjR[0], wgs2gcjR[1]);
      return gcj2bdR;
    }
    function gcj2bd(lat, lon) {
      var x = lon, y = lat;
      var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
      var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
      var bd_lon = z * Math.cos(theta) + 0.0065;
      var bd_lat = z * Math.sin(theta) + 0.006;
      var result = [];
      result.push(bd_lat);
      result.push(bd_lon);
      return result;
    }

    function bd2gcj(lat, lon) {
      var x = lon - 0.0065, y = lat - 0.006;
      var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
      var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
      var gg_lon = z * Math.cos(theta);
      var gg_lat = z * Math.sin(theta);
      var result = [];
      result.push(gg_lat);
      result.push(gg_lon);
      return result;
    }

    function wgs2gcj(lat, lon) {
      var dLat = transformLat(lon - 105.0, lat - 35.0);
      var dLon = transformLon(lon - 105.0, lat - 35.0);
      var radLat = lat / 180.0 * pi;
      var magic = Math.sin(radLat);
      magic = 1 - ee * magic * magic;
      var sqrtMagic = Math.sqrt(magic);
      dLat = (dLat * 180.0) / ((a * (1 - ee)) / (magic * sqrtMagic) * pi);
      dLon = (dLon * 180.0) / (a / sqrtMagic * Math.cos(radLat) * pi);
      var mgLat = lat + dLat;
      var mgLon = lon + dLon;
      var result = [];
      result.push(mgLat);
      result.push(mgLon);
      return result;
    }

    function transformLat(lat, lon) {
      var ret = -100.0 + 2.0 * lat + 3.0 * lon + 0.2 * lon * lon + 0.1 * lat * lon + 0.2 * Math.sqrt(Math.abs(lat));
      ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
      ret += (20.0 * Math.sin(lon * pi) + 40.0 * Math.sin(lon / 3.0 * pi)) * 2.0 / 3.0;
      ret += (160.0 * Math.sin(lon / 12.0 * pi) + 320 * Math.sin(lon * pi / 30.0)) * 2.0 / 3.0;
      return ret;
    }

    function transformLon(lat, lon) {
      var ret = 300.0 + lat + 2.0 * lon + 0.1 * lat * lat + 0.1 * lat * lon + 0.1 * Math.sqrt(Math.abs(lat));
      ret += (20.0 * Math.sin(6.0 * lat * pi) + 20.0 * Math.sin(2.0 * lat * pi)) * 2.0 / 3.0;
      ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
      ret += (150.0 * Math.sin(lat / 12.0 * pi) + 300.0 * Math.sin(lat / 30.0 * pi)) * 2.0 / 3.0;
      return ret;
    }
  </script>
</body>

</html>

原文链接:https://www.idaobin.com/archives/2267.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

− 4 = 1