日期:2014-05-16 浏览次数:20496 次
<html> <head> <title></title> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=ABQIAAAAn8dF06B-QpniAeXC-bdCVBSCooeQ7x8_7WnK9Fc_vSUhGs5F4BSMl23EayM7v4EESxLBoX22Z0GQ3Q" type="text/javascript"></script> <script type="text/javascript"> // 矩形是在地图上勾勒经纬边界的简单叠加层,其边界已指定 // 粗细和颜色,并(可选)可以使用半透明背景颜色. function Rectangle(bounds, opt_weight, opt_color) { this.bounds_ = bounds; this.weight_ = opt_weight || 2; this.color_ = opt_color || "#FF0000"; } Rectangle.prototype = new GOverlay(); // 创建表示此矩形的 DIV. Rectangle.prototype.initialize = function (map) { // 创建表示我们的矩形的 DIV var div = document.createElement("div"); div.style.border = this.weight_ + "px solid " + this.color_; div.style.position = "absolute"; // 我们的矩形相对于地图是平面,所以将其添加到MAP_PANE 面板, // 与地图本身的绘制顺序相同(即在标记阴影下方) map.getPane(G_MAP_MAP_PANE).appendChild(div); this.map_ = map; this.div_ = div; } // 从地图面板删除 DIV Rectangle.prototype.remove = function () { this.div_.parentNode.removeChild(this.div_); } // 将我们的数据复制到新的矩形 Rectangle.prototype.copy = function () { return new Rectangle(this.bounds_, this.weight_, this.color_, this.backgroundColor_, this.opacity_); } // 基于当前投影和缩放级别重新绘制矩形 Rectangle.prototype.redraw = function (force) { // We only need to redraw if the coordinate system has changed if (!force) return; // 计算边界两个对角的 DIV 坐标,获取矩形的尺寸和位置 var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest()); var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast()); // 现在基于边界的 DIV 坐标放置 DIV this.div_.style.width = Math.abs(c2.x - c1.x) + "px"; this.div_.style.height = Math.abs(c2.y - c1.y) + "px"; this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_) + "px"; this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_) + "px"; } function initialize() { if (GBrowserIsCompatible()) { var map = new GMap2(document.getElementById("map_canvas")); map.setCenter(new GLatLng(39.917, 116.397), 14); map.addControl(new GSmallMapControl()); map.addControl(new GMapTypeControl()); // 在地图中心显示矩形,大小约为主地图的四分之一 var result = document.getElementById("bound"); var bounds = map.getBounds(); result.value = bounds; var southWest = bounds.getSouthWest(); var northEast = bounds.getNorthEast(); var lngDelta = northEast.lng() - southWest.lng(); var latDelta = northEast.lat() - southWest.lat(); var rectBounds = new GLatLngBounds( new GLatLng(southWest.lat() + latDelta, southWest.lng() + lngDelta), new GLatLng(northEast.lat() - latDelta, northEast.lng() - lngDelta)); map.addOverlay(new Rectangle(rectBounds)); } } </script> </head> <body onload="initialize()" onunload="GUnload()"> <div id="map_canvas" style="width:50%; height:500px;float:left;"></div><br /> <input type="text" id="bound" name="bound" value="" /> </body> </html>