dany_zj的专栏

追寻着自己梦中的足迹

翻译 Google Maps API Version 2 Documentation(中文)收藏

Google Maps API Version 2 Documentation

Google 地图 JavaScript API 允许你把 Google 地图 插入到你的网页中. 要使用这些 API, 你必须 申请一个 API 注册码, 并且仔细阅读下面的使用说明.

这组 API 是新版的, 修复了些bugs,并且比前一版本文件精简了许多. Bear with us as we fill in the holes, and join the Maps API discussion group to give feedback and discuss the API.

这个地图API的版本号是2 , 发布于 2006年4月3日. 假如你使用的版本是1 或则API(发布日期在 2006年4月3日 前的版本), 你需要更新你的网站.
请查看:

目录

听众

这个文档的目标对象是 熟悉 JavaScript 编程和面向对象编程 的读者 ,而且你还必须熟悉 Google 地图 的面想用户的观点。这里有 JavaScript 指南 供参考。

介绍

Google 地图的"Hello, World"

通过下面的简单的例子,开始学习 API。 在下面的页面中将显示一个 500x300px(象数)的 美国加利福尼亚 帕洛阿尔托市(美国加利福尼亚西部的城市,在圣何塞西北)的地图 :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Google Maps JavaScript API Example</title>
    <script src="http://maps.google.com/maps?file=api&v=2&key=abcdefg"
            type="text/javascript"></script>
    <script type="text/javascript">
    //<![CDATA[

    function load() {
      if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);
      }
    }

    //]]>
    </script>
  </head>
  <body onload="load()" onunload="GUnload()">
    <div id="map" style="width: 500px; height: 300px"></div>
  </body>
</html>

你可以 下载这个例子 尝试去编辑它, 但在之前你必须用你自己的API注册码替换掉例子中的注册码。(假如你注册的一个带有目录,那么它在子目录中也能正常工作)

