百度地图判断当前位置是否在N多个多边形范围里面与画线

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


恰饭广告




  注意:

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

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

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

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

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

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body,
        html,
        #allmap {
            width: 100%;
            height: 100%;
            overflow: hidden;
            margin: 0;
            font-family: "微软雅黑";
        }
    </style>
    <script type="text/javascript"
        src="https://api.map.baidu.com/api?v=2.0&ak=自己申请"></script>
    <script type="text/javascript" src="GeoUtils.js"></script>
    <!--加载鼠标绘制工具-->
    <script type="text/javascript"
        src="https://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.js"></script>
    <link rel="stylesheet" href="https://api.map.baidu.com/library/DrawingManager/1.4/src/DrawingManager_min.css" />


    <title>多边形区域判断</title>
</head>

<body>
    <div>可以把地图缩小,看一下多边形范围画在哪</div>
    <button id="daka">判定</button>
    <button onclick="clearAll()">撤销刚画出来的全部</button>
    <button onclick="getPath()">获取画出来的范围坐标</button>
    <div id="allmap" style="height:100%;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;">
    </div>
</body>

</html>
<script type="text/javascript">
    getMyLocation();
    function getMyLocation() {
        if (navigator.geolocation) {
            //判断是否有这个对象
            navigator.geolocation.getCurrentPosition(function (pos) {
                var bd = GpsToBaiduPoint(pos.coords);
                var list = new Array();
                list.push(bd);
                initialize(list);

                var marker = new BMap.Marker(list[0]); //将点转化成标注点
                map.addOverlay(marker);  //将标注点添加到地图上
                marker.addEventListener('click', function () {
                    alert("你的位置");
                })
            })
        } else {
            console.log("当前系统不支持GPS API")
        }
    }

    function getPath() {
        alert(mypath);
    }

    //创建地图
    var map = new BMap.Map("allmap");
    var myrange = [];
    var myrangearr = [];

    //创建多边形  
    var poly = [{ "adress": "[{\"lng\":102.368698,\"lat\":25.614778},{\"lng\":102.738944,\"lat\":25.044171},{\"lng\":103.85428,\"lat\":25.054646},{\"lng\":103.85428,\"lat\":25.925055}]", "carid": "司机1", "place": "多边形" }, { "adress": "[{\"lng\":101.389042,\"lat\":25.297413},{\"lng\":101.642005,\"lat\":25.104913},{\"lng\":101.731692,\"lat\":25.866811}]", "carid": "司机1", "place": "三角形" }];

    getRange(poly);

    function getRange(poly) {
        var range = [];
        var rangearr = [];
        var polygon = "";
        var polygonarr = [];
        for (var j = 0; j < poly.length; j++) {
            var len = JSON.parse(poly[j].adress);
            for (var i = 0; i < len.length; i++) {
                range.push(new BMap.Point(len[i].lng, len[i].lat));
                rangearr.push(new BMap.Point(len[i].lng, len[i].lat));
            }
            range.push(poly[j].place);
            polygon = new BMap.Polygon(range, { strokeColor: "#f50704", fillColor: "#cfcfcf", strokeWeight: 3, strokeOpacity: 0, fillOpacity: 0, });
            map.addOverlay(polygon);
            polygonarr.push(polygon);

            myrange.push(range);
            myrangearr.push(rangearr);
            polygonarr[j].addEventListener('click', function () {
                alert(this.to[this.to.length - 1])
            })
            range = [];
            rangearr=[];
        }
    }

    function showInfo(thisMarker, point) {
        var mypolygon = "";
        var range2 = [];
        for (var x = 0; x < myrangearr.length; x++) {
            var len = myrangearr[x];
            for (var i = 0; i < len.length; i++) {
                range2.push(new BMap.Point(len[i].lng, len[i].lat));
            }
            mypolygon = new BMap.Polygon(range2);
            // //判断点是否在
            if (BMapLib.GeoUtils.isPointInPolygon(point, mypolygon)) {
                alert(poly[x].carid + "在" + poly[x].place + "区域内");
            } else {
                alert(poly[x].carid + "不在" + poly[x].place + "区域内");
            }
            range2 = [];
        }

    }


    function initialize(bdpoint) {
        // 百度地图API功能  
        map.addControl(new BMap.NavigationControl());               // 添加平移缩放控件  
        map.addControl(new BMap.ScaleControl());                    // 添加比例尺控件  
        map.addControl(new BMap.OverviewMapControl());              //添加缩略地图控件  
        map.enableScrollWheelZoom();                            //启用滚轮放大缩小   

        var point = new BMap.Point(bdpoint[0].lng, bdpoint[0].lat);    // 创建点坐标  
        map.centerAndZoom(point, 10);                      // 初始化地图,设置中心点坐标和地图级别。  


        //点击事件
        var btn = document.getElementById("daka");
        btn.addEventListener("click",
            function () {
                showInfo(this, bdpoint[0]);
            });
    }

    //画图
    //鼠标绘制完成回调方法   获取各个点的经纬度
    var overlays = [];
    var mypath = "";
    var overlaycomplete = function (e) {
        overlays.push(e.overlay);
        var path = e.overlay.getPath();//Array<Point> 返回多边型的点数组
        mypath = JSON.stringify(path);
        console.log(mypath);
    };

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

    //实例化鼠标绘制工具
    var drawingManager = new BMapLib.DrawingManager(map, {
        isOpen: false, //是否开启绘制模式
        enableDrawingTool: true, //是否显示工具栏
        drawingMode: BMAP_DRAWING_POLYGON,//绘制模式  多边形
        drawingToolOptions: {
            anchor: BMAP_ANCHOR_TOP_RIGHT, //位置
            offset: new BMap.Size(5, 5), //偏离值
            drawingModes: [
                BMAP_DRAWING_POLYGON
            ]
        },
        polygonOptions: styleOptions //多边形的样式
    });

    //添加鼠标绘制工具监听事件,用于获取绘制结果
    drawingManager.addEventListener('overlaycomplete', overlaycomplete);
    
    //清除刚画出的所有线
    function clearAll() {
        for (var i = 0; i < overlays.length; i++) {
            map.removeOverlay(overlays[i]);
        }
        overlays.length = 0
    }


    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>

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

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

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



恰饭广告

发表评论

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

64 − 60 =