1. 程式人生 > >百度地圖實現測量面積和測量距離功能

百度地圖實現測量面積和測量距離功能

最近在公司的專案中,需要用到百度地圖的測距和測面積功能,但是在網上只找到了測量距離的api,即BMapLib.DistanceTool。

但是測面積在網上沒有找到很好的資料,百度提供的DrawingManager雖然也可以實現測面積,但是感覺太lol了,然後繼續找資料,發現有人跟我遇到同樣的問題,他的解決思路是對BMapLib.DistanceTool進行改造,但遺憾的是沒有提供原始碼。

我也想過要改造BMapLib.DistanceTool,但是這個對我來說很有挑戰性,畢竟js我差不多是小白,今天閒來無事,決定一試。下載了BMapLib.DistanceTool的原始碼看,大部分都看不懂,呵呵,不過我要做的工作就是在事件處理中加入自己的邏輯,尋著這個思路,經過幾番折騰,終於搞定了,整體效果自己還比較滿意。

好了,廢話不多說,接下來進入重點,我把百度地圖實現測量面積原始碼公佈下(Java成長交流學習群:184998348),分享給大家,若有大神路過,別見怪,呵呵。

首先來張效果圖:

下面是原始碼:

1.measureAreaTool_baidu.html

<!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{width: 100%;height: 100%;margin:0;font-family:"微軟雅黑";}    
    #allmap {width: 100%; height:500px; overflow: hidden;}    
    #result {width:100%;font-size:12px;}    
    </style>
     <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=你的AK"></script>    
    <script src="js/GeoUtils.js" type="text/javascript"></script>
    <script type="text/javascript" src="js/AreaTool_min.js"></script>
    <title>百度地圖API功能演示</title>
</head>    
<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="result">    
        <input type="button"  value="面積測量" onclick="measureArea(this)" /><br/>
    </div>

<script type="text/javascript">    
    var map = new BMap.Map('map');
    var poi = new BMap.Point(113.948913,22.530844);    
    map.centerAndZoom(poi, 16);    
    map.enableScrollWheelZoom();
    //新增測量面積工具
   	var measureAreaTool = createMeasureAreaTool(map);
    //面積測量
    var measureArea = function(e){
    	measureAreaTool.open();
    }
</script>
</body>    
</html>    

2.依賴的js

2.1  百度地圖的核心js檔案,這個用於顯示百度地圖的,不多說

2.2    AreaTool_min.js  這個就是我改造百度地圖測距js後自己建立的測面積工具,完成對面積的測量

 // 百度地圖API功能