在上面的例子中URL地址(http://maps.google.com/maps?file=api&v=2) 是一个本地 JavaScript 文件 ,他将加载所有需要的元件去替换页面中的Google 地图。你必须包含一个script 标记来指定这个URL, 并且使用你的注册码登记API。假如你的注册码是"abcdefg", 那么你在 script 标记中描述它,参考下面:

<script src="http://maps.google.com/maps?file=api&v=2&key=abcdefg"
        type="text/javascript">
</script>

GMap2描绘一个地图. 它显示的是一个简单的地图在网页上。你也可以创建多个类实例在一个页面中(one for each map on the page)。当你创建一个新的地图时,你需要给他指定一个页面元素(通常使用div 元素)的名称给地图。除非你指定一个确切的尺寸给地图,否则地图将使用容器的尺寸来决定地图的尺寸。

浏览器兼容性

Google 地图 API 支持 多款浏览器。不同的应用程序需要不同的行为支持客户端浏览器不兼容性, API 提供一个全局方法(GBrowserIsCompatible())来检测兼容性,但它不会自动去检测兼容性。脚本http://maps.google.com/maps?file=api&v=2能被几乎所有的浏览器解析而不发生任何错误,所以在页面中未检测兼容性前包含这段脚本是安全的。

None of the examples in this document check for compatibility (other than the first example, above), nor do they display an error message for older browsers. Clearly real applications should do something more friendly with incompatible browsers, but we have omitted such checks to make the examples more readable.

Non-trivial applications will inevitably encounter inconsistencies between browsers and platforms. There is no simple solution to these problems, but the Google Maps API discussion group and quirksmode.org are both good resources to find workarounds.

XHTML 和 VML

我们推荐你使用 XHTML(standards-compliant) 规则书写你的包含地图的页面。当浏览器读取到 XHTML DOCTYPE 在页面的开头时,它将使用"standards compliance"模式去呈现页面,这将更好的提供布局和行为控制在浏览器中。

假如你要在地图中显示折线 (像Google 地图中指示行走路线时显示的线),你需要包含VML命名空间和一些CSS代码在你的XHTML文档中。把你的XHTML文档像下面的开头:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>My Google Maps Hack</title>
    <style type="text/css">
    v\:* {
      behavior:url(#default#VML);
    }
    </style>
    <script src="http://maps.google.com/maps?file=api&v=2&key=abcdefg"
             type="text/javascript"></script>
  </head>

API 版本升级

在URL地址http://maps.google.com/maps?file=api&v=2v=2 部分中指定的API的版本(版本2)。当我们在未来做一个大的API升级时,我们将修改他的版本号来标记在 Google Code(Google 代码库)Maps API discussion group(地图API讨论组). 。

在发布一个新的版本后,我们会包含老版本和新版本协作一个月。在一个月后,老版本的将本取消/关闭,使用老版本的代码将在不久后不能使用。

地图团队(Google的一个开发组) 透明的升级API包含最新的错误修复和性能提升。这些错误修复主要为性能提升,but we may inadvertently break some API clients。 Please use the Maps API discussion group to report such issues.

地理编码和路径选择

这时没有加载Google 地图 API geocoding(地理编码) or routing(路径选择)服务。 However, there are a number of free geocoders on the web.

范例

下面的没个例子显示了一种相关的 JavaScript 代码, 非完整的HTML 文件。你必须把这些代码插入到HTML框架中,显示内容前,或者你可以在例子后面点击下载完整的范例文件。

基本

下面的例子将创建一个新地图,并且指定地图到 美国加利福尼亚帕洛阿尔托市。

var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

查看范例 (simple.html)

地图移动动画

下面的例子将显示一个地图,等待2秒后 移动到新的坐标。

panTo 方法 使地图居中到一个新的指定坐标。假如指定的坐标是在地图的显示范围内,地图将平稳的移动到新的坐标上;假如不是,地图将跳到指定的坐标(不做动画效果)。

var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
window.setTimeout(function() {
  map.panTo(new GLatLng(37.4569, -122.1569));
}, 2000);

查看范例 (animate.html)

增加控制器

你可以通过使用addControl方法在地图上增加一个新的控制器。在这里例子中,我们添加了内置的GSmallMapControlGMapTypeControl控制器,允许我们缩放地图和切换地图显示模式(地图/卫星/两者)。

var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

查看范例 (controls.html)

事件监听

使用GEvent.addListener方法注册一个事件监听对象。当地图上事件发生时,事件将被传递给监听对象,并执行对应事件的函数。在下面的代码中,我们显示纬度和经度信息在地图被拖拽后。

var map = new GMap2(document.getElementById("map"));
GEvent.addListener(map, "moveend", function() {
  var center = map.getCenter();
  document.getElementById("message").innerHTML = center.toString();
});
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

查看范例 (event.html)

更多关于事件信息,请查看事件概况。完整的列出GMap2的所有事件、参数、生成(generate?), 参考GMap2.Events.

打开信息窗口 Opening an Info Window

使用openInfoWindow方法打开一个信息窗口,传递一个位置和DOM对象,显示在地图上。下面的代码显示一个包含简单文件"Hello, world"的信息窗口在地图的中央。

var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.openInfoWindow(map.getCenter(),
	document.createTextNode("Hello, world"));

查看范例 (infowindow.html)

Map Overlays

下面的例子显示10个随机标记位置和5个随机点控制的折线在地图上。 GMarker 在没有指定的图标时使用默认的Google地图图标。参考创建图标例子创建自定义的图标。

回忆上面讲过的,但在IE中显示折线,你的HTML文件中必须包含VML命名空间和CSS。参考XHTML 和 VML 获取更多信息.

var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13); 

// Add 10 markers in random locations on the map
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
for (var i = 0; i < 10; i++) {
  var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
                          southWest.lng() + lngSpan * Math.random());
  map.addOverlay(new GMarker(point));
}

