博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【技巧】谷歌地图操作类
阅读量:5334 次
发布时间:2019-06-15

本文共 15866 字,大约阅读时间需要 52 分钟。

原文:

/********************************************************************************

Name:谷歌地图操作类
Author:刘皓
Date:2012.8.13
Desc:该类封装谷歌地图的一些操作
version:1.0
*********************************************************************************/

///*一些全局常量*/

//var INIT_GOOGLE_ZOOM = 5;
//var INIT_GOOGLE_LAT = 39.915;
//var INIT_GOOGLE_LNG = 116.404;

function GMap(mapId/*地图对象ID*/) {

    this._mapId = mapId; //地图对象ID
    this._mapTypeId = 'GoogleMap'; //地图类型ID

    //当前覆盖物

    this._vehicleMarker = new Array();
    this._alarmMarker = new Array();
    this._buildingMarker = new Array();
    this._labelMarker = new Array();
    this._infobox = new Array();
    this._line = new Array();
    this._measureMarker = new Array();
    this._map = new Object(); //当前地图对象
    this._infowindow = null; //当前信息窗格对象
    this._drawTool = new Object(); //绘制工具
}

/***********************************************map(地图对象)***********************************************************/

/*
方法:init()
说明:初始化地图对象。
参数:
conatiner: div容器
*/
GMap.prototype.init = function (container) {
    if (google == undefined || google == null || google.maps == null) {
        alert("地图未能成功加载!");
        return;
    }
    var latlng = new google.maps.LatLng($.appConfig.map.lat, $.appConfig.map.lng);
    var myOptions =
            {
                zoom: $.appConfig.map.zoom,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                scaleControl: true,
                overviewMapControl: true,
                streetViewControl:true
            };
    this._map = new google.maps.Map(document.getElementById(container), myOptions);

    return this._map;

}

/*

方法:initTool()
说明:加载地图工具
*/
GMap.prototype.initTool = function () {
    var self = this;
    this._drawTool = new google.maps.drawing.DrawingManager({
        map: self._map,
        drawingControl: true,
        drawingControlOptions: {
            position: google.maps.ControlPosition.TOP_CENTER,
            drawingModes: [
            //   google.maps.drawing.OverlayType.MARKER,
   google.maps.drawing.OverlayType.CIRCLE,
   google.maps.drawing.OverlayType.POLYLINE,
            //   google.maps.drawing.OverlayType.POLYGON,
            //   google.maps.drawing.OverlayType.RECTANGLE
  ]
        }
    });
}

/*

方法:activeTool()
说明:激活地图工具
参数说明:
toolCode: 地图工具代码
*/
GMap.prototype.activeTool = function (toolCode) {
    switch (toolCode) {
        case 100:
            this._drawTool.setDrawingMode(google.maps.drawing.OverlayType.POLYLINE);
            break;
        case 101:
            this._drawTool.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
            break;
        case 102:
            this._drawTool.setDrawingMode(google.maps.drawing.OverlayType.CIRCLE);
            break;
        case 103:
            this._drawTool.setDrawingMode(google.maps.drawing.OverlayType.MARKER);
            break;
        case 104:
            this._drawTool.setDrawingMode(google.maps.drawing.OverlayType.POLYGON);
            break;
        default:
            this._drawTool.setDrawingMode(null);
            break;
    }
};

/*

方法:inactiveTool()
说明:禁用工具
*/
GMap.prototype.inactiveTool = function () {
    this._drawTool.setDrawingMode(null);
}

