吐槽贴:百度地图 api 封装 的实用功能 [源码下载]

ZMap 类 功能介绍

ZMap 是学习百度地图 api 接口,开发基本功能后整的一个脚本类,本类方法功能大多使用 prototype 原型 实现;

包含的功能有:轨迹回放,圈画区域可编辑,判断几个坐标是否在一个圆圈内,生活服务查询,
从经纬度获取地址信息,地图工具包括测距,获取面积,以积打印地图,地图全屏,实时路况,坐标是否在polygon区域内,
打车方案,经过中间途经点,添加地图控件;

地图界面:

ZMap.js 部分代码说明

/**
 * 百度地图 api 功能整合
 * @author    Gloot
 * @email     glootz@gmail.com
 * @QQ        345268267
 * @blog      http://www.cnblogs.com/editor
 * @dependency :<link href="http://api.map.baidu.com/library/TrafficControl/1.4/src/TrafficControl_min.css" rel="stylesheet" type="text/css" />
 * <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2&services=true"></script>
 * <script type="text/javascript" src="http://api.map.baidu.com/library/DistanceTool/1.2/src/DistanceTool_min.js"></script>
 * <script type="text/javascript" src="http://api.map.baidu.com/library/TrafficControl/1.4/src/TrafficControl_min.js"></script>  
 * <script type="text/javascript" src="/devices/scripts/GeoUtils.js"></script>
 */
ZMap = {
    mapObj : null,
    mapId : '',
    opts: ''
};

mapObj: 是地图初始化对象, ZMap.mapObj = new BMap.Map('mapContainer');

mapId: 指的是 显示地图的标签容器 如: 

<div id="mapId"></div>

opts: 是保存地图初始化时的一些配置,如果坐标,级别等;

ZMap.createMap = function(mapId, opts) {
    
    if (ZMap.mapObj) {
        ZMap.mapObj.clearOverlay();
    }
    
    ZMap.mapObj = new BMap.Map(mapId);
    ZMap.mapId = mapId;
    ZMap.opts = opts;
    //debugger;
    if (opts) {
        var level = opts.level || 15;
        if (opts.lng && opts.lat) {
            var point = new BMap.Point(opts.lng, opts.lat);
            ZMap.mapObj.centerAndZoom(point, level);
        } else if(opts.addr){
            ZMap.mapObj.centerAndZoom(opts.addr, level);
        } else {
            ZMap.mapObj.centerAndZoom('北京', 15);
        }
    }
    
    setTimeout(function() { //删除版权
        $('#'+mapId).find('.anchorBL').remove();
    }, 1000);
};

地图初始化方法; opts 为 json 数据: 

{
    lng: 193.2323
    lat:  25.2323
    city: '泉州'
    level: 15
}

 

以下代码为实现地图支持滚动鼠标轮,放大缩小,以及对添加控件的方法;

ZMap.enables = {
    scrollWheel: function() {
        ZMap.mapObj.enableScrollWheelZoom();
    }
};

ZMap.controls = {
    addNavi : function(opts) {
        ZMap.mapObj.addControl(new BMap.NavigationControl(opts));
    },
    addScale : function(opts) {
        ZMap.mapObj.addControl(new BMap.ScaleControl(opts));
    },
    addOverview : function(opts) {
        ZMap.mapObj.addControl(new BMap.OverviewMapControl(opts));
    },
    addMapType : function(opts) {
        ZMap.mapObj.addControl(new BMap.MapTypeControl(opts));
    },
    addGeolocation : function(opts) { //mobi
        try {
            ZMap.mapObj.addControl(new BMap.GeolocationControl(opts));
        }catch(e) {}
    }
};

opts 为配置 控件的停靠偏离边界位置,详细看百度地图 api;

地图添加 标注 Marker 的方法:

ZMap.iconMarker = function(icon, point) {
    var micon = new BMap.Icon(icon.img, new BMap.Size(icon.width, icon.height));
    var marker = new BMap.Marker(point, {icon: micon});
    ZMap.mapObj.addOverlay(marker);
    return marker;
};

ZMap.labelMarker = function(msg, point) {
    var lbl = new BMap.Label(msg, {});
    var marker = new BMap.Marker(point);
    marker.setLabel(lbl);
    ZMap.mapObj.addOverlay(marker);
    return marker;
};

ZMap.marker = function(point) {
    var marker = new BMap.Marker(point, {});
    ZMap.mapObj.addOverlay(marker);
    return marker;
};

ZMap.markerCallback = function(point, callback) {
    var marker = ZMap.marker(point);
    ZMap.addListener(marker, 'click', callback);
};

地图提示框,及添加事件监听方法:

