Google Maps JS API v3 - 简单的多标记示例

722

我还比较陌生谷歌地图API。我有一个数据数组,想要循环遍历并在地图上标记。看起来很简单,但我找到的所有多标记教程都很复杂。

让我们以谷歌网站上的数据数组为例:

var locations = [
  ['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]
];

我只是想绘制所有这些点,并在点击时弹出一个 infoWindow 来显示名称。

15个回答

1219

这是我能够简化的最简单版本:

<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
    var locations = [
      ['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]
    ];
    
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    
    var infowindow = new google.maps.InfoWindow();

    var marker, i;
    
    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });
      
      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>

在 Codepen 上编辑/派生 →

截图

Google 地图多个标记

当将回调参数传递给 addListener 方法时,涉及到一些闭包魔法。如果您对闭包的工作原理不熟悉,这可能会是一个相当棘手的话题。如果是这种情况,建议查看以下 Mozilla 文章进行简要介绍:

Mozilla 开发者中心:使用闭包


4
是的,这些括号是必需的,以便实际调用无名称函数。由于闭包的原因,需要传递参数才能使JavaScript工作。请参见我回答这个问题的示例和更多信息:https://dev59.com/23E85IYBdhLWcg3wqVX5#2670420 - Daniel Vassallo
不错的答案,但可以进一步简化。由于所有标记都将具有单独的InfoWindows,并且JavaScript不在乎您向对象添加额外属性,因此您只需要将“InfoWindow”添加到标记的属性中,然后从自身调用“.open()”即可。我本来会在这里发布更改,但修改足够大,以至于[我发布了自己的答案](https://dev59.com/qHA75IYBdhLWcg3w3NLf#38113268)。 - Matthew Cordaro
嗨,@Daniel Vassallo,我也有在我的Ionic Angular项目中显示多个标记的需求。请帮助我,我已经在stackoverflow上提出了一个问题。这是问题链接:https://stackoverflow.com/questions/57985967/adding-multiple-markers-in-ionic-google-map - Shaik
1
它有效。谢谢。您将如何从Google地图中删除标记,因为您正在使用单个标记实例并在循环中初始化。请分享您的想法。 - Kamlesh
如果数据库中有很多带有经纬度的位置,当用户拖动地图时,我们如何与数据库匹配?请注意,数据库中有很多位置,我们不能选择所有数据。 - J Ha
显示剩余2条评论

64

这是多个标记加载的另一个示例,每个标记都有独特的titleinfoWindow文本。使用最新的Google Maps API V3.11进行测试。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <title>Multiple Markers Google Maps</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
    <script
      src="https://maps.googleapis.com/maps/api/js?v=3.11&sensor=false"
      type="text/javascript"
    ></script>
    <script type="text/javascript">
      // check DOM Ready
      $(document).ready(function () {
        // execute
        (function () {
          // map options
          var options = {
            zoom: 5,
            center: new google.maps.LatLng(39.909736, -98.522109), // centered US
            mapTypeId: google.maps.MapTypeId.TERRAIN,
            mapTypeControl: false,
          };

          // init map
          var map = new google.maps.Map(
            document.getElementById('map_canvas'),
            options
          );

          // NY and CA sample Lat / Lng
          var southWest = new google.maps.LatLng(40.744656, -74.005966);
          var northEast = new google.maps.LatLng(34.052234, -118.243685);
          var lngSpan = northEast.lng() - southWest.lng();
          var latSpan = northEast.lat() - southWest.lat();

          // set multiple marker
          for (var i = 0; i < 250; i++) {
            // init markers
            var marker = new google.maps.Marker({
              position: new google.maps.LatLng(
                southWest.lat() + latSpan * Math.random(),
                southWest.lng() + lngSpan * Math.random()
              ),
              map: map,
              title: 'Click Me ' + i,
            });

            // process multiple info windows
            (function (marker, i) {
              // add click event
              google.maps.event.addListener(marker, 'click', function () {
                infowindow = new google.maps.InfoWindow({
                  content: 'Hello, World!!',
                });
                infowindow.open(map, marker);
              });
            })(marker, i);
          }
        })();
      });
    </script>
  </head>
  <body>
    <div id="map_canvas" style="width: 800px; height: 500px"></div>
  </body>
</html>

250个标记的截图:

Google Maps API V3.11 with Multiple Markers

它会自动随机生成Lat/Lng以使其独特。如果您想测试500、1000、xxx个标记和性能,此示例将非常有用。


1
在发布复制和粘贴的样板/原文答案时要小心,这些往往会被社区标记为“垃圾邮件”。如果您这样做,那么通常意味着这些问题是重复的,请标记它们。 - Kev
1
这将为每个标记获取许多弹出式“infoWindow”,如果当前显示,则不会隐藏其他“infoWindow”。这真的很有帮助 :) - Kannika
@Anup,如果你只是阅读问题并发表评论会更好。问题正在问“多个标记的示例”,无论它是随机的还是你自己的等等。 - Madan Sapkota
为什么不使用new MarkerClusterer()来提高性能呢?请查看ChirsSwires的回答。 - DevWL
1
@DevWL,这个问题在2013年已经得到解答。你可以自由更新。 - Madan Sapkota
它有效。谢谢。您将如何从Google地图中删除标记,因为您正在使用单个标记实例并在循环中初始化。请分享您的想法。 - Kamlesh