// Add a polyline with five random points. Sort the points by
// longitude so that the line does not intersect itself.
var points = [];
for (var i = 0; i < 5; i++) {
  points.push(new GLatLng(southWest.lat() + latSpan * Math.random(),
                          southWest.lng() + lngSpan * Math.random()));
}
points.sort(function(p1, p2) {
  return p1.lng() - p2.lng();
});
map.addOverlay(new GPolyline(points));

查看范例 (overlay.html)

点击句柄 Click Handling

要触发一个地图点击动作,注册一个"click"事件在你的GMap2。当事件被触发后事件句柄将接收2个乘数:被点击标记和GLatLng坐标。假如没有标记被点击,第一个乘数为null

注: 只有内建在overlay中的标记才支持"click"事件。其他类型的标记(比如:GPolyline)不能被点击。

下面的例子中,当访问者在地图上没有点击任何一个标记时,我们创建一个新的标记在点击的点上。假如访问者点击一个标记,我们则把这个标记从地图中删除它。

var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

GEvent.addListener(map, "click", function(marker, point) {
  if (marker) {
    map.removeOverlay(marker);
  } else {
    map.addOverlay(new GMarker(point));
  }
});

查看范例 (click.html)

更多关于事件信息,请查看事件概况。 完整的列出GMap2的所有事件、参数、生成(generate?), 参考GMap2.Events.

显示信息窗口在标记上 Display Info Windows Above Markers

在这个例子中,我们显示一个自定义的信息窗口,通过监听所有的标记"click"事件,并且显示在事件标记上。 We take advantage of JavaScript function closures 来定制信息窗口的内容为每个标记.

var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

// Creates a marker at the given point with the given number label
function createMarker(point, number) {
  var marker = new GMarker(point);
  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml("Marker #<b>" + number + "</b>");
  });
  return marker;
}

// Add 10 markers to the map at random locations
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
for (var i = 0; i < 10; i++) {
  var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
                          southWest.lng() + lngSpan * Math.random());
  map.addOverlay(createMarker(point, i + 1));
}

查看范例 (markerinfowindow.html)

更多关于事件信息,请查看事件概况。完整的列出GMap2的所有事件、参数、生成(generate?), 参考GMap2.Events.

可换页的信息窗口 Tabbed Info Windows

版本2API引入 openInfoWindowTabs()GInfoWindowTab类来支持多页窗口和命名页。下面的例子显示一个简单的可换页信息窗口在标记上。

var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

// Our info window content
var infoTabs = [
  new GInfoWindowTab("Tab #1", "This is tab #1 content"),
  new GInfoWindowTab("Tab #2", "This is tab #2 content")
];

// Place a marker in the center of the map and open the info window
// automatically
var marker = new GMarker(map.getCenter());
GEvent.addListener(marker, "click", function() {
  marker.openInfoWindowTabsHtml(infoTabs);
});
map.addOverlay(marker);
marker.openInfoWindowTabsHtml(infoTabs);

查看范例 (tabbedinfowindow.html)

创建图标

这个例子创建一个新类型的图标,使用Google Ride Finder "mini" 标记做例子。我们要指定图标图象,阴影图象,图标大小,阴影大小,锚定图标到地图上坐标和锚定信息窗口到图标上坐标。

var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

// Create our "tiny" marker icon
var icon = new GIcon();
icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
icon.iconSize = new GSize(12, 20);
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);

// Add 10 markers to the map at random locations
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
for (var i = 0; i < 10; i++) {
  var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
                          southWest.lng() + lngSpan * Math.random());
  map.addOverlay(new GMarker(point, icon));
}

查看范例 (icon.html)

使用Icon类 Using Icon Classes

在许多案例中,你的图标可能需要多种不同的前景但形状和阴影相同。最容易的方法是,使用结构拷贝方式拷贝对象的所有属性和方法,然后在新对象中覆盖相关属性。 The easiest way to achieve this behavior is to use the copy constructor for the =GIcon= class, which copies all the properties over to a new icon which you can then customize.

