一切就绪!

着手开发前,请先阅读我们的开发者文档

激活 Google Maps JavaScript API

为帮助您起步,我们将引导您在 Google Developers Console 中先完成几项任务:

  1. 创建或选择项目
  2. 激活 Google Maps JavaScript API 及相关服务
  3. 创建相应密钥
继续

标记

简介

标记用来标识地图上的位置。默认情况下,标记使用标准图像。标记可以显示自定义图像,在这种情况下,它们通常被称为“图标”。标记和图标都是 Marker 类型的对象。您可以在标记的构造函数中设置一个自定义图标,也可以通过对该标记调用 setIcon() 来进行设置。请参阅以下有关定制标记图像的详细信息。

从广义上讲,标记是叠层的一种。有关其他叠层类型的信息,请参阅在地图上绘制

标记设计为具有交互能力。例如,默认情况下,标记可以接收“点击”事件,这样您就可以通过添加一个事件侦听器来弹出用于显示自定义信息的信息窗口。您可以允许用户在地图上移动标记,只需将该标记的 draggable 属性设置为 true 即可。如需了解有关可拖动标记的详细信息,请参阅以下内容。

添加标记

google.maps.Marker 的构造函数只需传入一个 MarkerOptions 对象字面量,用于指定标记的初始属性。

以下字段特别重要,并且在构建标记时通常会进行设置:

  • position(必填)指定用于标识标记的初始位置的 LatLng。其中一种检索 LatLng 的方法是使用 Geocoding 服务
  • map(可选)指定用来放置标记的 Map。如果您在构建标记时未指定地图,则标记会被创建,但不会附加到(或显示在)地图上。您以后可以通过调用标记的 setMap() 方法来添加标记。

以下示例将一个简单的标记添加到乌鲁鲁(位于澳大利亚的中心)的地图上:

function initMap() {
  var myLatLng = {lat: -25.363, lng: 131.044};

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: myLatLng
  });

  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
  });
}
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
 <!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
function initMap() {
  var myLatLng = {lat: -25.363, lng: 131.044};

  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: myLatLng
  });

  var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    title: 'Hello World!'
  });
}

在以上示例中,在构建标记时使用了 MarkerOptions 中的 map 属性将该标记放置在地图上。或者,您也可以直接使用标记的 setMap() 方法将该标记添加到地图上,如以下示例中所示:

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
  zoom: 4,
  center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);

var marker = new google.maps.Marker({
    position: myLatlng,
    title:"Hello World!"
});

// To add the marker to the map, call setMap();
marker.setMap(map);

标记的 title 将作为工具提示显示。

如果您不希望在标记的构造函数中传递任何 MarkerOptions,只需在构造函数的最后一个自变量中传递一个空对象 {} 即可。

查看示例 (marker-simple.html)

移除标记

要从地图上移除标记,请调用 setMap() 方法并传递 null 作为自变量。

marker.setMap(null);

请注意,上述方法并不会删除该标记。它只是将该标记从地图上移除。如果您是想删除该标记,则应该从地图上移除它,然后将该标记本身设置为 null

如果您希望管理一组标记,则应该创建一个数组来保存这些标记。使用此数组,您就可以依次对数组中的每个标记调用 setMap() 来移除这些标记。您也可以删除这些标记,只需先将其从地图上移除,然后将数组的 length 设置为 0,这将移除这些标记的所有引用。

查看示例 (marker-remove.html)

以动画方式呈现标记

您可以通过动画的方式呈现标记,以便它们能够在各种不同的情况下展现出动态移动的效果。要指定某个标记的动画呈现方式,请使用该标记的 animation 属性,其类型为 google.maps.Animation。可支持以下 Animation 值:

  • DROP 表示第一次将该标记放置在地图上时,该标记应该从地图顶部下落到其最终位置。一旦标记停止移动,动画即停止,并且 animation 将还原为 null。在创建 Marker 时,通常会指定这种类型的动画。
  • BOUNCE 表示该标记应该在原地弹跳。弹跳标记将持续弹跳,直到其 animation 属性显式设置为 null

您可以通过对 Marker 对象调用 setAnimation() 来对现有标记启动动画。

// The following example creates a marker in Stockholm, Sweden using a DROP
// animation. Clicking on the marker will toggle the animation between a BOUNCE
// animation and no animation.

var marker;

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: {lat: 59.325, lng: 18.070}
  });

  marker = new google.maps.Marker({
    map: map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: {lat: 59.327, lng: 18.067}
  });
  marker.addListener('click', toggleBounce);
}

function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
 <!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
// The following example creates a marker in Stockholm, Sweden using a DROP
// animation. Clicking on the marker will toggle the animation between a BOUNCE
// animation and no animation.

var marker;

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 13,
    center: {lat: 59.325, lng: 18.070}
  });

  marker = new google.maps.Marker({
    map: map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: {lat: 59.327, lng: 18.067}
  });
  marker.addListener('click', toggleBounce);
}