ZMap.addListener = function(obj,type,callback) {
    obj.addEventListener(type, function(e) {
        callback(e);
    });
};

ZMap.msgAlert = function(opts, msg, pObj, point) {
    var infoWindow = new BMap.InfoWindow(msg, opts);
    pObj.openInfoWindow(infoWindow, point);
};

以下是 ZMap 中其中的一个方法,轨迹回放功能,采用原型实现

/**
 * 轨迹回放
 * @param opts
 * @returns {ZMap.GuiJiPlay}
 */
ZMap.GuiJiPlay = function(opts, flag) {
    if (flag) {
        ZMap.createMap(ZMap.mapId, ZMap.opts);
    }
    opts = opts || {};
    this.points = [];
    this.centerPoint = null;
    this.index = 0;
    this.timer = null;
    this.polyline = null;
    this.runlines = [];
    
    this.potlen = 0;
    this.marker = {
        marker : null,
        label: '',
        icon: {
            width: 50,
            height: 50
        }
    };
    
    if (opts.label && opts.label != '') {
        this.marker.label = opts.label;
    }
    
    if (opts.icon) {
        this.marker.icon = opts.icon;
    }
};

ZMap.GuiJiPlay.prototype.set = function(pointArr) {
    var me = this;
    
    for (itm in pointArr) {
        var one = pointArr[itm];
        var point = null;
        try {
            eval("point=new BMap.Point("+one+");");
        }catch(e) {}
        
        if (point) {
            me.points.push(point);
        }
    }
    
    me.potlen = me.points.length;
    
    me.init();
};

ZMap.GuiJiPlay.prototype.init = function() {
    var me = this;
    me.clear();
    
    me.centerPoint = new BMap.Point((me.points[0].lng + me.points[me.potlen - 1].lng) / 2, (me.points[0].lat + me.points[me.potlen - 1].lat) / 2);
    ZMap.mapObj.panTo(me.centerPoint);  
    
    me.polyline = new BMap.Polyline(me.points, {strokeColor: "blue", strokeWeight: 5, strokeOpacity: 1});
    ZMap.mapObj.addOverlay(me.polyline);  
    
    if (!me.marker.icon) {
        me.marker.marker = ZMap.iconMarker(me.marker.icon, me.points[0]);
    } else if (me.marker.label != '') {
        me.marker.marker = ZMap.labelMarker(me.marker.label, me.points[0]);
    } else {
        me.marker.marker = ZMap.marker(me.points[0]);
    }
    
};

ZMap.GuiJiPlay.prototype.reset = function() {
    var me = this;
    me.index = 0;
    if (me.marker.marker && me.points.length > 0) {
        me.marker.marker.setPosition(me.points[0]);  
    }
    
    if (me.timer) {
        window.clearTimeout(me.timer);  
    }
    me.timer = null;
};

ZMap.GuiJiPlay.prototype.clear = function() {
    var me = this;
    if (me.polyline) {
        ZMap.mapObj.removeOverlay(me.polyline);
    }

    for (itm in me.runlines) {
        var line = me.runlines[itm];
        ZMap.mapObj.removeOverlay(line);
    }
    me.polyline = null;
    me.runlines = [];
    me.reset();
};

ZMap.GuiJiPlay.prototype.play = function() {
    var me = this;
    var point = me.points[me.index];  
    
    if(me.index > 0) {  
        var cline = new BMap.Polyline([me.points[me.index - 1], point], {strokeColor: "red", strokeWeight: 1, strokeOpacity: 1});
        ZMap.mapObj.addOverlay(cline);  
        me.runlines.push(cline);
    }  
    
    me.marker.marker.setPosition(point);  
    me.index++;  
    if(true) {  
        ZMap.mapObj.panTo(point);  
    }  
    if(me.index < me.points.length) {  
        me.timer = window.setTimeout(function() {
            me.play();
        }, 1000);  
    } else {
        ZMap.mapObj.panTo(point);  
    }
};

使用 ZMap.js

1. baidu.jsp 地图展示页面,引入的脚本资源:

<link href="http://api.map.baidu.com/library/TrafficControl/1.4/src/TrafficControl_min.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="/devices/scripts/jquery-1.7.2.js"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=1.2&services=true"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/library/DistanceTool/1.2/src/DistanceTool_min.js"></script>
    <script type="text/javascript" src="http://api.map.baidu.com/library/TrafficControl/1.4/src/TrafficControl_min.js"></script>  
    <script type="text/javascript" src="/devices/scripts/GeoUtils.js"></script>
    <script type="text/javascript" src="/devices/scripts/ZMap.js"></script>

2. 地图显示容器基本 html 块;