var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var baseIcon = new GIcon();
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);

// Creates a marker whose info window displays the letter corresponding
// to the given index.
function createMarker(point, index) {
  // Create a lettered icon for this point using our icon class
  var letter = String.fromCharCode("A".charCodeAt(0) + index);
  var icon = new GIcon(baseIcon);
  icon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
  var marker = new GMarker(point, icon);

  GEvent.addListener(marker, "click", function() {
    marker.openInfoWindowHtml("Marker <b>" + letter + "</b>");
  });
  return marker;
}

// Add 10 markers to the map at random locations
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var lngSpan = northEast.lng() - southWest.lng();
var latSpan = northEast.lat() - southWest.lat();
for (var i = 0; i < 10; i++) {
  var point = new GLatLng(southWest.lat() + latSpan * Math.random(),
                          southWest.lng() + lngSpan * Math.random());
  map.addOverlay(createMarker(point, i));
}

查看范例 (iconclass.html)

使用XML和异步HTTP的地图 Using XML and Asynchronous HTTP with Maps

在这个例子中,我们使用GDownloadUrl 方法下载一个静态的文件("data.xml"),文件包含一个经/纬度列表。当文件下载完毕,我们使用GXml 分析XML,并且创建文档中所有的坐标标记。

var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

// Download the data in data.xml and load it on the map. The format we
// expect is:
// <markers>
//   <marker lat="37.441" lng="-122.141"/>
//   <marker lat="37.322" lng="-121.213"/>
// </markers>
GDownloadUrl("data.xml", function(data, responseCode) {
  var xml = GXml.parse(data);
  var markers = xml.documentElement.getElementsByTagName("marker");
  for (var i = 0; i < markers.length; i++) {
    var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                            parseFloat(markers[i].getAttribute("lng")));
    map.addOverlay(new GMarker(point));
  }
});

查看范例 (async.html). 范例中使用的XML文档 data.xml.

自定义地图控制器 Custom Map Controls

版本2的地图API引入 允许通过继承GControl类创建自定义地图控制器,像内置的面版和缩放控制器。在这个例子中,我们创建一个简单的缩放控制器 that has textual links rather than the 图形图标 used in the 标准Google地图缩放控制器。

GTextualZoomControl类定义 defines the two required methods of the GControl interface: initialize(), in which we create the DOM elements representing our control; and getDefaultPosition(), in which we return the GControlPosition used if another position is not given when this control is added to a map. See the class reference for GControl for more information about the methods you can override when you create your custom controls.

All map controls should be added to the map container which can be accessed with the getContainer() method on GMap2.

// A TextualZoomControl is a GControl that displays textual "Zoom In"
// and "Zoom Out" buttons (as opposed to the iconic buttons used in
// Google Maps).
function TextualZoomControl() {
}
TextualZoomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var zoomInDiv = document.createElement("div");
  this.setButtonStyle_(zoomInDiv);
  container.appendChild(zoomInDiv);
  zoomInDiv.appendChild(document.createTextNode("Zoom In"));
  GEvent.addDomListener(zoomInDiv, "click", function() {
    map.zoomIn();
  });

  var zoomOutDiv = document.createElement("div");
  this.setButtonStyle_(zoomOutDiv);
  container.appendChild(zoomOutDiv);
  zoomOutDiv.appendChild(document.createTextNode("Zoom Out"));
  GEvent.addDomListener(zoomOutDiv, "click", function() {
    map.zoomOut();
  });

  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

// Sets the proper CSS for the given button element.
TextualZoomControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "underline";
  button.style.color = "#0000cc";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "6em";
  button.style.cursor = "pointer";
}

var map = new GMap2(document.getElementById("map"));
map.addControl(new TextualZoomControl());
map.setCenter(new GLatLng(37.441944, -122.141944), 13);

查看范例 (customcontrol.html)

Custom Overlays