/*

方法:drawComplete()
说明:绘画完成方法
参数说明:
callback:回调函数
*/
GMap.prototype.drawComplete = function (callback) {
    var self = this;
    google.maps.event.addListener(self._drawTool, "overlaycomplete", function (m) {
        var typeCode = 0;
        var radius = 0; // only valid for circle
        var strPoints = '';
        var length = 0; //距离
        var overlay = new Object();
        switch (m.type) {
            case google.maps.drawing.OverlayType.POLYLINE: //100
                typeCode = 100;
                var paths = m.overlay.getPath();
                length = google.maps.geometry.spherical.computeLength(paths);
                length = length / 1000; //转换为KM
                for (var i = 0; i < paths.length; i++) {
                    strPoints += paths.getAt(i).lng() + ',' + paths.getAt(i).lat() + ',';
                }
                //self.arrLine.push(m.overlay);
                self._measureMarker.push(m.overlay);
                break;
            case google.maps.drawing.OverlayType.RECTANGLE: //101
                typeCode = 101;
                var bounds = m.overlay.getBounds();
                strPoints += bounds.getSouthWest().lng() + ',' + bounds.getSouthWest().lat() + ',';
                strPoints += bounds.getNorthEast().lng() + ',' + bounds.getNorthEast().lat() + ',';
                // self.arrRect.push(m.overlay);
                break;
            case google.maps.drawing.OverlayType.CIRCLE: //102
                typeCode = 102;
                radius = m.overlay.getRadius();
                var pt = m.overlay.getCenter();
                strPoints += pt.lng() + ',' + pt.lat() + ',';
                overlay = m.overlay;
                break;
            case google.maps.drawing.OverlayType.MARKER: //103
                typeCode = 103;
                var pt = m.overlay.getPosition();
                strPoints += pt.lng() + ',' + pt.lat() + ',';
                // self.arrObj.push(m.overlay);
                break;
            case google.maps.drawing.OverlayType.POLYGON: //104
                typeCode = 104;
                var paths = m.overlay.getPath();
                for (var i = 0; i < paths.length; i++) {
                    strPoints += paths.getAt(i).lng() + ',' + paths.getAt(i).lat() + ',';
                }
                //self.arrPolygon.push(m.overlay);
                break;
            default:
                return;
                break;
        }
        callback(typeCode, radius, strPoints, length.toFixed(3), overlay);
    });
}

/*

方法:drawCircle()
说明:画圆
*/
GMap.prototype.drawCircle = function (lat, lng, radius) {
    var buildCircle;
    var populationOptions = {
        strokeColor: /*"#FF0000"*/"336699",
        strokeOpacity: 0.8,
        strokeWeight: 0,
        fillColor:  /*"#FF0000"*/"336699",
        fillOpacity: 0.10,
        map: this._map,
        center: new google.maps.LatLng(lat, lng),
        radius: radius
    };
    buildCircle = new google.maps.Circle(populationOptions);
    return buildCircle;
}

/*

方法:drawLine()
说明:画线条
*/
GMap.prototype.drawLine = function (latlng1, latlng2) {
    var points = [latlng1, latlng2];
    var myPath = new google.maps.Polyline({
        path: points,
        strokeColor: "#FF0000",
        strokeOpacity: 1.0,
        strokeWeight: 2
    });

    // myPath.setMap(this._map);

    return myPath;

}

/*

方法:removeAllOverLays()
说明:清除地图所有标记。
*/
GMap.prototype.removeAllOverLays = function () {
    this.removeOverlayByTypeId('vehicle');
    this.removeOverlayByTypeId('alarm');
    this.removeOverlayByTypeId('building');
    this.removeOverlayByTypeId('label');
    this.removeOverlayByTypeId('infobox');
    this.removeOverlayByTypeId('line');
}