var BMapLib = window.BMapLib = BMapLib || {}; (function() {
    var c = c || {
        guid: "$BAIDU$"
    }; (function() {
        window[c.guid] = {};
        c.extend = function(g, e) {
            for (var f in e) {
                if (e.hasOwnProperty(f)) {
                    g[f] = e[f]
                }
            }
            return g
        };
        c.lang = c.lang || {};
        c.lang.guid = function() {
            return "TANGRAM__" + (window[c.guid]._counter++).toString(36)
        };
        window[c.guid]._counter = window[c.guid]._counter || 1;
        window[c.guid]._instances = window[c.guid]._instances || {};
        c.lang.Class = function(e) {
            this.guid = e || c.lang.guid();
            window[c.guid]._instances[this.guid] = this
        };
        window[c.guid]._instances = window[c.guid]._instances || {};
        c.lang.isString = function(e) {
            return "[object String]" == Object.prototype.toString.call(e)
        };
        c.lang.isFunction = function(e) {
            return "[object Function]" == Object.prototype.toString.call(e)
        };
        c.lang.Class.prototype.toString = function() {
            return "[object " + (this._className || "Object") + "]"
        };
        c.lang.Class.prototype.dispose = function() {
            delete window[c.guid]._instances[this.guid];
            for (var e in this) {
                if (!c.lang.isFunction(this[e])) {
                    delete this[e]
                }
            }
            this.disposed = true
        };
        c.lang.Event = function(e, f) {
            this.type = e;
            this.returnValue = true;
            this.target = f || null;
            this.currentTarget = null
        };
        c.lang.Class.prototype.addEventListener = function(h, g, f) {
            if (!c.lang.isFunction(g)) {
                return
            } ! this.__listeners && (this.__listeners = {});
            var e = this.__listeners,
            i;
            if (typeof f == "string" && f) {
                if (/[^\w\-]/.test(f)) {
                    throw ("nonstandard key:" + f)
                } else {
                    g.hashCode = f;
                    i = f
                }
            }
            h.indexOf("on") != 0 && (h = "on" + h);
            typeof e[h] != "object" && (e[h] = {});
            i = i || c.lang.guid();
            g.hashCode = i;
            e[h][i] = g
        };
        c.lang.Class.prototype.removeEventListener = function(g, f) {
            if (c.lang.isFunction(f)) {
                f = f.hashCode
            } else {
                if (!c.lang.isString(f)) {
                    return
                }
            } ! this.__listeners && (this.__listeners = {});
            g.indexOf("on") != 0 && (g = "on" + g);
            var e = this.__listeners;
            if (!e[g]) {
                return
            }
            e[g][f] && delete e[g][f]
        };
        c.lang.Class.prototype.dispatchEvent = function(h, e) {
            if (c.lang.isString(h)) {
                h = new c.lang.Event(h)
            } ! this.__listeners && (this.__listeners = {});
            e = e || {};
            for (var g in e) {
                h[g] = e[g]
            }
            var g, f = this.__listeners,
            j = h.type;
            h.target = h.target || this;
            h.currentTarget = this;
            j.indexOf("on") != 0 && (j = "on" + j);
            c.lang.isFunction(this[j]) && this[j].apply(this, arguments);
            if (typeof f[j] == "object") {
                for (g in f[j]) {
                    f[j][g].apply(this, arguments)
                }
            }
            return h.returnValue
        };
        c.lang.inherits = function(k, i, h) {
            var g, j, e = k.prototype,
            f = new Function();
            f.prototype = i.prototype;
            j = k.prototype = new f();
            for (g in e) {
                j[g] = e[g]
            }
            k.prototype.constructor = k;
            k.superClass = i.prototype;
            if ("string" == typeof h) {
                j._className = h
            }
        };
        c.dom = c.dom || {};
        c._g = c.dom._g = function(e) {
            if (c.lang.isString(e)) {
                return document.getElementById(e)
            }
            return e
        };
        c.g = c.dom.g = function(e) {
            if ("string" == typeof e || e instanceof String) {
                return document.getElementById(e)
            } else {
                if (e && e.nodeName && (e.nodeType == 1 || e.nodeType == 9)) {
                    return e
                }
            }
            return null
        };
        c.insertHTML = c.dom.insertHTML = function(h, e, g) {
            h = c.dom.g(h);
            var f, i;
            if (h.insertAdjacentHTML) {
                h.insertAdjacentHTML(e, g)
            } else {
                f = h.ownerDocument.createRange();
                e = e.toUpperCase();
                if (e == "AFTERBEGIN" || e == "BEFOREEND") {
                    f.selectNodeContents(h);
                    f.collapse(e == "AFTERBEGIN")
                } else {
                    i = e == "BEFOREBEGIN";
                    f[i ? "setStartBefore": "setEndAfter"](h);
                    f.collapse(i)
                }
                f.insertNode(f.createContextualFragment(g))
            }
            return h
        };
        c.ac = c.dom.addClass = function(k, m) {
            k = c.dom.g(k);
            var f = m.split(/\s+/),
            e = k.className,
            j = " " + e + " ",
            h = 0,
            g = f.length;
            for (; h < g; h++) {
                if (j.indexOf(" " + f[h] + " ") < 0) {
                    e += (e ? " ": "") + f[h]
                }
            }
            k.className = e;
            return k
        };
        c.event = c.event || {};
        c.event._listeners = c.event._listeners || [];
        c.on = c.event.on = function(f, i, k) {
            i = i.replace(/^on/i, "");
            f = c._g(f);
            var j = function(m) {
                k.call(f, m)
            },
            e = c.event._listeners,
            h = c.event._eventFilter,
            l,
            g = i;
            i = i.toLowerCase();
            if (h && h[i]) {
                l = h[i](f, i, j);
                g = l.type;
                j = l.listener
            }
            if (f.addEventListener) {
                f.addEventListener(g, j, false)
            } else {
                if (f.attachEvent) {
                    f.attachEvent("on" + g, j)
                }
            }
            e[e.length] = [f, i, k, j, g];
            return f
        };
        c.un = c.event.un = function(g, j, f) {
            g = c._g(g);
            j = j.replace(/^on/i, "").toLowerCase();
            var m = c.event._listeners,
            h = m.length,
            i = !f,
            l, k, e;
            while (h--) {
                l = m[h];
                if (l[1] === j && l[0] === g && (i || l[2] === f)) {
                    k = l[4];
                    e = l[3];
                    if (g.removeEventListener) {
                        g.removeEventListener(k, e, false)
                    } else {
                        if (g.detachEvent) {
                            g.detachEvent("on" + k, e)
                        }
                    }
                    m.splice(h, 1)
                }
            }
            return g
        };
        c.preventDefault = c.event.preventDefault = function(e) {
            if (e.preventDefault) {
                e.preventDefault()
            } else {
                e.returnValue = false
            }
        }
    })();
    //TODO
    var d = BMapLib.MeasureAreaTool = function(f, e) {
        if (!f) {
            return
        }
        this._map = f;
        e = e || {};
        this._opts = c.extend(c.extend(this._opts || {},
        {
            tips: "\u6d4b\u8ddd",
            followText: "\u5355\u51fb\u786e\u5b9a\u5730\u70b9\uff0c\u53cc\u51fb\u7ed3\u675f",
            unit: "metric",
            lineColor: "#ff6319",
            lineStroke: 2,
            opacity: 0.8,
            lineStyle: "solid",
            cursor: "http://api.map.baidu.com/images/ruler.cur",
            secIcon: null,
            closeIcon: null
        }), e);
        this._followTitle = null;
        this._points = [];
        this._paths = [];
        this._dots = [];
        this._segDistance = [];
        this._overlays = [];
        this._enableMassClear = true,
        this._units = {
            metric: {
                name: "metric",
                conv: 1,
                incon: 1000,
                u1: "\u7c73",
                u2: "\u516c\u91cc"
            },
            us: {
                name: "us",
                conv: 3.2808,
                incon: 5279.856,
                u1: "\u82f1\u5c3a",
                u2: "\u82f1\u91cc"
            }
        };
        this._isOpen = false;
        this._startFollowText = "\u5355\u51fb\u786e\u5b9a\u8d77\u70b9";
        this._movingTimerId = null;
        this._styles = {
            BMapLib_diso: "height:17px;width:5px;position:absolute;background:url(http://api.map.baidu.com/images/dis_box_01.gif) no-repeat left top",
            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",
            BMapLib_disBoxDis: "color:#ff6319;font-weight:bold"
        };
        if (this._opts.lineStroke <= 0) {
            this._opts.lineStroke = 2
        }
        if (this._opts.opacity > 1) {
            this._opts.opacity = 1
        } else {
            if (this._opts.opacity < 0) {
                this._opts.opacity = 0
            }
        }
        if (this._opts.lineStyle != "solid" && this._opts.lineStyle != "dashed") {
            this._opts.lineStyle = "solid"
        }
        if (!this._units[this._opts.unit]) {
            this._opts.unit = "metric"
        }
        this.text = "\u6d4b\u8ddd"
    };
    c.lang.inherits(d, c.lang.Class, "DistanceTool");
    d.prototype._bind = function() {
        this._setCursor(this._opts.cursor);
        var f = this;
        c.on(this._map.getContainer(), "mousemove",
        function(i) {
            if (!f._isOpen) {
                return
            }
            if (!f._followTitle) {
                return
            }
            i = window.event || i;
            var g = i.target || i.srcElement;
            if (g != a.getDom(f._map)) {
                f._followTitle.hide();
                return
            }
            if (!f._mapMoving) {
                f._followTitle.show()
            }
            var h = a.getDrawPoint(i, true);
            f._followTitle.setPosition(h)
        });
        if (this._startFollowText) {
            var e = this._followTitle = new BMap.Label(this._startFollowText, {
                offset: new BMap.Size(14, 16)
            });
            this._followTitle.setStyles({
                color: "#333",
                borderColor: "#ff0103"
            })
        }
    };
    d.prototype.open = function() {
        if (this._isOpen == true) {
            return true
        }
        if ( !! BMapLib._toolInUse) {
            return
        }
        this._isOpen = true;
        BMapLib._toolInUse = true;
        if (this._mapMoving) {
            delete this._mapMoving
        }
        var h = this;
        if (!this._binded) {
            this._binded = true;
            this._bind();
            this._map.addEventListener("moving",
            function() {
                h._hideCurrent()
            })
        }
        if (this._followTitle) {
            this._map.addOverlay(this._followTitle);
            this._followTitle.hide()
        }
        var g = function(q) {
        	//TODO
            var l = h._map;//獲取map物件
            if (!h._isOpen) {//判斷測距工具是否開啟,關閉則返回
                return
            }
            q = window.event || q;
            var n = a.getDrawPoint(q, true);//獲取滑鼠點選的點
            if (!h._isPointValid(n)) {//判斷點是否有效
                return
            }
            h._bind.initX = q.pageX || q.clientX || 0;//綁定當前的座標
            h._bind.initY = q.pageY || q.clientY || 0;
            if (h._points.length > 0) {
                var t = l.pointToPixel(h._points[h._points.length - 1]);//獲取點陣列最後一個元素,轉換為Pixel點
                var m = l.pointToPixel(n);//將當前的點轉換為Pixel點
                var p = Math.sqrt(Math.pow(t.x - m.x, 2) + Math.pow(t.y - m.y, 2));//求兩個點的距離
                if (p < 5) {//距離小於5則返回
                    return
                }
            }
            h._bind.x = q.layerX || q.offsetX || 0;//儲存當前座標
            h._bind.y = q.layerY || q.offsetY || 0;
            h._points.push(n);//將當前座標存入陣列
            h._addSecPoint(n);//TODO
            if (h._paths.length == 0) {
                h._formatTitle(1, h._opts.followText, h._getTotalDistance())
            }
            if (h._paths.length > 0) {
                h._paths[h._paths.length - 1].show();
                h._paths[h._paths.length - 1].setStrokeOpacity(h._opts.opacity)
            }
            var w = new BMap.Polyline([n, n], {
                enableMassClear: h._enableMassClear
            });
            h._map.addOverlay(w);
            h._paths.push(w);
            h._overlays.push(w);
            w.setStrokeWeight(h._opts.lineStroke);
            w.setStrokeColor(h._opts.lineColor);
            w.setStrokeOpacity(h._opts.opacity / 2);
            w.setStrokeStyle(h._opts.lineStyle);
            if (h._mapMoving) {
                w.hide()
            }
            if (h._points.length > 1) {
                var o = h._paths[h._points.length - 2];
                o.setPositionAt(1, n)
            }
            var r = "";
            var v;
            if (h._points.length > 1) {
                var u = h._setSegDistance(h._points[h._points.length - 2], h._points[h._points.length - 1]);
                var s = h._getTotalDistance();
                r = h._formatDisStr(s);
                v = new BMap.Label(r, {
                    offset: new BMap.Size(10, -5),
                    enableMassClear: h._enableMassClear
                });
            } else {
                r = "\u8d77\u70b9";
                v = new BMap.Label(r, {
                    offset: new BMap.Size(-10, -25),
                    enableMassClear: h._enableMassClear
                });
            }
            // var v = new BMap.Label(r, {
            //     offset: new BMap.Size(10, -5),
            //     enableMassClear: h._enableMassClear
            // });
            v.setStyles({
                color: "#333",
                borderColor: "#ff0103"
            });
            h._map.addOverlay(v);
            h._formatSegLabel(v, r);
            h._overlays.push(v);
            n.disLabel = v;
            v.setPosition(n);
            var k = new c.lang.Event("onaddpoint");
            k.point = n;
            k.pixel = h._map.pointToPixel(n);
            k.index = h._points.length - 1;
            k.distance = h._getTotalDistance().toFixed(0);
            h.dispatchEvent(k)
        };
        var f = function(p) {
            if (!h._isOpen) {
                return
            }
            if (h._paths.length > 0) {
                p = window.event || p;
                var l = p.pageX || p.clientX || 0;
                var k = p.pageY || p.clientY || 0;
                if (typeof h._bind.initX == "undefined") {
                    h._bind.x = p.layerX || p.offsetX || 0;
                    h._bind.y = p.layerY || p.offsetY || 0;
                    h._bind.initX = l;
                    h._bind.initY = k
                }
                var r = h._bind.x + l - h._bind.initX;
                var q = h._bind.y + k - h._bind.initY;
                var z = h._paths[h._paths.length - 1];
                var m = h._map.pixelToPoint(new BMap.Pixel(r, q));
                z.setPositionAt(1, m);
                if (!h._mapMoving) {
                    z.show()
                }
                var A = 0;
                var u = 0;
                if (r < 10) {
                    A = 8
                } else {
                    if (r > h._map.getSize().width - 10) {
                        A = -8
                    }
                }
                if (q < 10) {
                    u = 8
                } else {
                    if (q > h._map.getSize().height - 10) {
                        u = -8
                    }
                }
                if (A != 0 || u != 0) {
                    if (!f._movingTimerId) {
                        h._mapMoving = true;
                        h._map.panBy(A, u, {
                            noAnimation: true
                        });
                        h._movingTimerId = f._movingTimerId = setInterval(function() {
                            h._map.panBy(A, u, {
                                noAnimation: true
                            })
                        },
                        30);
                        z.hide();
                        h._followTitle && h._followTitle.hide()
                    }
                } else {
                    if (f._movingTimerId) {
                        clearInterval(f._movingTimerId);
                        delete f._movingTimerId;
                        delete h._movingTimerId;
                        var w = h._paths[h._paths.length - 1];
                        var v = h._map.pixelToPoint(new BMap.Pixel(r, q));
                        if (!w) {
                            return
                        }
                        w.setPositionAt(1, v);
                        w.show();
                        if (h._followTitle) {
                            h._followTitle.setPosition(v);
                            h._followTitle.show()
                        }
                        h._bind.i = 0;
                        h._bind.j = 0;
                        delete h._mapMoving
                    }
                }
                if (h._followTitle) {
                    var o = h._getTotalDistance();
                    var n = h._map.getDistance(h._points[h._points.length - 1], m);
                    h._updateInstDis(h._followTitle, o + n)
                }
            } else {
                if (h._followTitle) {
                    h._followTitle.show();
                    p = window.event || p;
                    var s = p.target || p.srcElement;
                    if (s != a.getDom()) {
                        h._followTitle.hide()
                    }
                }
            }
        };
        var e = function(k) {
            if (!h._isOpen) {
                return
            }
            c.un(a.getDom(h._map), "click", g);
            c.un(document, "mousemove", f);
            c.un(a.getDom(h._map), "dblclick", e);
            c.un(document, "keydown", j);
            c.un(a.getDom(h._map), "mouseup", i);
            setTimeout(function() {
            	//1
                h.close()
            },
            50)
        };
        var j = function(k) {
            k = window.event || k;
            if (k.keyCode == 27) {
                h._clearCurData();
                setTimeout(function() {
                	//2
                    h.close()
                },
                50)
            }
        };
        var i = function(k) {
            k = window.event || k;
            var l = 0;
            if (/msie (\d+\.\d)/i.test(navigator.userAgent)) {
                l = document.documentMode || +RegExp["\x241"]
            }
            if (l && k.button != 1 || k.button == 2) {
            	//3
                h.close()
            }
        };
        h._initData();
        this._formatTitle();
        a.show(this._map);
        this._setCursor(this._opts.cursor);
        c.on(a.getDom(this._map), "click", g);
        c.on(document, "mousemove", f);
        c.on(a.getDom(this._map), "dblclick", e);
        c.on(document, "keydown", j);
        c.on(a.getDom(this._map), "mouseup", i);
        this.bindFunc = [{
            elem: a.getDom(this._map),
            type: "click",
            func: g
        },
        {
            elem: a.getDom(this._map),
            type: "dblclick",
            func: e
        },
        {
            elem: document,
            type: "mousemove",
            func: f
        },
        {
            elem: document,
            type: "keydown",
            func: j
        },
        {
            elem: a.getDom(this._map),
            type: "mouseup",
            func: i
        }];
        return true
    };
    d.prototype._dispatchLastEvent = function() {
        var e = new c.lang.Event("ondrawend");
        e.points = this._points ? this._points.slice(0) : [];
        e.overlays = this._paths ? this._paths.slice(0, this._paths.length - 1) : [];
        e.distance = this._getTotalDistance().toFixed(0);
        this.dispatchEvent(e)
    };
    d.prototype.close = function() {
        if (this._isOpen == false) {
            return
        }
        this._isOpen = false;
        BMapLib._toolInUse = false;
        if (this._mapMoving) {
            delete this._mapMoving
        }
        var g = this;
        g._dispatchLastEvent();
        if (g._points.length < 2) {
            g._clearCurData()
        } else {
            g._paths[g._paths.length - 1].remove();
            g._paths[g._paths.length - 1] = null;
            g._paths.length = g._paths.length - 1;
            var h = g._points[g._points.length - 1];
            if (h.disLabel) {
                h.disLabel.remove()
            }
            g._processLastOp()
        }
        a.hide();
        for (var f = 0,
        e = this.bindFunc.length; f < e; f++) {
            c.un(this.bindFunc[f].elem, this.bindFunc[f].type, this.bindFunc[f].func)
        }
        if (g._movingTimerId) {
            clearInterval(g._movingTimerId);
            g._movingTimerId = null
        }
        if (this._followTitle) {
            this._followTitle.hide()
        }
    };
    d.prototype._clearCurData = function() {
        for (var f = 0,
        e = this._points.length; f < e; f++) {
            if (this._points[f].disLabel) {
                this._points[f].disLabel.remove()
            }
        }
        for (var f = 0,
        e = this._paths.length; f < e; f++) {
            this._paths[f].remove()
        }
        for (var f = 0,
        e = this._dots.length; f < e; f++) {
            this._dots[f].remove()
        }
        this._initData()
    };
    d.prototype._initData = function() {
        this._points.length = 0;
        this._paths.length = 0;
        this._segDistance.length = 0;
        this._dots.length = 0
    };
    d.prototype._setSegDistance = function(g, f) {
        if (!g || !f) {
            return
        }
        var e = this._map.getDistance(g, f);
        this._segDistance.push(e);
        return e
    };
    d.prototype._getTotalDistance = function() {
        var g = 0;
        for (var f = 0,
        e = this._segDistance.length; f < e; f++) {
            g += this._segDistance[f]
        }
        return g
    };
    d.prototype._convertUnit = function(e, f) {
        f = f || "metric";
        if (this._units[f]) {
            return e * this._units[f].conv
        }
        return e
    };
    d.prototype._addSecPoint = function(g) {
        var f = this._opts.secIcon ? this._opts.secIcon: new BMap.Icon("http://api.map.baidu.com/images/mapctrls.png", new BMap.Size(11, 11), {
            imageOffset: new BMap.Size( - 26, -313)
        });
        var e = new BMap.Marker(g, {
            icon: f,
            clickable: false,
            baseZIndex: 3500000,
            zIndexFixed: true,
            enableMassClear: this._enableMassClear
        });
        this._map.addOverlay(e);
        this._dots.push(e)
    };
    d.prototype._formatDisStr = function(h) {
        var f = this._opts.unit;
        var g = this._units[f].u1;
        var e = this._convertUnit(h, f);
        if (e > this._units[f].incon) {
            e = e / this._units[f].incon;
            g = this._units[f].u2;
            e = e.toFixed(1)
        } else {
            e = e.toFixed(0)
        }
        return e + g
    };
    d.prototype._setCursor = function(f) {
        var e = /webkit/.test(navigator.userAgent.toLowerCase()) ? "url(" + this._opts.cursor + ") 3 6, crosshair": "url(" + this._opts.cursor + "), crosshair";
        a._setCursor(e)
    };
    d.prototype._getCursor = function() {
        return this._opts.cursor
    };
    d.prototype._formatSegLabel = function(e, f) {
        e.setStyle({
            border: "none",
            padding: "0"
        });
        e.setContent("<span style='" + this._styles.BMapLib_diso + "'><span style='" + this._styles.BMapLib_disi + "'>" + f + "</span></span>")
    };
    d.prototype._processLastOp = function() {
        var i = this;
        delete i._bind.x;
        delete i._bind.y;
        delete i._bind.initX;
        delete i._bind.initY;
        if (i._paths.length > i._points.length - 1) {
            var g = i._paths.length - 1;
            i._paths[g].remove();
            i._paths[g] = null;
            i._paths.length = g
        }
        var e = {};
        e.points = i._points.slice(0);
        e.paths = i._paths.slice(0);
        e.dots = i._dots.slice(0);
        e.segDis = i._segDistance.slice(0);
        var j = i._map.pointToPixel(e.points[e.points.length - 1]);
        var h = i._map.pointToPixel(e.points[e.points.length - 2]);
        var k = [0, 0];
        var f = [0, 0];
        if (j.y - h.y >= 0) {
            f = [ - 5, 11]
        } else {
            f = [ - 5, -35]
        }
        if (j.x - h.x >= 0) {
            k = [14, 0]
        } else {
            k = [ - 14, 0]
        }
        var n = e.points[e.points.length - 1];
        n.disLabel = new BMap.Label("", {
            offset: new BMap.Size( - 15, -40),
            enableMassClear: i._enableMassClear
        });
        n.disLabel.setStyles({
            color: "#333",
            borderColor: "#ff0103"
        });
        i._map.addOverlay(n.disLabel);
        n.disLabel.setOffset(new BMap.Size(f[0], f[1]));
        n.disLabel.setPosition(n);
        i._formatTitle(2, "", "", n.disLabel);
        var m = this._opts.closeIcon ? this._opts.closeIcon: new BMap.Icon("http://api.map.baidu.com/images/mapctrls.gif", new BMap.Size(12, 12), {
            imageOffset: new BMap.Size(0, -14)
        });
        e.closeBtn = new BMap.Marker(e.points[e.points.length - 1], {
            icon: m,
            offset: new BMap.Size(k[0], k[1]),
            baseZIndex: 3600000,
            enableMassClear: i._enableMassClear
        });
        //將多邊形繫結到關閉按鈕上
        var hh = this;
        e.closeBtn._polygon = hh.polygon;
        hh.polygon = undefined;
        hh._areaPoints = undefined;
        i._map.addOverlay(e.closeBtn);
        //繫結新增焦點事件
        e.closeBtn.setTitle("\u6e05\u9664\u672c\u6b21\u6d4b\u8ddd");
        e.closeBtn.addEventListener("click",
        function(r) {
        	//TODO
        	var polygon = r.target._polygon;
        	if(polygon.label!=undefined){
        		hh._map.removeOverlay(polygon.label);
        	}
        	hh._map.removeOverlay(polygon);
            r.target._polygon =undefined;

            for (var p = 0,
            o = e.points.length; p < o; p++) {
                e.points[p].disLabel.remove();
                e.points[p].disLabel = null
            }
            for (var p = 0,
            o = e.paths.length; p < o; p++) {
                e.paths[p].remove();
                e.paths[p] = null
            }
            for (var p = 0,
            o = e.dots.length; p < o; p++) {
                e.dots[p].remove();
                e.dots[p] = null
            }
            e.closeBtn.remove();
            e.closeBtn = null;
            b(r);
            var q = new c.lang.Event("onremovepolyline");
            i.dispatchEvent(q)
            //todo
        });
        i._initData()
    };
    d.prototype._formatTitle = function(g, l, e, i) {
        var h = i || this._followTitle;
        if (!h) {
            return
        }
        h.setStyle({
            lineHeight: "16px",
            zIndex: "85",
            padding: "3px 5px"
        });
        var n = this._startFollowText || "";
        var k = [];
        if (g == 1) {
            h.setOffset(0, 25);
            var m = this._opts.unit;
            var j = this._units[m].u1;
            var f = this._convertUnit(e, m);
            if (f > this._units[m].incon) {
                f = f / this._units[m].incon;
                j = this._units[m].u2;
                f = f.toFixed(1)
            } else {
                f = f.toFixed(0)
            }
            k.push("<span>\u603b\u957f\uff1a<span style='" + this._styles.BMapLib_disBoxDis + "'>" + f + "</span>" + j + "</span><br />");
            k.push("<span style='color:#7a7a7a'>" + l + "</span>")
        } else {
            if (g == 2) {
                var m = this._opts.unit;
                var j = this._units[m].u1;
                var f = this._convertUnit(this._getTotalDistance(), m);
                if (f > this._units[m].incon) {
                    f = f / this._units[m].incon;
                    j = this._units[m].u2;
                    f = f.toFixed(1)
                } else {
                    f = f.toFixed(0)
                }
                k.push("\u603b\u957f\uff1a<span style='" + this._styles.BMapLib_disBoxDis + "'>" + f + "</span>" + j)
            } else {
                h.setOffset(0, 25);
                k.push(n)
            }
        }
        h.setContent(k.join(""))
    };
    d.prototype._updateInstDis = function(g, e) {
        var f = this._opts.unit;
        var i = this._units[f].u1;
        if (e > this._units[f].incon) {
            e = e / this._units[f].incon;
            i = this._units[f].u2;
            e = e.toFixed(1)
        } else {
            e = e.toFixed(0)
        }
        if (g) {
            var h = [];
            h.push("<span>\u603b\u957f\uff1a<span style='" + this._styles.BMapLib_disBoxDis + "'>" + e + "</span>" + i + "</span><br />");
            h.push("<span style='color:#7a7a7a'>" + this._opts.followText + "</span>");
            g.setContent(h.join(""))
        }
    };
    d.prototype._hideCurrent = function() {
        if (!this._isOpen) {
            return
        }
        if (this._paths.length > 0) {
            var e = this._paths[this._paths.length - 1];
            e.hide()
        }
        this._followTitle && this._followTitle.hide()
    };
    d.prototype._isPointValid = function(h) {
        if (!h) {
            return false
        }
        var f = this._map.getBounds();
        var e = f.getSouthWest(),
        g = f.getNorthEast();
        if (h.lng < e.lng || h.lng > g.lng || h.lat < e.lat || h.lat > g.lat) {
            return false
        }
        return true
    };
    var a = {
        _map: null,
        _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>",
        _maskElement: null,
        _cursor: "default",
        _inUse: false,
        show: function(e) {
            if (!this._map) {
                this._map = e
            }
            this._inUse = true;
            if (!this._maskElement) {
                this._createMask(e)
            }
            this._maskElement.style.display = "block"
        },
        _createMask: function(g) {
            this._map = g;
            if (!this._map) {
                return
            }
            c.insertHTML(this._map.getContainer(), "beforeEnd", this._html);
            var f = this._maskElement = this._map.getContainer().lastChild;
            var e = function(h) {
                b(h);
                return c.preventDefault(h)
            };
            c.on(f, "mouseup",
            function(h) {
                if (h.button == 2) {
                    e(h)
                }
            });
            c.on(f, "contextmenu", e);
            f.style.display = "none"
        },
        getDrawPoint: function(h, j) {
            h = window.event || h;
            var f = h.layerX || h.offsetX || 0;
            var i = h.layerY || h.offsetY || 0;
            var g = h.target || h.srcElement;
            if (g != a.getDom(this._map) && j == true) {
                while (g && g != this._map.getContainer()) {
                    if (! (g.clientWidth == 0 && g.clientHeight == 0 && g.offsetParent && g.offsetParent.nodeName.toLowerCase() == "td")) {
                        f += g.offsetLeft;
                        i += g.offsetTop
                    }
                    g = g.offsetParent
                }
            }
            if (g != a.getDom(this._map) && g != this._map.getContainer()) {
                return
            }
            if (typeof f === "undefined" || typeof i === "undefined") {
                return
            }
            if (isNaN(f) || isNaN(i)) {
                return
            }
            return this._map.pixelToPoint(new BMap.Pixel(f, i))
        },
        hide: function() {
            if (!this._map) {
                return
            }
            this._inUse = false;
            if (this._maskElement) {
                this._maskElement.style.display = "none"
            }
        },
        getDom: function(e) {
            if (!this._maskElement) {
                this._createMask(e)
            }
            return this._maskElement
        },
        _setCursor: function(e) {
            this._cursor = e || "default";
            if (this._maskElement) {
                this._maskElement.style.cursor = this._cursor
            }
        }
    };
    function b(f) {
        var f = window.event || f;
        f.stopPropagation ? f.stopPropagation() : f.cancelBubble = true
    }
})();