Version 2 of the Maps API introduces the ability to create custom map overlays, like the built-in GMarker and GPolyline overlays, by subclassing the built-in GOverlay class. In this example, we create a Rectangle overlay that outlines a geographic region on the map.

The Rectangle class defines the four required methods of the GOverlay interface: initialize(), in which we create the DOM elements representing our overlay; remove(), in which we remove the overlay elements from the map; copy(), which copies the overlay for use in another map instance; and redraw(), which positions and sizes the overlay on the map based on the current projection and zoom level. See the class reference for GOverlay for more information about the methods you can override when you create your custom overlays.

Every DOM element that makes up an overlay exists on a map pane that defines the z-order at which it will be drawn. For example, polylines are flat against the map, so they are drawn in the lowest G_MAP_MAP_PANE. Markers place their shadow elements in the G_MAP_MARKER_SHADOW_PANE and their foreground elements in the G_MAP_MARKER_PANE. Placing your overlay elements in the correct panes ensures that polylines are drawn below marker shadows and the info window is drawn above other overlays on the map. In this example, our overlay is flat against the map, so we add it to the lowest z-order pane G_MAP_MAP_PANE, just like GPolyline. See the class reference for a complete list of map panes.

// A Rectangle is a simple overlay that outlines a lat/lng bounds on the
// map. It has a border of the given weight and color and can optionally
// have a semi-transparent background color.
function Rectangle(bounds, opt_weight, opt_color) {
  this.bounds_ = bounds;
  this.weight_ = opt_weight || 2;
  this.color_ = opt_color || "#888888";
}
Rectangle.prototype = new GOverlay();

// Creates the DIV representing this rectangle.
Rectangle.prototype.initialize = function(map) {
  // Create the DIV representing our rectangle
  var div = document.createElement("div");
  div.style.border = this.weight_ + "px solid " + this.color_;
  div.style.position = "absolute";

  // Our rectangle is flat against the map, so we add our selves to the
  // MAP_PANE pane, which is at the same z-index as the map itself (i.e.,
  // below the marker shadows)
  map.getPane(G_MAP_MAP_PANE).appendChild(div);

  this.map_ = map;
  this.div_ = div;
}

// Remove the main DIV from the map pane
Rectangle.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.div_);
}

// Copy our data to a new Rectangle
Rectangle.prototype.copy = function() {
  return new Rectangle(this.bounds_, this.weight_, this.color_,
                       this.backgroundColor_, this.opacity_);
}

// Redraw the rectangle based on the current projection and zoom level
Rectangle.prototype.redraw = function(force) {
  // We only need to redraw if the coordinate system has changed
  if (!force) return;

  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our rectangle
  var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
  var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());

  // Now position our DIV based on the DIV coordinates of our bounds
  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";
}

var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(37.4419, -122.1419), 13);

// Display a rectangle in the center of the map at about a quarter of
// the size of the main map
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var lngDelta = (northEast.lng() - southWest.lng()) / 4;
var latDelta = (northEast.lat() - southWest.lat()) / 4;
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));

查看范例 (customoverlay.html)

Troubleshooting

If your code doesn't seem to be working, here are some approaches that might help you solve your problems:

  • Make sure your API key is valid.
  • Look for typos. Remember that JavaScript is a case-sensitive language.
  • Use a JavaScript debugger. In Firefox, you can use the JavaScript console or the Venkman Debugger. In IE, you can use the Microsoft Script Debugger.
  • Search the Maps API discussion group. If you can't find a post that answers your question, post your question to the group along with a link to a web page that demonstrates the problem.
  • See Other Resources for third party developer resources.

Other resources

Here are some additional resources. Note that these sites are not owned or supported by Google.

  • Mapki is a popular wiki with information about the Maps API, including an FAQ page.

API Overview

The API Overview walks through the central concepts of the Maps API. For a complete reference of methods and classes exported by the API, see the Maps API Class Reference.

The GMap2 class