/*

方法:removeOverlayByTypeId()
说明:根据覆盖物类型ID清除标记。
参数:overlayTypeId
可选的值:
vehicle:车辆图标
alarm:报警
building:建筑
label:标签图标
infowindow:信息窗格
*/
GMap.prototype.removeOverlayByTypeId = function (overlayTypeId) {
    switch (overlayTypeId) {
        case 'vehicle':
            for (var i = 0; i < this._vehicleMarker.length; ++i) {
                this.removeOverlay(this._vehicleMarker[i]);
            }
            this._vehicleMarker.length = 0;
            break;
        case 'alarm':
            for (var i = 0; i < this._alarmMarker.length; ++i) {
                this.removeOverlay(this._alarmMarker[i]);
            }
            this._alarmMarker.length = 0;
            break;
        case 'building':
            for (var i = 0; i < this._buildingMarker.length; ++i) {
                this.removeOverlay(this._buildingMarker[i]);
            }
            this._buildingMarker.length = 0;
            break;
        case 'label':
            for (var i = 0; i < this._labelMarker.length; ++i) {
                this.removeOverlay(this._labelMarker[i]);
            }
            this._labelMarker.length = 0;
        case 'infobox':
            for (var i = 0; i < this._infobox.length; ++i) {
                this.removeOverlay(this._infobox[i]);
            }
            this._infobox.length = 0;
        case 'measure':
            for (var i = 0; i < this._measureMarker.length; ++i) {
                this.removeOverlay(this._measureMarker[i]);
            }
            this._measureMarker.length = 0;
        case 'line':
            for (var i = 0; i < this._line.length; ++i) {
                this.removeOverlay(this._line[i]);
            }
            this._line.length = 0;
            break;
        default:
            break;
    }
}

/*

方法:LatLng()
说明:构造一个经纬度对象
参数:
lat:维度
lng:经度
*/
GMap.prototype.LatLng = function (lat, lng) {
    return new google.maps.LatLng(lat, lng);
}

/*****************************************************map.base(核心方法)***************************************************/

/*
方法:setZoom()
说明:设置级别。
参数:
level 级别
*/
GMap.prototype.setZoom = function (level) {
    this._map.setZoom(level);
}

/*

方法:getZoom()
说明:获取级别。
返回值:number
*/
GMap.prototype.getZoom = function () {
    return this._map.getZoom();
}

/*

方法:zoomIn()
说明:放大
*/
GMap.prototype.zoomIn = function () {
    this.setZoom(this._map.getZoom() + 1);
}

/*

方法:zoomOut()
说明:缩小
*/
GMap.prototype.zoomOut = function () {
    this.setZoom(this._map.getZoom() - 1);
}

/*

方法:setCenter()
说明:设置中心点
*/
GMap.prototype.setCenter = function (latlng) {
    this._map.setCenter(latlng);
}

/*

方法:panTo()
说明:移动到
*/
GMap.prototype.panTo = function (latlng) {
    this._map.panTo(latlng);
}

/*

方法:getBounds()
说明: 获取地图边界
返回值:LatLngBounds
说明:LatLngBounds包含了地图西南和东北的经纬度,其包含的相关重要的方法:
contains(latlng):是否包含某个点
extend(latlng):扩展边界以包含某个点
getNorthEast():获取地图东北角的经纬度
getSouthWest():获取地图西南角的经纬度
*/
GMap.prototype.getBounds = function () {
    return this._map.getBounds();
}

/*

方法:isInBounds()
说明:是否在边界内
参数:经度纬度
*/
GMap.prototype.isInBounds = function (latlng) {
    return this.getBounds().contains(latlng);
}

/*

方法:panToBounds()
说明:调整地图视角
参数:LatLngBounds对象
*/
GMap.prototype.panToBounds = function (latlngBounds) {
    this._map.panToBounds(latlngBounds);
}

/*

方法:LatLngBounds()
说明:构造一个边界对象
参数说明:
sw:西南坐标点
ne:东北坐标点
*/
GMap.prototype.LatLngBounds = function (sw, ne) {
    return new google.maps.LatLngBounds(sw, ne);
}

/*

方法:fitBounds()
说明:调整边界视角
参数说明:
latlngBounds:地图边界对象
*/
GMap.prototype.fitBounds = function (latlngBounds) {
    this._map.fitBounds(latlngBounds);
}

