码迷,mamicode.com
首页 > 其他好文 > 详细

百度地图实现测量面积和测量距离功能

时间:2020-05-06 12:08:02      阅读:928      评论:0      收藏:0      [点我收藏+]

标签:int   this   linu   key   filter   agent   index   png   efi   

最近在公司的项目中,需要用到百度地图的测距和测面积功能,但是在网上只找到了测量距离的api,即BMapLib.DistanceTool。

但是测面积在网上没有找到很好的资料,百度提供的DrawingManager虽然也可以实现测面积,但是感觉太lol了,然后继续找资料,发现有人跟我遇到同样的问题,他的解决思路是对BMapLib.DistanceTool进行改造,但遗憾的是没有提供源码。

我也想过要改造BMapLib.DistanceTool,但是这个对我来说很有挑战性,毕竟js我差不多是小白,今天闲来无事,决定一试。下载了BMapLib.DistanceTool的源码看,大部分都看不懂,呵呵,不过我要做的工作就是在事件处理中加入自己的逻辑,寻着这个思路,经过几番折腾,终于搞定了,整体效果自己还比较满意。

好了,废话不多说,接下来进入重点,我把百度地图实现测量面积源码公布下(Java成长交流学习群:184998348),代码下载地址:https://download.csdn.net/download/hgq0916/10579481。分享给大家,若有大神路过,别见怪,哈哈。

首先来张效果图:

 

技术图片

 

 

下面是源码:

1.measureAreaTool_baidu.html

 1 <!DOCTYPE html>    
 2 <html>    
 3 <head>    
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    
 5     <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />    
 6     <style type="text/css">    
 7     body, html{width: 100%;height: 100%;margin:0;font-family:"微软雅黑";}    
 8     #allmap {width: 100%; height:500px; overflow: hidden;}    
 9     #result {width:100%;font-size:12px;}    
10     </style>
11      <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的AK"></script>    
12     <script src="js/GeoUtils.js" type="text/javascript"></script>
13     <script type="text/javascript" src="js/AreaTool_min.js"></script>
14     <title>百度地图API功能演示</title>
15 </head>    
16 <body>
17     <div id="allmap" style="overflow:hidden;zoom:1;position:relative;">       
18         <div id="map" style="height:100%;-webkit-transition: all 0.5s ease-in-out;transition: all 0.5s ease-in-out;">    
19        </div>    
20     </div>
21     <div id="result">    
22         <input type="button"  value="面积测量" οnclick="measureArea(this)" /><br/>
23     </div>
24  
25 <script type="text/javascript">    
26     var map = new BMap.Map(‘map‘);
27     var poi = new BMap.Point(113.948913,22.530844);    
28     map.centerAndZoom(poi, 16);    
29     map.enableScrollWheelZoom();
30     //添加测量面积工具
31        var measureAreaTool = createMeasureAreaTool(map);
32     //面积测量
33     var measureArea = function(e){
34         measureAreaTool.open();
35     }
36 </script>
37 </body>    
38 </html>    

2.依赖的js

 

2.1  百度地图的核心js文件,这个用于显示百度地图的,不多说