An instance of GMap2 represents a single map on the page. You can create as many instances of this class as you want (one for each map on the page). When you create a new map instance, you specify a named element in the page (usually a div element) to contain the map. Unless you specify a size explicitly, the map uses the size of the container to determine its size.

The GMap2 class has methods to manipulate the map's center and zoom level and to add and remove overlays (such as GMarker and GPolyline instances). It also has a method to open an "info window," which is the popup window you see on Google Maps. See The Info Window for more information.

For more information about GMap2, see the GMap2 class reference.

Events

You can add dynamic elements to your application by using event listeners. An object exports a number of named events, and your application can "listen" to those events using the static methods GEvent.addListener and GEvent.bind. For example, this code snippet shows an alert every time the user clicks on the map:

var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(37.4419, -122.1419), 13);
GEvent.addListener(map, "click", function() {
  alert("You clicked the map.");
});

GEvent.addListener takes a function as the third argument, which promotes the use of function closures for event handlers. If you want to bind an event to a method on a class instance, you can use GEvent.bind. In the following example, an application class instance binds map events to its own methods, modifying class state when events are triggered:

function MyApplication() {
  this.counter = 0;
  this.map = new GMap2(document.getElementById("map"));
  this.map.setCenter(new GLatLng(37.4419, -122.1419), 13);
  GEvent.bind(this.map, "click", this, this.onMapClick);
}

MyApplication.prototype.onMapClick = function() {
  this.counter++;
  alert("You have clicked the map " + this.counter + " " +
        (this.counter == 1 ?"time" : "times"));
}

var application = new MyApplication();

查看范例 (bind.html)

The Info Window

Each map has a single "info window," which displays HTML content in a floating window above the map. The info window looks a little like a comic-book word balloon; it has a content area and a tapered stem, where the tip of the stem is at a specified point on the map. You can see the info window in action by clicking a marker in Google Maps.

You can't show more than one info window at a time for a given map, but you can move the info window and change its contents as needed.

The basic info window method is openInfoWindow, which takes a point and an HTML DOM element as arguments. The HTML DOM element is appended to the info window container, and the info window window tip is anchored to the given point.

The openInfoWindowHtml method is similar, but it takes an HTML string as its second argument rather than a DOM element.

To display an info window above an overlay like a marker, you can pass an optional third argument that specifies the pixel offset between the specified point and the tip of the info window. So, if your marker is 10 pixels tall, you might pass the pixel offset GSize(0, -10).

The GMarker class exports openInfoWindow methods that handle the pixel offset issues for you based on the size and shape of the icon, so you generally don't have to worry about calculating icon offsets in your application.

See the GMap2 and GMarker class references for more information.

Overlays

Overlays are objects on the map that are tied to latitude/longitude coordinates, so they move when you drag or zoom the map and when you switch map projections (such as when you switch from Map to Satellite mode).

The Maps API exports two types of overlays: markers, which are icons on the map, and polylines, which are lines made up of a series of points.

Markers and Icons

The GMarker constructor takes an icon and a point as arguments and exports a small set of events like "click". See the overlay.html example above for a simple example of creating markers.

The most difficult part of creating a marker is specifying the icon, which is complex because of the number of different images that make up a single icon in the Maps API.

Every icon has a foreground image and a shadow image. The shadow should be created at a 45 degree angle (upward and to the right) from the foreground image, and the bottom left corner of the shadow image should align with the bottom-left corner of the icon foreground image. The shadow should be a 24-bit PNG image with alpha transparency so that the edges of the shadow look correct on top of the map.

The GIcon class requires you specify the size of these images when you initialize the icon so the Maps API can create image elements of the appropriate size. This is the minimum amount of code required to specify an icon (in this case, the icon used on Google Maps):

var icon = new GIcon();
icon.image = "http://www.google.com/mapfiles/marker.png";
icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
icon.iconSize = new GSize(20, 34);
icon.shadowSize = new GSize(37, 34);

