currentPosition.html 8.92 KB
<!DOCTYPE html>
<html lang="en">
<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=uOoek3DMnG1Zor4gW8plPaAH1tuDFdbq"></script>
<!--	导入依赖的js-->
<!--加载鼠标绘制工具-->
<script type="text/javascript" src="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>

<link rel="stylesheet" href="http://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />
<!--百度地图api-->
<script type="text/javascript" src="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.js"></script>
<!--高德地图api-->
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=4eb1af3a9376f8e741ba7a7829f25fa3"></script>
<script type="text/javascript" src="http://api.map.baidu.com/library/GeoUtils/1.2/src/GeoUtils_min.js"></script>
<link rel="stylesheet" href="http://api.map.baidu.com/library/SearchInfoWindow/1.4/src/SearchInfoWindow_min.css" />
<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<script src='http://res.wx.qq.com/open/js/jweixin-1.6.0.js'></script>
<title>用户位置校验工具</title>
<head>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
  <meta charset="UTF-8">
  <title>Title</title>
  <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
</head>
<style>
  html,body,#container{
    height:100%;
  }
  .info{
    width:30rem;
  }
</style>
<body>
<div id="allmap" style="overflow:hidden;zoom:1;position:relative;">
  <div id="map" style="height:100%;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;"></div>
</div>
<!--<div id='container'></div>-->
<div class="info">
  <h4 id='status'></h4><hr>
  <p id='result'></p><hr>
</div>
<!--<p>地理坐标:<br/><span id="latlon"></span></p>-->
<!--<div class="geo">-->
<!--  <p>百度地图定位位置:</p>-->
<!--  <p id="baidu_geo"></p>-->
<!--</div>-->
<script type="text/javascript">
  // 百度地图API功能
  var BDmap = new BMap.Map('map');

  // 高德地图api获取用户位置
  var map = new AMap.Map('container', {
    resizeEnable: true
  });


  //解析定位结果
  function onComplete(data) {
    document.getElementById('status').innerHTML='获取定位信息成功'
    var str = [];
    str.push('定位结果:' + data.position );
    str.push('定位类别:' + data.location_type);
    if(data.accuracy){
      str.push(' 精度:' + data.accuracy + '米');
    }//如为IP精确定位结果则没有精度信息
    // str.push('是否经过偏移:' + (data.isConverted ? '是' : '否'));
    document.getElementById('result').innerHTML = str.join('<br>');
    showPosition(data.position);
  }

  //解析定位错误信息
  function onError(data) {
    document.getElementById('status').innerHTML='定位失败'
    document.getElementById('result').innerHTML = '失败原因排查信息:'+data.message;
  }

  function showPosition(position) {
    // $("#latlon").html("纬度:" + position.coords.latitude + ',经度:' + position.coords.longitude);
    //  // 坐标转换:经度在前,纬度在后(经度,纬度)
    //  // 逆地理编码:纬度在前,经度在后(纬度,经度)
    //  var latlon = position.coords.longitude + ',' + position.coords.latitude;
    var latlon = position.R + ',' + position.Q;
    var changeLatlon = '';
     // 百度地图坐标转换
    var changeUrl = 'http://api.map.baidu.com/geoconv/v1/?coords=' + latlon + '&from=1&to=5&ak=uOoek3DMnG1Zor4gW8plPaAH1tuDFdbq';
    $.ajax({
           type: "GET",
           dataType: "jsonp",
           url: changeUrl,
           success: function (json) {
               if (json.status == 0) {
                     $.each(json.result,function (i,v) {
                           // 逆地理编码:纬度在前,经度在后
                          changeLatlon = v.y + ',' + v.x;
                       });
                     //百度地图逆地理编码
                     var url = "http://api.map.baidu.com/geocoder/v2/?ak=lRRyy6qoBwnAgj3w4ugGFqoSsWC8du3v&callback=renderReverse&location=" + changeLatlon + "&output=json&pois=0";
                     $.ajax({
                           type: "GET",
                           dataType: "jsonp",
                           url: url,
                           beforeSend: function () {
                             $("#status").html('正在解析电子围栏信息...');
                          },
                         success: function (json) {
                             debugger
                             if (json.status == 0) {
                               $("#status").html('解析成功!');
                               var str = [];
                               var content = document.getElementById('result').innerHTML;
                               str.push(content);
                               str.push('地图位置:' + json.result.formatted_address);
                               let lat = json.result.location.lat;
                               let lng = json.result.location.lng;
                               if (IsInPolygon(lat, lng)){
                                 str.push('是否在电子围栏范围内:是');
                               }else {
                                 str.push('是否在电子围栏范围内:否');
                               }
                               document.getElementById('result').innerHTML = str.join('<br>');

                               // $("#baidu_geo").html(json.result.formatted_address);
                             }
                          },
                         error: function (XMLHttpRequest, textStatus, errorThrown) {
                               $("#result").html(changeLatlon + "的地址位置获取失败");
                           }
                    });
                 }
           },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
               alert("坐标转换失败");
           }
    });
  }

  function getElectricFence(){
    var ctx = "http://yb.huahengcloud.com/jeecg-boot";
    $.ajax({
      timeout: 10000, //超时时间设置为10秒
      contentType:"application/json",//传给服务器的数据类型
      dataType:"json", //接收服务器传来的数据格式
      type: "get",
      async:false, // async异步 false改为同步
      url:  "/fence/electricFence/list",
      data: {
        "state":"Y",
      },
      success:function (res) {
        if (res.success){
          var data = res.result.records;
          for (var p in data){
            let point = dataAnalysis(data[p].coordinate);
            let polArry = [];
            point.forEach(item => {
              let p = new BMap.Point(item.lng,item.lat);
              polArry.push(p);
            });
            polygon = new BMap.Polygon(polArry,styleOptions);
            // BDmap.addOverlay(polygon);
          }
        }
      },
      error:function () {
        alert("查询失败!");
      }
    });
  }
  function dataAnalysis(data){
    let str = data.replace('POLYGON((','').replace('))','').split(',');
    let result = [];
    for (let i = 0;i < str.length; i++){
      let temp = str[i].split(' ');
      result.push({'lng':temp[0], 'lat': temp[1]});
    }
    return result;
  }

  function IsInPolygon(lat, lng){
    let point = new BMap.Point(lng,lat);
    // let marker = new BMap.Marker(point);
    // BDmap.addOverlay(marker);
    debugger
    if(BMapLib.GeoUtils.isPointInPolygon(point,polygon)){
      console.log("在区域内");
      return true;
    }else{
      console.log("不再区域内");
      return false;
    }

  }


  let styleOptions = {
    strokeColor:"red",    //边线颜色。
    fillColor:"red",      //填充颜色。当参数为空时,圆形将没有填充效果。
    strokeWeight: 3,       //边线的宽度,以像素为单位。
    strokeOpacity: 0.8,	   //边线透明度,取值范围0 - 1。
    fillOpacity: 0.6,      //填充的透明度,取值范围0 - 1。
    strokeStyle: 'solid' //边线的样式,solid或dashed。
  }
  let polygon;


  // 页面加载之前
  $(document).ready(function(){
    getElectricFence();
    AMap.plugin('AMap.Geolocation', function() {
      var geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位,默认:true
        timeout: 10000,          //超过10秒后停止定位,默认:5s
        buttonPosition:'RB',    //定位按钮的停靠位置
        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
        zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点

      });
      map.addControl(geolocation);
      geolocation.getCurrentPosition(function(status,result){
        if(status=='complete'){
          onComplete(result)
        }else{
          onError(result)
        }
      });
    });
  });


</script>
</body>
</html>