2.2    AreaTool_min.js  这个就是我改造百度地图测距js后自己创建的测面积工具,完成对面积的测量

   1  // 百度地图API功能
   2 var BMapLib = window.BMapLib = BMapLib || {}; (function() {
   3     var c = c || {
   4         guid: "$BAIDU$"
   5     }; (function() {
   6         window[c.guid] = {};
   7         c.extend = function(g, e) {
   8             for (var f in e) {
   9                 if (e.hasOwnProperty(f)) {
  10                     g[f] = e[f]
  11                 }
  12             }
  13             return g
  14         };
  15         c.lang = c.lang || {};
  16         c.lang.guid = function() {
  17             return "TANGRAM__" + (window[c.guid]._counter++).toString(36)
  18         };
  19         window[c.guid]._counter = window[c.guid]._counter || 1;
  20         window[c.guid]._instances = window[c.guid]._instances || {};
  21         c.lang.Class = function(e) {
  22             this.guid = e || c.lang.guid();
  23             window[c.guid]._instances[this.guid] = this
  24         };
  25         window[c.guid]._instances = window[c.guid]._instances || {};
  26         c.lang.isString = function(e) {
  27             return "[object String]" == Object.prototype.toString.call(e)
  28         };
  29         c.lang.isFunction = function(e) {
  30             return "[object Function]" == Object.prototype.toString.call(e)
  31         };
  32         c.lang.Class.prototype.toString = function() {
  33             return "[object " + (this._className || "Object") + "]"
  34         };
  35         c.lang.Class.prototype.dispose = function() {
  36             delete window[c.guid]._instances[this.guid];
  37             for (var e in this) {
  38                 if (!c.lang.isFunction(this[e])) {
  39                     delete this[e]
  40                 }
  41             }
  42             this.disposed = true
  43         };
  44         c.lang.Event = function(e, f) {
  45             this.type = e;
  46             this.returnValue = true;
  47             this.target = f || null;
  48             this.currentTarget = null
  49         };
  50         c.lang.Class.prototype.addEventListener = function(h, g, f) {
  51             if (!c.lang.isFunction(g)) {
  52                 return
  53             } ! this.__listeners && (this.__listeners = {});
  54             var e = this.__listeners,
  55             i;
  56             if (typeof f == "string" && f) {
  57                 if (/[^\w\-]/.test(f)) {
  58                     throw ("nonstandard key:" + f)
  59                 } else {
  60                     g.hashCode = f;
  61                     i = f
  62                 }
  63             }
  64             h.indexOf("on") != 0 && (h = "on" + h);
  65             typeof e[h] != "object" && (e[h] = {});
  66             i = i || c.lang.guid();
  67             g.hashCode = i;
  68             e[h][i] = g
  69         };
  70         c.lang.Class.prototype.removeEventListener = function(g, f) {
  71             if (c.lang.isFunction(f)) {
  72                 f = f.hashCode
  73             } else {
  74                 if (!c.lang.isString(f)) {
  75                     return
  76                 }
  77             } ! this.__listeners && (this.__listeners = {});
  78             g.indexOf("on") != 0 && (g = "on" + g);
  79             var e = this.__listeners;
  80             if (!e[g]) {
  81                 return
  82             }
  83             e[g][f] && delete e[g][f]
  84         };
  85         c.lang.Class.prototype.dispatchEvent = function(h, e) {
  86             if (c.lang.isString(h)) {
  87                 h = new c.lang.Event(h)
  88             } ! this.__listeners && (this.__listeners = {});
  89             e = e || {};
  90             for (var g in e) {
  91                 h[g] = e[g]
  92             }
  93             var g, f = this.__listeners,
  94             j = h.type;
  95             h.target = h.target || this;
  96             h.currentTarget = this;
  97             j.indexOf("on") != 0 && (j = "on" + j);
  98             c.lang.isFunction(this[j]) && this[j].apply(this, arguments);
  99             if (typeof f[j] == "object") {
 100                 for (g in f[j]) {
 101                     f[j][g].apply(this, arguments)
 102                 }
 103             }
 104             return h.returnValue
 105         };
 106         c.lang.inherits = function(k, i, h) {
 107             var g, j, e = k.prototype,
 108             f = new Function();
 109             f.prototype = i.prototype;
 110             j = k.prototype = new f();
 111             for (g in e) {
 112                 j[g] = e[g]
 113             }
 114             k.prototype.constructor = k;
 115             k.superClass = i.prototype;
 116             if ("string" == typeof h) {
 117                 j._className = h
 118             }
 119         };
 120         c.dom = c.dom || {};
 121         c._g = c.dom._g = function(e) {
 122             if (c.lang.isString(e)) {
 123                 return document.getElementById(e)
 124             }
 125             return e
 126         };
 127         c.g = c.dom.g = function(e) {
 128             if ("string" == typeof e || e instanceof String) {
 129                 return document.getElementById(e)
 130             } else {
 131                 if (e && e.nodeName && (e.nodeType == 1 || e.nodeType == 9)) {
 132                     return e
 133                 }
 134             }
 135             return null
 136         };
 137         c.insertHTML = c.dom.insertHTML = function(h, e, g) {
 138             h = c.dom.g(h);
 139             var f, i;
 140             if (h.insertAdjacentHTML) {
 141                 h.insertAdjacentHTML(e, g)
 142             } else {
 143                 f = h.ownerDocument.createRange();
 144                 e = e.toUpperCase();
 145                 if (e == "AFTERBEGIN" || e == "BEFOREEND") {
 146                     f.selectNodeContents(h);
 147                     f.collapse(e == "AFTERBEGIN")
 148                 } else {
 149                     i = e == "BEFOREBEGIN";
 150                     f[i ? "setStartBefore": "setEndAfter"](h);
 151                     f.collapse(i)
 152                 }
 153                 f.insertNode(f.createContextualFragment(g))
 154             }
 155             return h
 156         };
 157         c.ac = c.dom.addClass = function(k, m) {
 158             k = c.dom.g(k);
 159             var f = m.split(/\s+/),
 160             e = k.className,
 161             j = " " + e + " ",
 162             h = 0,
 163             g = f.length;
 164             for (; h < g; h++) {
 165                 if (j.indexOf(" " + f[h] + " ") < 0) {
 166                     e += (e ? " ": "") + f[h]
 167                 }
 168             }
 169             k.className = e;
 170             return k
 171         };
 172         c.event = c.event || {};
 173         c.event._listeners = c.event._listeners || [];
 174         c.on = c.event.on = function(f, i, k) {
 175             i = i.replace(/^on/i, "");
 176             f = c._g(f);
 177             var j = function(m) {
 178                 k.call(f, m)
 179             },
 180             e = c.event._listeners,
 181             h = c.event._eventFilter,
 182             l,
 183             g = i;
 184             i = i.toLowerCase();
 185             if (h && h[i]) {
 186                 l = h[i](f, i, j);
 187                 g = l.type;
 188                 j = l.listener
 189             }
 190             if (f.addEventListener) {
 191                 f.addEventListener(g, j, false)
 192             } else {
 193                 if (f.attachEvent) {
 194                     f.attachEvent("on" + g, j)
 195                 }
 196             }
 197             e[e.length] = [f, i, k, j, g];
 198             return f
 199         };
 200         c.un = c.event.un = function(g, j, f) {
 201             g = c._g(g);
 202             j = j.replace(/^on/i, "").toLowerCase();
 203             var m = c.event._listeners,
 204             h = m.length,
 205             i = !f,
 206             l, k, e;
 207             while (h--) {
 208                 l = m[h];
 209                 if (l[1] === j && l[0] === g && (i || l[2] === f)) {
 210                     k = l[4];
 211                     e = l[3];
 212                     if (g.removeEventListener) {
 213                         g.removeEventListener(k, e, false)
 214                     } else {
 215                         if (g.detachEvent) {
 216                             g.detachEvent("on" + k, e)
 217                         }
 218                     }
 219                     m.splice(h, 1)
 220                 }
 221             }
 222             return g
 223         };
 224         c.preventDefault = c.event.preventDefault = function(e) {
 225             if (e.preventDefault) {
 226                 e.preventDefault()
 227             } else {
 228                 e.returnValue = false
 229             }
 230         }
 231     })();
 232     //TODO
 233     var d = BMapLib.MeasureAreaTool = function(f, e) {
 234         if (!f) {
 235             return
 236         }
 237         this._map = f;
 238         e = e || {};
 239         this._opts = c.extend(c.extend(this._opts || {},
 240         {
 241             tips: "\u6d4b\u8ddd",
 242             followText: "\u5355\u51fb\u786e\u5b9a\u5730\u70b9\uff0c\u53cc\u51fb\u7ed3\u675f",
 243             unit: "metric",
 244             lineColor: "#ff6319",
 245             lineStroke: 2,
 246             opacity: 0.8,
 247             lineStyle: "solid",
 248             cursor: "http://api.map.baidu.com/images/ruler.cur",
 249             secIcon: null,
 250             closeIcon: null
 251         }), e);
 252         this._followTitle = null;
 253         this._points = [];
 254         this._paths = [];
 255         this._dots = [];
 256         this._segDistance = [];
 257         this._overlays = [];
 258         this._enableMassClear = true,
 259         this._units = {
 260             metric: {
 261                 name: "metric",
 262                 conv: 1,
 263                 incon: 1000,
 264                 u1: "\u7c73",
 265                 u2: "\u516c\u91cc"
 266             },
 267             us: {
 268                 name: "us",
 269                 conv: 3.2808,
 270                 incon: 5279.856,
 271                 u1: "\u82f1\u5c3a",
 272                 u2: "\u82f1\u91cc"
 273             }
 274         };
 275         this._isOpen = false;
 276         this._startFollowText = "\u5355\u51fb\u786e\u5b9a\u8d77\u70b9";
 277         this._movingTimerId = null;
 278         this._styles = {
 279             BMapLib_diso: "height:17px;width:5px;position:absolute;background:url(http://api.map.baidu.com/images/dis_box_01.gif) no-repeat left top",
 280             BMapLib_disi: "color:#7a7a7a;position:absolute;left:5px;padding:0 4px 1px 0;line-height:17px;background:url(http://api.map.baidu.com/images/dis_box_01.gif) no-repeat right top",
 281             BMapLib_disBoxDis: "color:#ff6319;font-weight:bold"
 282         };
 283         if (this._opts.lineStroke <= 0) {
 284             this._opts.lineStroke = 2
 285         }
 286         if (this._opts.opacity > 1) {
 287             this._opts.opacity = 1
 288         } else {
 289             if (this._opts.opacity < 0) {
 290                 this._opts.opacity = 0
 291             }
 292         }
 293         if (this._opts.lineStyle != "solid" && this._opts.lineStyle != "dashed") {
 294             this._opts.lineStyle = "solid"
 295         }
 296         if (!this._units[this._opts.unit]) {
 297             this._opts.unit = "metric"
 298         }
 299         this.text = "\u6d4b\u8ddd"
 300     };
 301     c.lang.inherits(d, c.lang.Class, "DistanceTool");
 302     d.prototype._bind = function() {
 303         this._setCursor(this._opts.cursor);
 304         var f = this;
 305         c.on(this._map.getContainer(), "mousemove",
 306         function(i) {
 307             if (!f._isOpen) {
 308                 return
 309             }
 310             if (!f._followTitle) {
 311                 return
 312             }
 313             i = window.event || i;
 314             var g = i.target || i.srcElement;
 315             if (g != a.getDom(f._map)) {
 316                 f._followTitle.hide();
 317                 return
 318             }
 319             if (!f._mapMoving) {
 320                 f._followTitle.show()
 321             }
 322             var h = a.getDrawPoint(i, true);
 323             f._followTitle.setPosition(h)
 324         });
 325         if (this._startFollowText) {
 326             var e = this._followTitle = new BMap.Label(this._startFollowText, {
 327                 offset: new BMap.Size(14, 16)
 328             });
 329             this._followTitle.setStyles({
 330                 color: "#333",
 331                 borderColor: "#ff0103"
 332             })
 333         }
 334     };
 335     d.prototype.open = function() {
 336         if (this._isOpen == true) {
 337             return true
 338         }
 339         if ( !! BMapLib._toolInUse) {
 340             return
 341         }
 342         this._isOpen = true;
 343         BMapLib._toolInUse = true;
 344         if (this._mapMoving) {
 345             delete this._mapMoving
 346         }
 347         var h = this;
 348         if (!this._binded) {
 349             this._binded = true;
 350             this._bind();
 351             this._map.addEventListener("moving",
 352             function() {
 353                 h._hideCurrent()
 354             })
 355         }
 356         if (this._followTitle) {
 357             this._map.addOverlay(this._followTitle);
 358             this._followTitle.hide()
 359         }
 360         var g = function(q) {
 361             //TODO
 362             var l = h._map;//获取map对象
 363             if (!h._isOpen) {//判断测距工具是否打开,关闭则返回
 364                 return
 365             }
 366             q = window.event || q;
 367             var n = a.getDrawPoint(q, true);//获取鼠标点击的点
 368             if (!h._isPointValid(n)) {//判断点是否有效
 369                 return
 370             }
 371             h._bind.initX = q.pageX || q.clientX || 0;//绑定当前的坐标
 372             h._bind.initY = q.pageY || q.clientY || 0;
 373             if (h._points.length > 0) {
 374                 var t = l.pointToPixel(h._points[h._points.length - 1]);//获取点数组最后一个元素,转换为Pixel点
 375                 var m = l.pointToPixel(n);//将当前的点转换为Pixel点
 376                 var p = Math.sqrt(Math.pow(t.x - m.x, 2) + Math.pow(t.y - m.y, 2));//求两个点的距离
 377                 if (p < 5) {//距离小于5则返回
 378                     return
 379                 }
 380             }
 381             h._bind.x = q.layerX || q.offsetX || 0;//保存当前坐标
 382             h._bind.y = q.layerY || q.offsetY || 0;
 383             h._points.push(n);//将当前坐标存入数组
 384             h._addSecPoint(n);//TODO
 385             if (h._paths.length == 0) {
 386                 h._formatTitle(1, h._opts.followText, h._getTotalDistance())
 387             }
 388             if (h._paths.length > 0) {
 389                 h._paths[h._paths.length - 1].show();
 390                 h._paths[h._paths.length - 1].setStrokeOpacity(h._opts.opacity)
 391             }
 392             var w = new BMap.Polyline([n, n], {
 393                 enableMassClear: h._enableMassClear
 394             });
 395             h._map.addOverlay(w);
 396             h._paths.push(w);
 397             h._overlays.push(w);
 398             w.setStrokeWeight(h._opts.lineStroke);
 399             w.setStrokeColor(h._opts.lineColor);
 400             w.setStrokeOpacity(h._opts.opacity / 2);
 401             w.setStrokeStyle(h._opts.lineStyle);
 402             if (h._mapMoving) {
 403                 w.hide()
 404             }
 405             if (h._points.length > 1) {
 406                 var o = h._paths[h._points.length - 2];
 407                 o.setPositionAt(1, n)
 408             }
 409             var r = "";
 410             var v;
 411             if (h._points.length > 1) {
 412                 var u = h._setSegDistance(h._points[h._points.length - 2], h._points[h._points.length - 1]);
 413                 var s = h._getTotalDistance();
 414                 r = h._formatDisStr(s);
 415                 v = new BMap.Label(r, {
 416                     offset: new BMap.Size(10, -5),
 417                     enableMassClear: h._enableMassClear
 418                 });
 419             } else {
 420                 r = "\u8d77\u70b9";
 421                 v = new BMap.Label(r, {
 422                     offset: new BMap.Size(-10, -25),
 423                     enableMassClear: h._enableMassClear
 424                 });
 425             }
 426             // var v = new BMap.Label(r, {
 427             //     offset: new BMap.Size(10, -5),
 428             //     enableMassClear: h._enableMassClear
 429             // });
 430             v.setStyles({
 431                 color: "#333",
 432                 borderColor: "#ff0103"
 433             });
 434             h._map.addOverlay(v);
 435             h._formatSegLabel(v, r);
 436             h._overlays.push(v);
 437             n.disLabel = v;
 438             v.setPosition(n);
 439             var k = new c.lang.Event("onaddpoint");
 440             k.point = n;
 441             k.pixel = h._map.pointToPixel(n);
 442             k.index = h._points.length - 1;
 443             k.distance = h._getTotalDistance().toFixed(0);
 444             h.dispatchEvent(k)
 445         };
 446         var f = function(p) {
 447             if (!h._isOpen) {
 448                 return
 449             }
 450             if (h._paths.length > 0) {
 451                 p = window.event || p;
 452                 var l = p.pageX || p.clientX || 0;
 453                 var k = p.pageY || p.clientY || 0;
 454                 if (typeof h._bind.initX == "undefined") {
 455                     h._bind.x = p.layerX || p.offsetX || 0;
 456                     h._bind.y = p.layerY || p.offsetY || 0;
 457                     h._bind.initX = l;
 458                     h._bind.initY = k
 459                 }
 460                 var r = h._bind.x + l - h._bind.initX;
 461                 var q = h._bind.y + k - h._bind.initY;
 462                 var z = h._paths[h._paths.length - 1];
 463                 var m = h._map.pixelToPoint(new BMap.Pixel(r, q));
 464                 z.setPositionAt(1, m);
 465                 if (!h._mapMoving) {
 466                     z.show()
 467                 }
 468                 var A = 0;
 469                 var u = 0;
 470                 if (r < 10) {
 471                     A = 8
 472                 } else {
 473                     if (r > h._map.getSize().width - 10) {
 474                         A = -8
 475                     }
 476                 }
 477                 if (q < 10) {
 478                     u = 8
 479                 } else {
 480                     if (q > h._map.getSize().height - 10) {
 481                         u = -8
 482                     }
 483                 }
 484                 if (A != 0 || u != 0) {
 485                     if (!f._movingTimerId) {
 486                         h._mapMoving = true;
 487                         h._map.panBy(A, u, {
 488                             noAnimation: true
 489                         });
 490                         h._movingTimerId = f._movingTimerId = setInterval(function() {
 491                             h._map.panBy(A, u, {
 492                                 noAnimation: true
 493                             })
 494                         },
 495                         30);
 496                         z.hide();
 497                         h._followTitle && h._followTitle.hide()
 498                     }
 499                 } else {
 500                     if (f._movingTimerId) {
 501                         clearInterval(f._movingTimerId);
 502                         delete f._movingTimerId;
 503                         delete h._movingTimerId;
 504                         var w = h._paths[h._paths.length - 1];
 505                         var v = h._map.pixelToPoint(new BMap.Pixel(r, q));
 506                         if (!w) {
 507                             return
 508                         }
 509                         w.setPositionAt(1, v);
 510                         w.show();
 511                         if (h._followTitle) {
 512                             h._followTitle.setPosition(v);
 513                             h._followTitle.show()
 514                         }
 515                         h._bind.i = 0;
 516                         h._bind.j = 0;
 517                         delete h._mapMoving
 518                     }
 519                 }
 520                 if (h._followTitle) {
 521                     var o = h._getTotalDistance();
 522                     var n = h._map.getDistance(h._points[h._points.length - 1], m);
 523                     h._updateInstDis(h._followTitle, o + n)
 524                 }
 525             } else {
 526                 if (h._followTitle) {
 527                     h._followTitle.show();
 528                     p = window.event || p;
 529                     var s = p.target || p.srcElement;
 530                     if (s != a.getDom()) {
 531                         h._followTitle.hide()
 532                     }
 533                 }
 534             }
 535         };
 536         var e = function(k) {
 537             if (!h._isOpen) {
 538                 return
 539             }
 540             c.un(a.getDom(h._map), "click", g);
 541             c.un(document, "mousemove", f);
 542             c.un(a.getDom(h._map), "dblclick", e);
 543             c.un(document, "keydown", j);
 544             c.un(a.getDom(h._map), "mouseup", i);
 545             setTimeout(function() {
 546                 //1
 547                 h.close()
 548             },
 549             50)
 550         };
 551         var j = function(k) {
 552             k = window.event || k;
 553             if (k.keyCode == 27) {
 554                 h._clearCurData();
 555                 setTimeout(function() {
 556                     //2
 557                     h.close()
 558                 },
 559                 50)
 560             }
 561         };
 562         var i = function(k) {
 563             k = window.event || k;
 564             var l = 0;
 565             if (/msie (\d+\.\d)/i.test(navigator.userAgent)) {
 566                 l = document.documentMode || +RegExp["\x241"]
 567             }
 568             if (l && k.button != 1 || k.button == 2) {
 569                 //3
 570                 h.close()
 571             }
 572         };
 573         h._initData();
 574         this._formatTitle();
 575         a.show(this._map);
 576         this._setCursor(this._opts.cursor);
 577         c.on(a.getDom(this._map), "click", g);
 578         c.on(document, "mousemove", f);
 579         c.on(a.getDom(this._map), "dblclick", e);
 580         c.on(document, "keydown", j);
 581         c.on(a.getDom(this._map), "mouseup", i);
 582         this.bindFunc = [{
 583             elem: a.getDom(this._map),
 584             type: "click",
 585             func: g
 586         },
 587         {
 588             elem: a.getDom(this._map),
 589             type: "dblclick",
 590             func: e
 591         },
 592         {
 593             elem: document,
 594             type: "mousemove",
 595             func: f
 596         },
 597         {
 598             elem: document,
 599             type: "keydown",
 600             func: j
 601         },
 602         {
 603             elem: a.getDom(this._map),
 604             type: "mouseup",
 605             func: i
 606         }];
 607         return true
 608     };
 609     d.prototype._dispatchLastEvent = function() {
 610         var e = new c.lang.Event("ondrawend");
 611         e.points = this._points ? this._points.slice(0) : [];
 612         e.overlays = this._paths ? this._paths.slice(0, this._paths.length - 1) : [];
 613         e.distance = this._getTotalDistance().toFixed(0);
 614         this.dispatchEvent(e)
 615     };
 616     d.prototype.close = function() {
 617         if (this._isOpen == false) {
 618             return
 619         }
 620         this._isOpen = false;
 621         BMapLib._toolInUse = false;
 622         if (this._mapMoving) {
 623             delete this._mapMoving
 624         }
 625         var g = this;
 626         g._dispatchLastEvent();
 627         if (g._points.length < 2) {
 628             g._clearCurData()
 629         } else {
 630             g._paths[g._paths.length - 1].remove();
 631             g._paths[g._paths.length - 1] = null;
 632             g._paths.length = g._paths.length - 1;
 633             var h = g._points[g._points.length - 1];
 634             if (h.disLabel) {
 635                 h.disLabel.remove()
 636             }
 637             g._processLastOp()
 638         }
 639         a.hide();
 640         for (var f = 0,
 641         e = this.bindFunc.length; f < e; f++) {
 642             c.un(this.bindFunc[f].elem, this.bindFunc[f].type, this.bindFunc[f].func)
 643         }
 644         if (g._movingTimerId) {
 645             clearInterval(g._movingTimerId);
 646             g._movingTimerId = null
 647         }
 648         if (this._followTitle) {
 649             this._followTitle.hide()
 650         }
 651     };
 652     d.prototype._clearCurData = function() {
 653         for (var f = 0,
 654         e = this._points.length; f < e; f++) {
 655             if (this._points[f].disLabel) {
 656                 this._points[f].disLabel.remove()
 657             }
 658         }
 659         for (var f = 0,
 660         e = this._paths.length; f < e; f++) {
 661             this._paths[f].remove()
 662         }
 663         for (var f = 0,
 664         e = this._dots.length; f < e; f++) {
 665             this._dots[f].remove()
 666         }
 667         this._initData()
 668     };
 669     d.prototype._initData = function() {
 670         this._points.length = 0;
 671         this._paths.length = 0;
 672         this._segDistance.length = 0;
 673         this._dots.length = 0
 674     };
 675     d.prototype._setSegDistance = function(g, f) {
 676         if (!g || !f) {
 677             return
 678         }
 679         var e = this._map.getDistance(g, f);
 680         this._segDistance.push(e);
 681         return e
 682     };
 683     d.prototype._getTotalDistance = function() {
 684         var g = 0;
 685         for (var f = 0,
 686         e = this._segDistance.length; f < e; f++) {
 687             g += this._segDistance[f]
 688         }
 689         return g
 690     };
 691     d.prototype._convertUnit = function(e, f) {
 692         f = f || "metric";
 693         if (this._units[f]) {
 694             return e * this._units[f].conv
 695         }
 696         return e
 697     };
 698     d.prototype._addSecPoint = function(g) {
 699         var f = this._opts.secIcon ? this._opts.secIcon: new BMap.Icon("http://api.map.baidu.com/images/mapctrls.png", new BMap.Size(11, 11), {
 700             imageOffset: new BMap.Size( - 26, -313)
 701         });
 702         var e = new BMap.Marker(g, {
 703             icon: f,
 704             clickable: false,
 705             baseZIndex: 3500000,
 706             zIndexFixed: true,
 707             enableMassClear: this._enableMassClear
 708         });
 709         this._map.addOverlay(e);
 710         this._dots.push(e)
 711     };
 712     d.prototype._formatDisStr = function(h) {
 713         var f = this._opts.unit;
 714         var g = this._units[f].u1;
 715         var e = this._convertUnit(h, f);
 716         if (e > this._units[f].incon) {
 717             e = e / this._units[f].incon;
 718             g = this._units[f].u2;
 719             e = e.toFixed(1)
 720         } else {
 721             e = e.toFixed(0)
 722         }
 723         return e + g
 724     };
 725     d.prototype._setCursor = function(f) {
 726         var e = /webkit/.test(navigator.userAgent.toLowerCase()) ? "url(" + this._opts.cursor + ") 3 6, crosshair": "url(" + this._opts.cursor + "), crosshair";
 727         a._setCursor(e)
 728     };
 729     d.prototype._getCursor = function() {
 730         return this._opts.cursor
 731     };
 732     d.prototype._formatSegLabel = function(e, f) {
 733         e.setStyle({
 734             border: "none",
 735             padding: "0"
 736         });
 737         e.setContent("<span style=‘" + this._styles.BMapLib_diso + "‘><span style=‘" + this._styles.BMapLib_disi + "‘>" + f + "</span></span>")
 738     };
 739     d.prototype._processLastOp = function() {
 740         var i = this;
 741         delete i._bind.x;
 742         delete i._bind.y;
 743         delete i._bind.initX;
 744         delete i._bind.initY;
 745         if (i._paths.length > i._points.length - 1) {
 746             var g = i._paths.length - 1;
 747             i._paths[g].remove();
 748             i._paths[g] = null;
 749             i._paths.length = g
 750         }
 751         var e = {};
 752         e.points = i._points.slice(0);
 753         e.paths = i._paths.slice(0);
 754         e.dots = i._dots.slice(0);
 755         e.segDis = i._segDistance.slice(0);
 756         var j = i._map.pointToPixel(e.points[e.points.length - 1]);
 757         var h = i._map.pointToPixel(e.points[e.points.length - 2]);
 758         var k = [0, 0];
 759         var f = [0, 0];
 760         if (j.y - h.y >= 0) {
 761             f = [ - 5, 11]
 762         } else {
 763             f = [ - 5, -35]
 764         }
 765         if (j.x - h.x >= 0) {
 766             k = [14, 0]
 767         } else {
 768             k = [ - 14, 0]
 769         }
 770         var n = e.points[e.points.length - 1];
 771         n.disLabel = new BMap.Label("", {
 772             offset: new BMap.Size( - 15, -40),
 773             enableMassClear: i._enableMassClear
 774         });
 775         n.disLabel.setStyles({
 776             color: "#333",
 777             borderColor: "#ff0103"
 778         });
 779         i._map.addOverlay(n.disLabel);
 780         n.disLabel.setOffset(new BMap.Size(f[0], f[1]));
 781         n.disLabel.setPosition(n);
 782         i._formatTitle(2, "", "", n.disLabel);
 783         var m = this._opts.closeIcon ? this._opts.closeIcon: new BMap.Icon("http://api.map.baidu.com/images/mapctrls.gif", new BMap.Size(12, 12), {
 784             imageOffset: new BMap.Size(0, -14)
 785         });
 786         e.closeBtn = new BMap.Marker(e.points[e.points.length - 1], {
 787             icon: m,
 788             offset: new BMap.Size(k[0], k[1]),
 789             baseZIndex: 3600000,
 790             enableMassClear: i._enableMassClear
 791         });
 792         //将多边形绑定到关闭按钮上
 793         var hh = this;
 794         e.closeBtn._polygon = hh.polygon;
 795         hh.polygon = undefined;
 796         hh._areaPoints = undefined;
 797         i._map.addOverlay(e.closeBtn);
 798         //绑定添加焦点事件
 799         e.closeBtn.setTitle("\u6e05\u9664\u672c\u6b21\u6d4b\u8ddd");
 800         e.closeBtn.addEventListener("click",
 801         function(r) {
 802             //TODO
 803             var polygon = r.target._polygon;
 804             if(polygon.label!=undefined){
 805                 hh._map.removeOverlay(polygon.label);
 806             }
 807             hh._map.removeOverlay(polygon);
 808             r.target._polygon =undefined;
 809  
 810             for (var p = 0,
 811             o = e.points.length; p < o; p++) {
 812                 e.points[p].disLabel.remove();
 813                 e.points[p].disLabel = null
 814             }
 815             for (var p = 0,
 816             o = e.paths.length; p < o; p++) {
 817                 e.paths[p].remove();
 818                 e.paths[p] = null
 819             }
 820             for (var p = 0,
 821             o = e.dots.length; p < o; p++) {
 822                 e.dots[p].remove();
 823                 e.dots[p] = null
 824             }
 825             e.closeBtn.remove();
 826             e.closeBtn = null;
 827             b(r);
 828             var q = new c.lang.Event("onremovepolyline");
 829             i.dispatchEvent(q)
 830             //todo
 831         });
 832         i._initData()
 833     };
 834     d.prototype._formatTitle = function(g, l, e, i) {
 835         var h = i || this._followTitle;
 836         if (!h) {
 837             return
 838         }
 839         h.setStyle({
 840             lineHeight: "16px",
 841             zIndex: "85",
 842             padding: "3px 5px"
 843         });
 844         var n = this._startFollowText || "";
 845         var k = [];
 846         if (g == 1) {
 847             h.setOffset(0, 25);
 848             var m = this._opts.unit;
 849             var j = this._units[m].u1;
 850             var f = this._convertUnit(e, m);
 851             if (f > this._units[m].incon) {
 852                 f = f / this._units[m].incon;
 853                 j = this._units[m].u2;
 854                 f = f.toFixed(1)
 855             } else {
 856                 f = f.toFixed(0)
 857             }
 858             k.push("<span>\u603b\u957f\uff1a<span style=‘" + this._styles.BMapLib_disBoxDis + "‘>" + f + "</span>" + j + "</span><br />");
 859             k.push("<span style=‘color:#7a7a7a‘>" + l + "</span>")
 860         } else {
 861             if (g == 2) {
 862                 var m = this._opts.unit;
 863                 var j = this._units[m].u1;
 864                 var f = this._convertUnit(this._getTotalDistance(), m);
 865                 if (f > this._units[m].incon) {
 866                     f = f / this._units[m].incon;
 867                     j = this._units[m].u2;
 868                     f = f.toFixed(1)
 869                 } else {
 870                     f = f.toFixed(0)
 871                 }
 872                 k.push("\u603b\u957f\uff1a<span style=‘" + this._styles.BMapLib_disBoxDis + "‘>" + f + "</span>" + j)
 873             } else {
 874                 h.setOffset(0, 25);
 875                 k.push(n)
 876             }
 877         }
 878         h.setContent(k.join(""))
 879     };
 880     d.prototype._updateInstDis = function(g, e) {
 881         var f = this._opts.unit;
 882         var i = this._units[f].u1;
 883         if (e > this._units[f].incon) {
 884             e = e / this._units[f].incon;
 885             i = this._units[f].u2;
 886             e = e.toFixed(1)
 887         } else {
 888             e = e.toFixed(0)
 889         }
 890         if (g) {
 891             var h = [];
 892             h.push("<span>\u603b\u957f\uff1a<span style=‘" + this._styles.BMapLib_disBoxDis + "‘>" + e + "</span>" + i + "</span><br />");
 893             h.push("<span style=‘color:#7a7a7a‘>" + this._opts.followText + "</span>");
 894             g.setContent(h.join(""))
 895         }
 896     };
 897     d.prototype._hideCurrent = function() {
 898         if (!this._isOpen) {
 899             return
 900         }
 901         if (this._paths.length > 0) {
 902             var e = this._paths[this._paths.length - 1];
 903             e.hide()
 904         }
 905         this._followTitle && this._followTitle.hide()
 906     };
 907     d.prototype._isPointValid = function(h) {
 908         if (!h) {
 909             return false
 910         }
 911         var f = this._map.getBounds();
 912         var e = f.getSouthWest(),
 913         g = f.getNorthEast();
 914         if (h.lng < e.lng || h.lng > g.lng || h.lat < e.lat || h.lat > g.lat) {
 915             return false
 916         }
 917         return true
 918     };
 919     var a = {
 920         _map: null,
 921         _html: "<div style=‘background:transparent url(http://api.map.baidu.com/images/blank.gif);position:absolute;left:0;top:0;width:100%;height:100%;z-index:1000‘ unselectable=‘on‘></div>",
 922         _maskElement: null,
 923         _cursor: "default",
 924         _inUse: false,
 925         show: function(e) {
 926             if (!this._map) {
 927                 this._map = e
 928             }
 929             this._inUse = true;
 930             if (!this._maskElement) {
 931                 this._createMask(e)
 932             }
 933             this._maskElement.style.display = "block"
 934         },
 935         _createMask: function(g) {
 936             this._map = g;
 937             if (!this._map) {
 938                 return
 939             }
 940             c.insertHTML(this._map.getContainer(), "beforeEnd", this._html);
 941             var f = this._maskElement = this._map.getContainer().lastChild;
 942             var e = function(h) {
 943                 b(h);
 944                 return c.preventDefault(h)
 945             };
 946             c.on(f, "mouseup",
 947             function(h) {
 948                 if (h.button == 2) {
 949                     e(h)
 950                 }
 951             });
 952             c.on(f, "contextmenu", e);
 953             f.style.display = "none"
 954         },
 955         getDrawPoint: function(h, j) {
 956             h = window.event || h;
 957             var f = h.layerX || h.offsetX || 0;
 958             var i = h.layerY || h.offsetY || 0;
 959             var g = h.target || h.srcElement;
 960             if (g != a.getDom(this._map) && j == true) {
 961                 while (g && g != this._map.getContainer()) {
 962                     if (! (g.clientWidth == 0 && g.clientHeight == 0 && g.offsetParent && g.offsetParent.nodeName.toLowerCase() == "td")) {
 963                         f += g.offsetLeft;
 964                         i += g.offsetTop
 965                     }
 966                     g = g.offsetParent
 967                 }
 968             }
 969             if (g != a.getDom(this._map) && g != this._map.getContainer()) {
 970                 return
 971             }
 972             if (typeof f === "undefined" || typeof i === "undefined") {
 973                 return
 974             }
 975             if (isNaN(f) || isNaN(i)) {
 976                 return
 977             }
 978             return this._map.pixelToPoint(new BMap.Pixel(f, i))
 979         },
 980         hide: function() {
 981             if (!this._map) {
 982                 return
 983             }
 984             this._inUse = false;
 985             if (this._maskElement) {
 986                 this._maskElement.style.display = "none"
 987             }
 988         },
 989         getDom: function(e) {
 990             if (!this._maskElement) {
 991                 this._createMask(e)
 992             }
 993             return this._maskElement
 994         },
 995         _setCursor: function(e) {
 996             this._cursor = e || "default";
 997             if (this._maskElement) {
 998                 this._maskElement.style.cursor = this._cursor
 999             }
1000         }
1001     };
1002     function b(f) {
1003         var f = window.event || f;
1004         f.stopPropagation ? f.stopPropagation() : f.cancelBubble = true
1005     }
1006 })();
1007  
1008 var _polygonStyleOptions = {    
1009         strokeColor:"blue",    //边线颜色。    
1010         fillColor:"#FFCCFF",      //填充颜色。当参数为空时,圆形将没有填充效果。    
1011         strokeWeight: 0.00001,       //边线的宽度,以像素为单位。    
1012         strokeOpacity: 0,    //边线透明度,取值范围0 - 1。    
1013         fillOpacity: 0.3,      //填充的透明度,取值范围0 - 1。    
1014         strokeStyle: ‘solid‘ //边线的样式,solid或dashed。    
1015 }   
1016 var _LabelOptions = {    
1017     color : "black",    
1018     fontSize : "16px",    
1019     fillColor:"red"      //填充颜色。当参数为空时,圆形将没有填充效果。    
1020 }   
1021  
1022 //自定义测量面积工具
1023 var createMeasureAreaTool =function(map){
1024     var myDis = new BMapLib.MeasureAreaTool(map);   //测距插件
1025  
1026     myDis.addEventListener("addpoint", function(e) {
1027         var _map = e.target._map;
1028         if(e.target._areaPoints == undefined){
1029             e.target._areaPoints = new Array();
1030         }
1031         e.target._areaPoints.push(e.point);
1032         if(e.target.polygon == undefined){
1033             var polygon = new BMap.Polygon(e.target._areaPoints,_polygonStyleOptions);
1034             myDis.polygon = polygon;
1035             _map.addOverlay(polygon);
1036         }else{
1037             var polygon = e.target.polygon;
1038             polygon.setPath(e.target._areaPoints);
1039             //计算多边形的面积
1040             var _area = 0;
1041             _area = BMapLib.GeoUtils.getPolygonArea(polygon);
1042             //保留两位小数
1043             _area = _area.toFixed(2);
1044             //获取多边形的中心
1045             var _paths = polygon.getPath();
1046             var point = getCenterPoint(_paths);
1047             //移除polygon之前的label
1048             if(polygon.label!=undefined){
1049                 var l = polygon.label;
1050                 _map.removeOverlay(l);
1051                 polygon.label = undefined;
1052             }
1053             //往多边形添加标注
1054             var label = new BMap.Label("区域面积:"+_area+"m3",_LabelOptions);
1055             polygon.label =label;
1056             label.setPosition(point);
1057             //往地图上添加标注
1058             _map.addOverlay(label);
1059         }
1060     }); 
1061     return myDis;
1062 }

2.3  GeoUtils.js  这个是计算面积的api,这个也是必须的。下载链接:http://api.map.baidu.com/library/GeoUtils/1.2/docs/symbols/BMapLib.GeoUtils.html

 

好了,现在可以测试效果了,浏览器打开measureAreaTool_baidu.html这个页面,点击面积测量就可以看到效果。

代码下载地址:https://download.csdn.net/download/hgq0916/10579481

 

————————————————
版权声明:本文为CSDN博主「奔腾的野马」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/hgq0916/article/details/78991927

百度地图实现测量面积和测量距离功能

标签:int   this   linu   key   filter   agent   index   png   efi   

原文地址:https://www.cnblogs.com/hexuerui/p/12835165.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!