The GIcon class also has several other properties that you should set to get maximum browser compatibility and functionality from your icons. For example, the imageMap property specifies the shape of the non-transparent parts of the icon image. If you do not set this property in your icon, the entire icon image (including the transparent parts) will be clickable in Firefox/Mozilla. See the GIcon class reference for more information.

Polylines

The GPolyline constructor takes an array of points as an argument, and creates a series of line segments that connect those points in the given sequence. You can also specify the color, weight, and opacity of the line. The color should be in the hexadecimal numeric HTML style, e.g., use #ff0000 instead of red. GPolyline does not understand named colors.

The following code snippet creates a 10-pixel-wide red polyline between two points:

var polyline = new GPolyline([
  new GLatLng(37.4419, -122.1419),
  new GLatLng(37.4519, -122.1519)
], "#ff0000", 10);
map.addOverlay(polyline);

In Internet Explorer, Google Maps uses VML to draw polylines (see XHTML and VML for more information). In all other browsers, we request an image of the line from Google servers and overlay that image on the map, refreshing the image as necessary as the map is zoomed and dragged around.

Controls

To add controls like the zoom bar to your map, use the addControl method. The Maps API comes with a handful of built-in controls you can use in your maps:

  • GLargeMapControl - a large pan/zoom control used on Google Local. Appears in the top left corner of the map.
  • GSmallMapControl - a smaller pan/zoom control used on Google Local. Appears in the top left corner of the map.
  • GSmallZoomControl - a small zoom control (no panning controls) used in the small map blowup windows used to display driving directions steps on Google Local.
  • GScaleControl - a map scale
  • GMapTypeControl - buttons that let the user toggle between map types (such as Map and Satellite)
  • GOverviewMapControl New! - a collapsible overview map in the corner of the screen

For example, to add the panning/zooming control you see on Google Maps to your map, you would include the following line in your map initialization:

map.addControl(new GLargeMapControl());

addControl takes an optional second GControlPosition parameter that lets you specify the position of the control on your map. If this argument is excluded, the Maps API uses the default position specified by the control. This example adds the map type control to the bottom right corner of the map with 10 pixels of padding:

map.addControl(new GMapTypeControl(),
               new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10, 10)));

See the GControlPosition class reference for more information.

XML and RPC

The Google Maps API exports a factory method for creating XmlHttpRequest objects that work in recent versions of IE, Firefox, and Safari. The following example downloads a file called myfile.txt and displays its contents in a JavaScript alert:

var request = GXmlHttp.create();
request.open("GET", "myfile.txt", true);
request.onreadystatechange = function() {
  if (request.readyState == 4) {
    alert(request.responseText);
  }
}
request.send(null);

The API also exports a simpler method for typical HTTP GET requests called GDownloadUrl that eliminates the need for XmlHttpRequest readyState checking. The example above could be rewritten using GDownloadUrl like this:

GDownloadUrl("myfile.txt", function(data, responseCode) {
  alert(data);
});

You can parse an XML document with the static method GXml.parse, which takes a string of XML as its only argument. This method is compatible with most modern browsers, but it throws an exception if the browser does not support XML parsing natively.

See the GXmlHttp and GXml class references for more information.

Reducing Browser Memory Leaks

The Google Maps API encourages the use of function closures, and the API event handling system GEvent attaches events to DOM nodes in such a way that almost inevitably causes some browsers to leak memory, particularly Internet Explorer. Version 2 of the Maps API introduces a new method, GUnload(), that will remove most of the circular references that cause these leaks. You should call GUnload() in the unload event of your page to reduce the potential that your application leaks memory:

<body onunload="GUnload()">

Using this function has virtually eliminated Internet Explorer memory leaks in Google Maps, though you should test for memory leaks on your own site using tools like Drip if you are noticing memory consumption problems.

发表于 @ 2006年09月20日 14:38:00|评论(loading...)

新一篇: C#中的正则表达式 | 旧一篇: Google Maps 开发指南

Csdn Blog version 3.1a
Copyright © dany_zj