function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}

查看示例 (marker-animations.html)

如果您有很多标记,您可能不想一次性将它们全都放在地图上。您可以使用 setTimeout() 通过如下所示的模式将这些标记的动画间隔开来:

function drop() {
  for (var i =0; i < markerArray.length; i++) {
    setTimeout(function() {
      addMarkerMethod();
    }, i * 200);
  }
}

查看示例 (marker-animations-iteration.html)

定制标记图像

如果您想在标记上显示字母或数字,可以使用标记标签。如果您需要更多的定制灵活性,可以定义一个要显示的图标,以代替默认的标记图像。定义图标的操作涉及到设置若干决定标记视觉行为的属性。

以下部分描述了标记标签、简单的图标、复杂的图标和符号(矢量图标)。

标记标签

标记标签是标记内显示的字母或数字。此部分中标记图片显示的标记标签带有字母“B”。您可以将标记标签指定为一个字符串或一个 MarkerLabel 对象,该对象包括一个字符串和其他标签属性。

当创建标记时,您可以指定 MarkerOptions 对象中的 label 属性。或者,您也可以通过调用 Marker 对象中的 setLabel() 在现有标记上设置标签。

以下示例在用户点击地图时显示带有标签的标记:

// In the following example, markers appear when the user clicks on the map.
// Each marker is labeled with a single alphabetical character.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;

function initialize() {
  var bangalore = { lat: 12.97, lng: 77.59 };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: bangalore
  });

  // This event listener calls addMarker() when the map is clicked.
  google.maps.event.addListener(map, 'click', function(event) {
    addMarker(event.latLng, map);
  });

  // Add a marker at the center of the map.
  addMarker(bangalore, map);
}

// Adds a marker to the map.
function addMarker(location, map) {
  // Add the marker at the clicked location, and add the next-available label
  // from the array of alphabetical characters.
  var marker = new google.maps.Marker({
    position: location,
    label: labels[labelIndex++ % labels.length],
    map: map
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
// In the following example, markers appear when the user clicks on the map.
// Each marker is labeled with a single alphabetical character.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var labelIndex = 0;

function initialize() {
  var bangalore = { lat: 12.97, lng: 77.59 };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: bangalore
  });

  // This event listener calls addMarker() when the map is clicked.
  google.maps.event.addListener(map, 'click', function(event) {
    addMarker(event.latLng, map);
  });

  // Add a marker at the center of the map.
  addMarker(bangalore, map);
}

// Adds a marker to the map.
function addMarker(location, map) {
  // Add the marker at the clicked location, and add the next-available label
  // from the array of alphabetical characters.
  var marker = new google.maps.Marker({
    position: location,
    label: labels[labelIndex++ % labels.length],
    map: map
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

查看示例 (marker-labels.html)

简单的图标

在最基本的情况下,图标可以简单地表示一个要代替默认的 Google 地图图钉图标的图像。要指定这样的图标,请将标记的 icon 属性设置为某个图像的 URL。Google Maps JavaScript API 将自动调整图标大小。

// This example adds a marker to indicate the position of Bondi Beach in Sydney,
// Australia.
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: -33, lng: 151}
  });

  var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
  var beachMarker = new google.maps.Marker({
    position: {lat: -33.890, lng: 151.274},
    map: map,
    icon: image
  });
}
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
 <!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
// This example adds a marker to indicate the position of Bondi Beach in Sydney,
// Australia.
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {lat: -33, lng: 151}
  });

  var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
  var beachMarker = new google.maps.Marker({
    position: {lat: -33.890, lng: 151.274},
    map: map,
    icon: image
  });
}

查看示例 (icon-simple.html)

复杂的图标

您也许想要指定复杂的形状来表示可点击的区域,并指定这些图标相对于其他叠层的显示方式(即它们的“叠放顺序”)。以这种方式指定的图标应该将其 icon 属性设置为一个 Icon 类型的对象。

Icon 对象定义了一个图像。该对象还定义了图标的 size(大小)、图标的 origin(原点,例如当您想要的图像是一个较大图像的一部分时),以及 anchor(锚点),锚点是图标热点的所在之处(基于原点)。

如果您在自定义标记上使用标签,则可以通过 Icon 对象中的 labelOrigin 属性来放置该标签。

// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat: -33.9, lng: 151.2}
  });

  setMarkers(map);
}

// Data for the markers consisting of a name, a LatLng and a zIndex for the
// order in which these markers should display on top of each other.
var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