<div id="container" style="margin:0px auto; width:700px; height:600px; padding-bottom: -40px; overflow: hidden;">
        <div id="panel" style="height:30px; width:100%; display:none; background: #6485ed;">
            <span>X</span>
        </div>
        <div id="istmap" style="width:100%; height:640px;"></div>
</div>

真正显示地图是的 istmap,panel 用于在地图全屏时显示顶端的关闭(返回原型)句柄;container 包含 istmap,主要是用来隐藏百度地图底部的那小块版权区域;

3. 地图初始化:

function defaultMap() {
    ZMap.createMap('istmap', {
        lng: 116.404,
        lat: 39.915,
        level: 15
    });
}

4. 轨迹回放功能;

var guiji ;
        function guiJiMap() {
            guiji = new ZMap.GuiJiPlay({
                marker: {
                    marker: null,
                    label:'车'
                }
            });
            var pointsStr = '116.401072,39.913859-116.401242,39.913859-116.401431,39.913873-116.401844,39.913886-116.402257,39.9139-116.402608,39.9139-116.402994,39.913914-116.403416,39.913928-116.403784,39.913942-116.404135,39.913949-116.404557,39.913962-116.405015,39.913997-116.405455,39.914004-116.405815,39.914011-116.406228,39.914045-116.406587,39.914045-116.406955,39.914059-116.407719,39.914052-116.40886,39.914108-116.408788,39.914101-116.409192,39.914101-116.409462,39.914108-116.409848,39.914115-116.410297,39.914163-116.410953,39.914239';
            var arrs = pointsStr.split('-');
            guiji.set(arrs);
        }

ZMap 下方法接收坐标数据,如果是多个的,基本是以数据形式: ['116.401072,39.913859', '116.401242,39.913859'] 传递;

轨迹回放有三个操作按钮:播放,暂停,重置;

$('#playbtn').css({
                position:'absolute',
                left: (parseInt(_left)+parseInt(_tblwidth) + 15) + 'px',
                top : (parseInt(_top) + _tdhgt * 3 + 3) + 'px'
            })
                .click(function() {
                    guiji.play();
                });
            
            $('#pausebtn').css({
                position:'absolute',
                left: (parseInt(_left)+parseInt(_tblwidth) + 15 + 60) + 'px',
                top : (parseInt(_top) + parseInt(_tdhgt) * 3 + 3) + 'px'
            })
                .click(function() {
                    if(guiji.timer) {  
                        window.clearTimeout(guiji.timer);  
                    }  
                });
            
            $('#resetbtn').css({
                position:'absolute',
                left: (parseInt(_left)+parseInt(_tblwidth) + 15 + 60 + 60) + 'px',
                top : (parseInt(_top) + parseInt(_tdhgt) * 3 + 3) + 'px'
            })
                .click(function() {
                    guiji.reset();
                });

pointsStr 可以是你从数据库,或其他轨迹坐标存放读取出来的数据,表示车辆在某个时间内的路线行驶轨迹;

guiji.set(新的 轨迹坐标数据),可以重置路线;

5. 打车路线,经过中间途经点;

有的时候你要某个地方,途中可能要选经过某个点;

function crossPointMap() {
            var addrs = ["天安门", "三里屯", "百度大厦"];
            
            var drlen = addrs.length;
            for (var i=0;i<drlen;i++) {
                if (i==0) {
                    continue;
                }
                
                var opts = {};
                if (drlen == 2) {
                    opts.start = true;
                    opts.end = true;
                } else {
                    if ((i-1) == 0) {
                        opts.start = true;
                    }
                    else if (i == (drlen-1)) {
                        opts.end = true;
                    }else {
                        opts.pass = true;
                    }
                }
                
                opts.icon = {};
                opts.icon.start = '起点';
                opts.icon.end = '终点';
                opts.icon.pass = '途经点';
                
                var drive = new ZMap.crossPointTraffic(opts);
                drive.search(addrs[i-1], addrs[i]);
                
                ZMap.enables.scrollWheel();
            }
        }

三里屯是你要经过的点;crossPointTraffic 的 opts 参数,可以设定起点,终点,途经点是以 label 还是 icon 的方法标注;

如果以 icon 的方法,则:

opts.icon.start = {
    img: 'icon图标位置',
    width: 50,
    height: 50
}

原码下载说明

源码项目: baiduMap.rar 下载 [https://files.cnblogs.com/editor/baiduMap.rar]

本项目由 SpringMvc + maven 框架实现;默认 home.do 首页,是按百度api 做出来的基本代码,baidu.do 是使用 ZMap.js 开发出来的界面;

 

posted @ 2014-11-07 10:08  Weiseditor  阅读(6663)  评论(9编辑  收藏  举报