/**************************************************用户自定义覆盖物*************************************************/
/*
Google Maps API 第 3 版提供了用于创建自定义叠加层的 OverlayView 类。OverlayView 是一个基类,提供了您在创建叠加层时必须实现的若干方法。
要创建自定义叠加层,请执行以下操作:
•将自定义对象的 prototype 设置为 google.maps.OverlayView() 的新实例。这可以有效地实现叠加层类的“子类化”。
•为自定义叠加层创建构造函数,并将该构造函数中的所有初始化参数都设置为自定义属性。
•在原型中实现 onAdd() 方法,以将叠加层附加到地图上。当地图准备好附加叠加层后,系统将会调用 OverlayView.onAdd()。
•在原型中实现 draw() 方法,以处理对象的视觉显示。同样,在对象首次显示后,系统将会调用 OverlayView.draw()。
•您还应当实现 onRemove() 方法,以清理在叠加层中添加的所有元素。
*/

function USGSOverlay(htmlObj/*DOM对象*/

                   , latlng/*中心点*/
                   , offset/*可选参数,相对于中心点偏移量*/
                   , typeId/*可选参数,覆盖物类型ID*/
                   , Id/*可选参数,覆盖物ID*/
                   ) {
    this.latlng_ = latlng;
    this.htmlObj_ = htmlObj;
    this.offset_ = offset;
    this.typeId_ = typeId;
    this.Id_ = Id;
}

USGSOverlay.prototype = new google.maps.OverlayView();

USGSOverlay.prototype.draw = function () {

    var overlayProjection = this.getProjection();
    var sw = overlayProjection.fromLatLngToDivPixel(this.latlng_);
    var div = this.htmlObj_;
    if (this.offset_ != undefined && this.offset_ != null) {
        div.style.left = sw.x + this.offset_.x + 'px';
        div.style.top = sw.y + this.offset_.y + 'px';
    }
    else {
        div.style.left = sw.x + 'px';
        div.style.top = sw.y + 'px';
    }
}

USGSOverlay.prototype.onAdd = function () {

    var panes = this.getPanes();
    // panes.overlayLayer.appendChild(this.htmlObj_);
    panes.overlayMouseTarget.appendChild(this.htmlObj_);
}

USGSOverlay.prototype.onRemove = function () {

    this.htmlObj_.parentNode.removeChild(this.htmlObj_);
    this.htmlObj_ = null;
}

USGSOverlay.prototype.hide = function () {

    if (this.htmlObj_) {
        this.htmlObj_.style.visibility = "hidden";
    }
}

USGSOverlay.prototype.show = function () {

    if (this.htmlObj_) {
        this.htmlObj_.style.visibility = "visible";
    }
}

//旋转:兼容各种浏览器

USGSOverlay.prototype.rotate = function (deg) {
    var obj = this.htmlObj_.children[0];

    /*---------------------IE-------------------*/

    var r, sin, cos;
    deg = deg % 360;
    r = deg / (360 / (Math.PI * 2));
    sin = Math.sin(r), cos = Math.cos(r);
    var temp = -sin;
    obj.style.filter = "progid:DXImageTransform.Microsoft.Matrix"
          + "("
          + "enabled=true,"
          + "sizingmethod='auto expand',"
          + "FilterType=bilinear,"
          + "M11=" + cos + ","
          + "M12=" + temp + ","
          + "M21=" + sin + ","
          + "M22=" + cos
          + ")";

    var width = obj.style.width;

    obj.style.left = width / 2 - obj.offsetWidth / 2;
    obj.style.top = width / 2 - obj.offsetHeight / 2;

    obj.style['transform'] = "rotate(" + deg + "deg);";

    /* ---Webkit Kernel browser---- */
    obj.style['-webkit-transform'] = "rotate(" + deg + "deg)";
    /*-----Firefox----- */
    obj.style['-moz-transform'] = "rotate(" + deg + "deg)";
    /*---Opera---*/
    obj.style['-o-transform'] = "rotate(" + deg + "deg)";
}

//绑定事件

USGSOverlay.prototype.bind = function (eventname, callback) {
    google.maps.event.addDomListener(this.htmlObj_, eventname, callback);
    //google.maps.event.addListener(this, eventname, callback);
}