41

我认为把这个放在这里是因为它似乎是那些开始使用Google Maps API的人们的热门着陆点。从性能角度来看,客户端渲染的多个标记可能是许多映射应用程序的失败之处。它很难进行基准测试、修复,有些情况甚至无法确定是否存在问题(由于浏览器实现的差异、客户端可用的硬件、移动设备等等)。

解决这个问题的最简单方法是使用标记聚类解决方案。基本思想是将地理位置相似的位置分组到一个带有显示点数量的组中。当用户缩放地图时,这些组会展开以显示下面的单个标记。

也许最简单实现的是markerclusterer库。一个基本的实现如下(在导入库之后):

<script type="text/javascript">
  function initialize() {
    var center = new google.maps.LatLng(37.4419, -122.1419);

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 3,
      center: center,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var markers = [];
    for (var i = 0; i < 100; i++) {
      var location = yourData.location[i];
      var latLng = new google.maps.LatLng(location.latitude,
          location.longitude);
      var marker = new google.maps.Marker({
        position: latLng
      });
      markers.push(marker);
    }
    var markerCluster = new MarkerClusterer({map, markers});
  }
  google.maps.event.addDomListener(window, 'load', initialize);
</script>

标记不是直接添加到地图上,而是添加到一个数组中。然后将该数组传递给库,库会为您处理复杂计算,并将其附加到地图上。

这些实现不仅大大提高了客户端性能,而且在许多情况下还导致更简单、更清晰的用户界面以及更容易消化大规模数据。

谷歌提供其他实现

希望这有助于一些对地图细节较新的人。


2
非常感谢,真是帮了大忙! 通过先制作谷歌地图数据点,然后将其传递给映射库(在这种情况下是MarketCluster)进行绘制,性能有数量级的差异。 对于约150,000个数据点,'Daniel Vassallo' 的第一篇文章需要大约2分钟才能加载,而现在只需要5秒钟。非常感谢 'Swires'! - Waqas
1
我认为这是一个很好的地方,我想大多数人在与Google地图相关时首先着陆的是这个页面,其次是“为什么我的地图加载如此缓慢”。 - ChrisSwires
@Monic,它只是您的数据集,它只是一个占位符变量。 - ChrisSwires

22

异步版本:

<script type="text/javascript">
  function initialize() {
    var locations = [
      ['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]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
      'callback=initialize';
  document.body.appendChild(script);
}

window.onload = loadScript;
  </script>

我进行了测试,但对我无效。当我使用Google Marker Accessibility时有效。 - Leffa

15

这是工作示例地图图片

var arr = new Array();
    function initialize() { 
        var i;  
        var Locations = [
                {
                  lat:48.856614, 
                  lon:2.3522219000000177, 
                  address:'Paris',
                  gval:'25.5',
                  aType:'Non-Commodity',
                  title:'Paris',
                  descr:'Paris'           
                },        
                    {
                  lat: 55.7512419, 
                  lon: 37.6184217,
                  address:'Moscow',
                  gval:'11.5',
                  aType:'Non-Commodity',
                  title:'Moscow',
                  descr:'Moscow Airport'              
                },     

                {
              lat:-9.481553000000002, 
              lon:147.190242, 
              address:'Port Moresby',
              gval:'1',
              aType:'Oil',
              title:'Papua New Guinea',
              descr:'Papua New Guinea 123123123'              
            },
            {
           lat:20.5200,
           lon:77.7500,
           address:'Indore',
            gval:'1',
            aType:'Oil',
            title:'Indore, India',
            descr:'Airport India'
        }
    ];

    var myOptions = {
        zoom: 2,
        center: new google.maps.LatLng(51.9000,8.4731),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var map = new google.maps.Map(document.getElementById("map"), myOptions);

    var infowindow =  new google.maps.InfoWindow({
        content: ''
    });

    for (i = 0; i < Locations.length; i++) {
            size=15;        
            var img=new google.maps.MarkerImage('marker.png',           
                new google.maps.Size(size, size),
                new google.maps.Point(0,0),
                new google.maps.Point(size/2, size/2)
           );

        var marker = new google.maps.Marker({
            map: map,
            title: Locations[i].title,
            position: new google.maps.LatLng(Locations[i].lat, Locations[i].lon),           
                icon: img
        });

        bindInfoWindow(marker, map, infowindow, "<p>" + Locations[i].descr + "</p>",Locations[i].title);  

    }

}

function bindInfoWindow(marker, map, infowindow, html, Ltitle) { 
    google.maps.event.addListener(marker, 'mouseover', function() {
            infowindow.setContent(html); 
            infowindow.open(map, marker); 

    });
    google.maps.event.addListener(marker, 'mouseout', function() {
        infowindow.close();

    }); 
} 

完整的工作示例。您只需复制、粘贴并使用即可。


12

来自Google地图API示例

function initialize() {
  var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(-33.9, 151.2),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(document.getElementById("map_canvas"),
                                myOptions);

  setMarkers(map, beaches);
}

/**
 * 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, locations) {
  // Add 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 = new google.maps.MarkerImage('images/beachflag.png',
      // This marker is 20 pixels wide by 32 pixels tall.
      new google.maps.Size(20, 32),
      // The origin for this image is 0,0.
      new google.maps.Point(0,0),
      // The anchor for this image is the base of the flagpole at 0,32.
      new google.maps.Point(0, 32));
  var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
      // The shadow image is larger in the horizontal dimension
      // while the position and offset are the same as for the main image.
      new google.maps.Size(37, 32),
      new google.maps.Point(0,0),
      new google.maps.Point(0, 32));
      // Shapes define the clickable region of the icon.
      // The type defines an HTML &lt;area&gt; 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 = {
      coord: [1, 1, 1, 20, 18, 20, 18 , 1],
      type: 'poly'
  };
  for (var i = 0; i < locations.length; i++) {
    var beach = locations[i];
    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        shadow: shadow,
        icon: image,
        shape: shape,
        title: beach[0],
        zIndex: beach[3]
    });
  }
}

8
此回答不包含 infoWindow 部分。 - onurmatik
@omat 奇怪的是,谷歌自己的文档并没有建议必须有 infoWindow 部分。但无论如何,它对我也不起作用 :( - Emil Ahlbäck
提供的链接未找到。 - Shailendra Madda

11

我写了另一种版本来节省地图空间,它将infowindow指针放在标记的实际经纬度上,同时在显示infowindow时暂时隐藏标记。

它还取消了标准的“标记”分配,并通过直接将新标记分配到标记创建时的标记数组中加快处理速度。不过请注意,这种方法已向标记和infowindow添加了其他属性,因此略有些不同寻常......但这就是我!

在这些Infowindow问题中从未提到过,标准的Infowindow不是放置在标记点的经纬度上,而是放置在标记图像的顶部。必须隐藏标记可见性才能使其工作,否则Maps API会将infowindow锚点再次推回到标记图像的顶部。

'markers'数组中对标记的引用是在标记声明时立即创建的,以便进行任何可能需要的其他处理任务(隐藏/显示、抓取坐标等...)。这样可以省去将标记对象分配给'marker',然后将'marker'推到标记数组中的额外步骤,这在我的书中是很多不必要的处理。

总之,这是一个不同于传统方式的infowindows实现,希望能够帮助和启发您。

    var locations = [
      ['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]
    ];
    var map;
    var markers = [];

    function init(){
      map = new google.maps.Map(document.getElementById('map_canvas'), {
        zoom: 10,
        center: new google.maps.LatLng(-33.92, 151.25),
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });

      var num_markers = locations.length;
      for (var i = 0; i < num_markers; i++) {  
        markers[i] = new google.maps.Marker({
          position: {lat:locations[i][1], lng:locations[i][2]},
          map: map,
          html: locations[i][0],
          id: i,
        });

        google.maps.event.addListener(markers[i], 'click', function(){
          var infowindow = new google.maps.InfoWindow({
            id: this.id,
            content:this.html,
            position:this.getPosition()
          });
          google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
            markers[this.id].setVisible(true);
          });
          this.setVisible(false);
          infowindow.open(map);
        });
      }
    }

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

这里是一个可运行的JSFiddle

附加说明
在此给出的 Google 示例数据中,您会注意到“位置”数组中有第四个地点,其中包含一个数字。鉴于这个示例,您也可以使用该值来替换当前循环值作为标记符号ID,例如...

var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {  
  markers[i] = new google.maps.Marker({
    position: {lat:locations[i][1], lng:locations[i][2]},
    map: map,
    html: locations[i][0],
    id: locations[i][3],
  });
};

10

ES6重写的被接受的答案:

$(document).ready(() => {
  const mapEl = $('#our_map').get(0); // OR document.getElementById('our_map');

  // Display a map on the page
  const map = new google.maps.Map(mapEl, { mapTypeId: 'roadmap' });

  const buildings = [
    {
      title: 'London Eye, London', 
      coordinates: [51.503454, -0.119562],
      info: 'carousel'
    },
    {
      title: 'Palace of Westminster, London', 
      coordinates: [51.499633, -0.124755],
      info: 'palace'
    }
  ];

  placeBuildingsOnMap(buildings, map);
});


const placeBuildingsOnMap = (buildings, map) => {
  // Loop through our array of buildings & place each one on the map  
  const bounds = new google.maps.LatLngBounds();
  buildings.forEach((building) => {
    const position = { lat: building.coordinates[0], lng: building.coordinates[1] }
    // Stretch our bounds to the newly found marker position
    bounds.extend(position);

    const marker = new google.maps.Marker({
      position: position,
      map: map,
      title: building.title
    });

    const infoWindow = new google.maps.InfoWindow();
    // Allow each marker to have an info window
    google.maps.event.addListener(marker, 'click', () => {
      infoWindow.setContent(building.info);
      infoWindow.open(map, marker);
    })

    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
  })
})

7
在您的程序中添加标记非常容易。您只需添加以下代码即可:
var marker = new google.maps.Marker({
  position: myLatLng,
  map: map,
  title: 'Hello World!'
});

以下字段在构建标记时特别重要并且常被设置:
  • position(必填)指定一个LatLng,用于标识标记的初始位置。获取LatLng的一种方法是使用地理编码服务
  • map(可选)指定要放置标记的地图。如果在创建标记时不指定地图,则会创建标记但不会附加到(或显示在)地图上。您可以通过调用标记的setMap()方法稍后添加标记。

注意:在示例中,title字段设置了标记的标题,它将出现为工具提示。

您可以在此处查看Google api文档。


以下是在地图中设置一个标记的完整示例。请注意,您必须用您的google API密钥替换YOUR_API_KEY

<!DOCTYPE html>
<html>
<head>
   <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
   <meta charset="utf-8">
   <title>Simple markers</title>
<style>
  /* 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;
  }
</style>
</head>
<body>
 <div id="map"></div>
<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!'
    });
  }
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

现在,如果您想在地图上绘制一个数组的标记,您应该这样做:
var locations = [
  ['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 initMap() {
  var myLatLng = {lat: -33.90, lng: 151.16};

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

  var count;

  for (count = 0; count < locations.length; count++) {  
    new google.maps.Marker({
      position: new google.maps.LatLng(locations[count][1], locations[count][2]),
      map: map,
      title: locations[count][0]
      });
   }
}

这个示例给了我以下结果:

在此输入图片描述


你还可以在你的标记中添加一个信息窗口,只需要使用以下代码:

var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[count][1], locations[count][2]),
    map: map
    });

marker.info = new google.maps.InfoWindow({
    content: 'Hello World!'
    });

您可以在此处获取有关信息窗口的Google文档


现在,我们可以像这样在标记被“单击”时打开 infoWindow:

var marker = new google.maps.Marker({
     position: new google.maps.LatLng(locations[count][1], locations[count][2]),
     map: map
     });

marker.info = new google.maps.InfoWindow({
     content: locations [count][0]
     });


google.maps.event.addListener(marker, 'click', function() {  
    // this = marker
    var marker_map = this.getMap();
    this.info.open(marker_map, this);
    // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
            });

注意,您可以在Google开发者网站上这里找到有关Listener的一些文档。


最后,如果用户单击标记,我们可以在标记中绘制一个信息窗口。 这是完整的代码:

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Info windows</title>
    <style>
    /* 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;
    }
    </style>
</head>
<body>
    <div id="map"></div>
    <script>

    var locations = [
        ['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]
    ];


    // When the user clicks the marker, an info window opens.

    function initMap() {
        var myLatLng = {lat: -33.90, lng: 151.16};

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

        var count=0;


        for (count = 0; count < locations.length; count++) {  

            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(locations[count][1], locations[count][2]),
                map: map
                });

            marker.info = new google.maps.InfoWindow({
                content: locations [count][0]
                });


            google.maps.event.addListener(marker, 'click', function() {  
                // this = marker
                var marker_map = this.getMap();
                this.info.open(marker_map, this);
                // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
                });
        }
    }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
</body>
</html>

通常情况下,您应该得到以下结果:

您的结果


6

来源 链接

演示 链接

完整的HTML代码

  • 点击或悬停时显示信息窗口。
  • 只会显示一个信息窗口。

在此输入图片描述

    <!DOCTYPE html>
    <html>

    <head>
        <style>
            /*  <span class="metadata-marker" style="display: none;" data-region_tag="css"></span>       Set the size of the div element that contains the map */
            #map {
                height: 400px;
                /* The height is 400 pixels */
                width: 100%;
                /* The width is the width of the web page */
            }
        </style>
        <script>
            var map;
            var InforObj = [];
            var centerCords = {
                lat: -25.344,
                lng: 131.036
            };
            var markersOnMap = [{
                    placeName: "Australia (Uluru)",
                    LatLng: [{
                        lat: -25.344,
                        lng: 131.036
                    }]
                },
                {
                    placeName: "Australia (Melbourne)",
                    LatLng: [{
                        lat: -37.852086,
                        lng: 504.985963
                    }]
                },
                {
                    placeName: "Australia (Canberra)",
                    LatLng: [{
                        lat: -35.299085,
                        lng: 509.109615
                    }]
                },
                {
                    placeName: "Australia (Gold Coast)",
                    LatLng: [{
                        lat: -28.013044,
                        lng: 513.425586
                    }]
                },
                {
                    placeName: "Australia (Perth)",
                    LatLng: [{
                        lat: -31.951994,
                        lng: 475.858081
                    }]
                }
            ];

            window.onload = function () {
                initMap();
            };

            function addMarkerInfo() {
                for (var i = 0; i < markersOnMap.length; i++) {
                    var contentString = '<div id="content"><h1>' + markersOnMap[i].placeName +
                        '</h1><p>Lorem ipsum dolor sit amet, vix mutat posse suscipit id, vel ea tantas omittam detraxit.</p></div>';

                    const marker = new google.maps.Marker({
                        position: markersOnMap[i].LatLng[0],
                        map: map
                    });

                    const infowindow = new google.maps.InfoWindow({
                        content: contentString,
                        maxWidth: 200
                    });

                    marker.addListener('click', function () {
                        closeOtherInfo();
                        infowindow.open(marker.get('map'), marker);
                        InforObj[0] = infowindow;
                    });
                    // marker.addListener('mouseover', function () {
                    //     closeOtherInfo();
                    //     infowindow.open(marker.get('map'), marker);
                    //     InforObj[0] = infowindow;
                    // });
                    // marker.addListener('mouseout', function () {
                    //     closeOtherInfo();
                    //     infowindow.close();
                    //     InforObj[0] = infowindow;
                    // });
                }
            }

            function closeOtherInfo() {
                if (InforObj.length > 0) {
                    /* detach the info-window from the marker ... undocumented in the API docs */
                    InforObj[0].set("marker", null);
                    /* and close it */
                    InforObj[0].close();
                    /* blank the array */
                    InforObj.length = 0;
                }
            }

            function initMap() {
                map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 4,
                    center: centerCords
                });
                addMarkerInfo();
            }
        </script>
    </head>

    <body>
        <h3>My Google Maps Demo</h3>
        <!--The div element for the map -->
        <div id="map"></div>

        <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>

    </body>

    </html>

1
谢谢你提供 closeOtherInfo,在你的回答之前我找不到一个好的解决方案来处理merkercluster。 :) - chris loughnane
1
那正是我正在寻找的。谢谢,兄弟,这在2020年工作得很好。 - Faizan Anwer Ali Rupani

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接