var _polygonStyleOptions = {    
        strokeColor:"blue",    //邊線顏色。    
        fillColor:"#FFCCFF",      //填充顏色。當引數為空時,圓形將沒有填充效果。    
        strokeWeight: 0.00001,       //邊線的寬度,以畫素為單位。    
        strokeOpacity: 0,    //邊線透明度,取值範圍0 - 1。    
        fillOpacity: 0.3,      //填充的透明度,取值範圍0 - 1。    
        strokeStyle: 'solid' //邊線的樣式,solid或dashed。    
}   
var _LabelOptions = {    
    color : "black",    
    fontSize : "16px",    
    fillColor:"red"      //填充顏色。當引數為空時,圓形將沒有填充效果。    
}   

//自定義測量面積工具
var createMeasureAreaTool =function(map){
	var myDis = new BMapLib.MeasureAreaTool(map);   //測距外掛

	myDis.addEventListener("addpoint", function(e) {
		var _map = e.target._map;
		if(e.target._areaPoints == undefined){
            e.target._areaPoints = new Array();
		}
        e.target._areaPoints.push(e.point);
		if(e.target.polygon == undefined){
			var polygon = new BMap.Polygon(e.target._areaPoints,_polygonStyleOptions);
			myDis.polygon = polygon;
			_map.addOverlay(polygon);
		}else{
			var polygon = e.target.polygon;
			polygon.setPath(e.target._areaPoints);
			//計算多邊形的面積
			var _area = 0;
			_area = BMapLib.GeoUtils.getPolygonArea(polygon);
			//保留兩位小數
			_area = _area.toFixed(2);
			//獲取多邊形的中心
			var _paths = polygon.getPath();
			var point = getCenterPoint(_paths);
			//移除polygon之前的label
			if(polygon.label!=undefined){
				var l = polygon.label;
				_map.removeOverlay(l);
				polygon.label = undefined;
			}
			//往多邊形新增標註
			var label = new BMap.Label("區域面積:"+_area+"m3",_LabelOptions);
			polygon.label =label;
			label.setPosition(point);
			//往地圖上新增標註
			_map.addOverlay(label);
		}
	}); 
	return myDis;
}