/***********************************************map.overlays(覆盖物)************************************************/

/*
方法:addOverlay()
说明:添加覆盖物。
参数说明:
typeId:覆盖物类型ID
obj:覆盖物对象,可以是标准的覆盖物对象,也可以是自定义覆盖物对象。如何创建自定义覆盖物,请参考“用户自定义覆盖物”。
*/
GMap.prototype.addOverlay = function (typeId, obj) {
    //添加到数组中管理
    switch (typeId) {
        case 'vehicle':
            this._vehicleMarker.push(obj);
            break;
        case 'alarm':
            this._alarmMarker.push(obj);
            break;
        case 'building':
            this._buildingMarker.push(obj);
            break;
        case 'label':
            this._labelMarker.push(obj);
            break;
        case 'infobox':
            this._infobox.push(obj);
            break;
        default:
            break;
    }

    //在地图上显示

    obj.setMap(this._map);
}

/*

方法:removeOverlay()
说明:移除覆盖物
参数说明:
obj:覆盖物对象,可以是标准的覆盖物对象,也可以是自定义覆盖物对象。如何创建自定义覆盖物,请参考“用户自定义覆盖物”。
*/
GMap.prototype.removeOverlay = function (obj) {
    obj.setMap(null);
}

/*

方法:isOverlayExist()
说明:判断覆盖物对象是否已经存在
参数说明:
typeId:覆盖物类型ID
Id:覆盖物ID
*/
GMap.prototype.isOverlayExist = function (typeId, Id) {
    var result = false;

    switch (typeId) {

        case 'vehicle':
            for (var i = 0; i < this._vehicleMarker.length; ++i) {
                if (Id == this._vehicleMarker[i].Id_) {
                    result = true;
                }
            }
            break;
        case 'alarm':
            for (var i = 0; i < this._alarmMarker.length; ++i) {
                if (Id == this._alarmMarker[i].Id_) {
                    result = true;
                }
            }
            break;
        case 'building':
            for (var i = 0; i < this._buildingMarker.length; ++i) {
                if (Id == this._buildingMarker[i].Id_) {
                    result = true;
                }
            }
            break;
        case 'label':
            for (var i = 0; i < this._labelMarker.length; ++i) {
                if (Id == this._labelMarker[i].Id_) {
                    result = true;
                }
            }
            break;
        case 'infobox':
            for (var i = 0; i < this._infobox.length; ++i) {
                if (Id == this._infobox[i].Id_) {
                    result = true;
                }
            }
            break;
        default:
            break;
    }

    return result;

}

/*

方法:getOverlay()
说明:获取覆盖物对象
参数说明:
typeId:覆盖物类型ID
Id:覆盖物ID
*/
GMap.prototype.getOverlay = function (typeId, Id) {
    var obj = null;

    if (this.isOverlayExist(typeId, Id)) {

        switch (typeId) {
            case 'vehicle':
                for (var i = 0; i < this._vehicleMarker.length; ++i) {
                    if (Id == this._vehicleMarker[i].Id_) {
                        obj = this._vehicleMarker[i];
                    }
                }
                break;
            case 'alarm':
                for (var i = 0; i < this._alarmMarker.length; ++i) {
                    if (Id == this._alarmMarker[i].Id_) {
                        obj = this._alarmMarker[i];
                    }
                }
                break;
            case 'building':
                for (var i = 0; i < this._buildingMarker.length; ++i) {
                    if (Id == this._buildingMarker[i].Id_) {
                        obj = this._buildingMarker[i];
                    }
                }
                break;
            case 'label':
                for (var i = 0; i < this._labelMarker.length; ++i) {
                    if (Id == this._labelMarker[i].Id_) {
                        obj = this._labelMarker[i];
                    }
                }
                break;
            case 'infobox':
                for (var i = 0; i < this._infobox.length; ++i) {
                    if (Id == this._infobox[i].Id_) {
                        obj = this._infobox;
                    }
                }
        }
    }

    return obj;

}