function setMarkers(map) {
  // Adds markers to the map.

  // Marker sizes are expressed as a Size of X,Y where the origin of the image
  // (0,0) is located in the top left of the image.

  // Origins, anchor positions and coordinates of the marker increase in the X
  // direction to the right and in the Y direction down.
  var image = {
    url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
    // This marker is 20 pixels wide by 32 pixels high.
    size: new google.maps.Size(20, 32),
    // The origin for this image is (0, 0).
    origin: new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at (0, 32).
    anchor: new google.maps.Point(0, 32)
  };
  // Shapes define the clickable region of the icon. The type defines an HTML
  // <area> element 'poly' which traces out a polygon as a series of X,Y points.
  // The final coordinate closes the poly by connecting to the first coordinate.
  var shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: 'poly'
  };
  for (var i = 0; i < beaches.length; i++) {
    var beach = beaches[i];
    var marker = new google.maps.Marker({
      position: {lat: beach[1], lng: beach[2]},
      map: map,
      icon: image,
      shape: shape,
      title: beach[0],
      zIndex: beach[3]
    });
  }
}
<div id="map"></div>
/* Always set the map height explicitly to define the size of the div
 * element that contains the map. */
#map {
  height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
 <!-- Replace the value of the key parameter with your own API key. -->
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
// The following example creates complex markers to indicate beaches near
// Sydney, NSW, Australia. Note that the anchor is set to (0,32) to correspond
// to the base of the flagpole.

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 10,
    center: {lat: -33.9, lng: 151.2}
  });

  setMarkers(map);
}

// Data for the markers consisting of a name, a LatLng and a zIndex for the
// order in which these markers should display on top of each other.
var beaches = [
  ['Bondi Beach', -33.890542, 151.274856, 4],
  ['Coogee Beach', -33.923036, 151.259052, 5],
  ['Cronulla Beach', -34.028249, 151.157507, 3],
  ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
  ['Maroubra Beach', -33.950198, 151.259302, 1]
];

function setMarkers(map) {
  // Adds markers to the map.

  // Marker sizes are expressed as a Size of X,Y where the origin of the image
  // (0,0) is located in the top left of the image.

  // Origins, anchor positions and coordinates of the marker increase in the X
  // direction to the right and in the Y direction down.
  var image = {
    url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
    // This marker is 20 pixels wide by 32 pixels high.
    size: new google.maps.Size(20, 32),
    // The origin for this image is (0, 0).
    origin: new google.maps.Point(0, 0),
    // The anchor for this image is the base of the flagpole at (0, 32).
    anchor: new google.maps.Point(0, 32)
  };
  // Shapes define the clickable region of the icon. The type defines an HTML
  // <area> element 'poly' which traces out a polygon as a series of X,Y points.
  // The final coordinate closes the poly by connecting to the first coordinate.
  var shape = {
    coords: [1, 1, 1, 20, 18, 20, 18, 1],
    type: 'poly'
  };
  for (var i = 0; i < beaches.length; i++) {
    var beach = beaches[i];
    var marker = new google.maps.Marker({
      position: {lat: beach[1], lng: beach[2]},
      map: map,
      icon: image,
      shape: shape,
      title: beach[0],
      zIndex: beach[3]
    });
  }
}

查看示例 (icon-complex.html)

MarkerImage 对象转换为 Icon 类型

在 Google Maps JavaScript API 3.10 版之前,复杂的图标都被定义为 MarkerImage 对象。在 3.10 版中添加了 Icon 对象字面量,并且从 3.11 版开始,它就取代了 MarkerImageIcon 对象字面量支持与 MarkerImage 相同的参数,从而可让您轻松地将 MarkerImage 转换成 Icon,只需删除构造函数,将以前的参数用 {} 括起来,然后添加每个参数的名称即可。例如:

var image = new google.maps.MarkerImage(
    place.icon,
    new google.maps.Size(71, 71),
    new google.maps.Point(0, 0),
    new google.maps.Point(17, 34),
    new google.maps.Size(25, 25));

可改为

var image = {
  url: place.icon,
  size: new google.maps.Size(71, 71),
  origin: new google.maps.Point(0, 0),
  anchor: new google.maps.Point(17, 34),
  scaledSize: new google.maps.Size(25, 25)
};

符号

除了光栅图像外,标记还可支持显示称为符号的矢量路径。要显示矢量路径,请将带有所需路径的 Symbol 对象字面量传递给标记的 icon 属性。您可以使用 google.maps.SymbolPath 中的预定义路径之一,或者使用 SVG 路径表示法定义一个自定义路径。

如需了解详细信息,请参阅有关符号的文档

使标记可拖动

要允许用户将某个标记拖动到地图上的其他位置,请在 MarkerOptions 中将 draggable 设置为 true

var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
  zoom: 4,
  center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);

// Place a draggable marker on the map
var marker = new google.maps.Marker({
    position: myLatlng,
    map: map,
    draggable:true,
    title:"Drag me!"
});

发送以下问题的反馈:

此网页
Google Maps JavaScript API
Google Maps JavaScript API
需要帮助?请访问我们的支持页面