2.3  GeoUtils.js  這個是計算面積的api,這個也是必須的。下載連結:http://api.map.baidu.com/library/GeoUtils/1.2/docs/symbols/BMapLib.GeoUtils.html

好了,現在可以測試效果了,瀏覽器開啟measureAreaTool_baidu.html這個頁面,點選面積測量就可以看到效果。

本人水平有限,程式碼有不足之處還請大家見諒,歡迎大家提建議。本人目前主要方向是Java,如果有興趣,可以一起交流,

Java成長交流學習群:184998348

相關推薦

地圖實現測量面積測量距離功能

最近在公司的專案中,需要用到百度地圖的測距和測面積功能,但是在網上只找到了測量距離的api,即BMapLib.DistanceTool。 但是測面積在網上沒有找到很好的資料,百度提供的DrawingManager雖然也可以實現測面積,但是感覺太lol了,然後繼續找資料,發現

使用地圖實現詳細地址自動補全

默認 tro int() div inner 使用 wid type 實現 <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scal

使用地圖實現詳細地址自動補全(補全bug''事件只能綁定到一個上的問題')

item 頁面 tid col border nconf complete ane result     loadMapAutocomplete("suggestId","searchResultPanel"); loadMapAutocomplete("suggest

網頁中利用地圖實現定位省(直轄市)市(區)

ren location .get point asc sca set map char <!doctype html> <head> <meta http-equiv="Content-Type" content="text/h

Android 整合地圖實現裝置定位

Android 整合百度地圖實現裝置定位步驟1:申請android 端SDK :http://lbsyun.baidu.com/步驟2:下載基礎版SDK步驟3:下載示例程式步驟4:開始整合:ak加入libs加入SDKInitializer.setCoordType(CoordType.BD09LL);圖示類

AngularJS進階(十九)在AngularJS應用中整合地圖實現定位功能

分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!http://blog.csdn.net/jiangjunshow 也歡迎大家轉載本篇文章。分享知識,造福人民,實現我們中華民族偉大復興!        

android端實現手機定位地圖實現

單獨無聊的單機程式並沒有意思,我們何不在程式裡面加上有趣的網路呢, 這次我們主要是講關於Android手機的定位系統,本次使用的是百度定位。   下面表格是提供的兩個我們後面需要的地址 百度定位下載地址 http://lbsyun.baidu.co

地圖API 少量點海量點 自定義新增資訊

開發中遇到需要地圖展示使用者座標點需求,在上一篇文章中解決載入大量點卡頓。需求中提到點選代表使用者發表的動態需要彈出資訊框,找了api中的資訊視窗例項暫時不用考慮圖片,就選擇純文字資訊視窗展示。// 百度地圖API功能 var map = new BMap.Map("all

vue移動端app呼叫地圖實現簡單定位

最近做畢業設計做了一個手機定位的小功能,在此記錄下來,我這個定在在電腦上進行測試是沒有許可權的,只有在手機上測試才能拿到具體的地理位置。第一步先是建立一個map.js檔案,用來引入和暴露百度地圖的元件,具體內容如下:export function MP(ak) { retur

Android定位&地圖&導航——基於地圖移動獲取位置自動定位

public class MainActivity extends Activity { public MyApplication app; static MapView mMapView = null; public MKMapViewListener mMapListen

Android定位&地圖&導航——基於地圖實現的定位功能

public class MyApplication extends Application{ public LocationClient mLocationClient = null; public GeofenceClient mGeofenceClient; publi

IOS地圖自定義大頭針氣泡

文/煜寒了(簡書作者) 原文連結:http://www.jianshu.com/p/6a334f071c69 著作權歸作者所有,轉載請聯絡作者獲得授權,並標註“簡書作者”。1.首先實現新增多個標註和自定義氣泡 新增自定義標註 [_mapView addAnnotations:array]; arry 中放入標

微信公眾號開發《三》微信JS-SDK之地理位置的獲取,整合地圖實現線上地圖搜尋

本次講解微信開發第三篇:獲取使用者地址位置資訊,是非常常用的功能,特別是服務行業公眾號,尤為需要該功能,本次講解的就是如何呼叫微信JS-SDK介面,獲取使用者位置資訊,並結合百度地鐵,實現線上地圖搜尋,與線上導航。 在這貼上上二篇博文連結,方便大家訪問: 1.何為J

地圖實現行政區域高亮顯示

最近專案中遇到一個地圖顯示的問題 從資料庫查詢到一個數據集,其中每條資料都包含自己的地理位置資訊(經度、緯度、省、市),需要在地圖上顯示這些資料的分佈,並高亮顯示 省市欄位的值並不規範,可能由於填寫並不正確而找不到經緯度 於是我打算通過表中的經緯度逆向解析省市名稱,再描繪省市的邊框,填充顏色從而達到高亮顯示的

android地圖實現範圍內標註

在開發的過程中發現一個問題,當你完成一個新的功能時,過一段時間就會淡忘,所以想通過寫部落格的方式來總結記錄下,以後有類似的功能還能參考下,簡單明瞭。 前一陣因為寫公司一個專案,有一個功能是在範圍內進行標註,簡單來說就是在當前位置附近XX米範圍之內點選地圖進行標

地圖實現區域省市周邊覆蓋模糊化(簡單實現)

使用百度js api2.0實現,簡單實現覆蓋模糊化周邊.實現原理是用兩塊三角形區域覆蓋,取地圖0,0;0,180;180,180;180,0四個角形成周邊覆蓋效果.僅供參考學習,如有不足之處,歡迎大家提供建議. function getBoundary(address, l

地圖SDK V3.2 定位SDK V4.2 完成定位功能

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"     package="com.example.getsmsinfo"  

解決在EasyUI中使用地圖出現不居中座標圖示顯示異常的問題(紅色程式碼部分)

問題:1.載入指定經緯度的座標點怎麼都不居中顯示,總是顯示在左上角,需要在地圖載入完後拖動才看到指定的座標點;2.顯示的座標點圖片沒有正常顯示,後面使用了自定義座標圖片(如圖):   解決後:   參考: 1.百度地圖API類:http://developer.baidu

地圖實現普通地圖、定位、周邊搜尋功能

//--------------一下是普通地圖的實現----------------------------------- 1:開啟百度地圖APi進去,如果沒有註冊過的需要註冊,註冊過的登入進入 2:點選開發——Android地圖SDk——點選獲取金鑰——點選建立應用——

android 地圖API 使用MarkerInfoWindow

/** * 根據手錶的經緯度在地圖上設定位置,更新頂部的位置文字描述 */ private void updateLocation(ArrayList<GPSBean> list) { /** * 1. 新使用者預設顯示地址