/*

方法:updateOverlay()
说明:更新覆盖物
参数:
typeId:类型ID
Id:覆盖物ID
obj:新覆盖物对象
*/
GMap.prototype.updateOverlay = function (typeId, Id, obj) {
    var overlay = this.getOverlay(typeId, Id);
    this.removeOverlay(overlay);

    switch (typeId) {

        case 'vehicle':
            for (var i = 0; i < this._vehicleMarker.length; ++i) {
                if (Id == this._vehicleMarker[i].Id_) {
                    this._vehicleMarker[i] = obj;
                }
            }
            break;
        case 'alarm':
            for (var i = 0; i < this._alarmMarker.length; ++i) {
                if (Id == this._alarmMarker[i].Id_) {
                    this._alarmMarker[i] = obj;
                }
            }
            break;
        case 'building':
            for (var i = 0; i < this._buildingMarker.length; ++i) {
                if (Id == this._buildingMarker[i].Id_) {
                    this._buildingMarker[i] = obj;
                }
            }
            break;
        case 'label':
            for (var i = 0; i < this._labelMarker.length; ++i) {
                if (Id == this._labelMarker[i].Id_) {
                    this._labelMarker[i] = obj;
                }
            }
            break;
        case 'infobox':
            for (var i = 0; i < this._infobox.length; ++i) {
                if (Id == this._infobox[i].Id_) {
                    this._infobox = obj;
                }
            }
    }

    this.addOverlay(typeId, obj);

}

/********************************************信息窗格*******************************************/

/*
方法:createInfowindow()
说明:创建一个infowindow对象,并显示
参数:
htmlContent:html内容
latlng:经度纬度
bShow:是否立即显示
*/
GMap.prototype.createInfowindow = function (htmlContent, latlng, bShow) {
    this._infowindow = new google.maps.InfoWindow({ content: htmlContent });
    this._infowindow.setPosition(latlng);

    if (bShow) {

        this._infowindow.open(this._map);
    }
}

/*

方法:updateInfowindow()
说明:修改infowindow对象
参数:
htmlContent:html内容
latlng:经度纬度
bShow:是否立即显示
*/
GMap.prototype.updateInfowindow = function (htmlContent, latlng, bShow) {
    this._infowindow.setContent(htmlContent);
    this._infowindow.setPosition(latlng);

    if (bShow) {

        this._infowindow.open(this._map);
    }
}

/*

方法:showInfowindow()
说明:显示信息窗格
*/
GMap.prototype.showInfowindow = function () {
    this._infowindow.open(this._map);
}

 

 

 

posted on
2014-06-26 23:27 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/lonelyxmas/p/3811072.html

你可能感兴趣的文章
Xamarin.Forms Layout Challenges – Social Network App(转载)
查看>>
iOS5 切换中文键盘时覆盖输入框的完美解决方案
查看>>
深度优先搜索DFS和广度优先搜索BFS简单解析
查看>>
JDBC连接MySQL
查看>>
从PCD文件写入和读取点云数据
查看>>
学习进度条
查看>>
Android GridView去除自带边框点击效果、去除右侧滚动条、禁止上下滑动
查看>>
Maven--Maven 安装最佳实践
查看>>
实时监听网站滚动条滚动
查看>>
checkbox 选中状态与显示状态的研究
查看>>
P3799 妖梦拼木棒 (组合数学)
查看>>
对象数组去重
查看>>
Python内置数据类型之List篇
查看>>
AOP与IOC的概念
查看>>
XML与TreeView
查看>>
VMware Workstation 虚拟机(客户机)创建和主机共享文件夹
查看>>
汇编课程设计2 不是终结版的完成版
查看>>
单例模式在Java和C#中的实现
查看>>
Qt5窗口设计
查看>>
Viewpoints 1.0 for Visual Studio .NET 2008
查看>>