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

标签 javascript google-maps google-maps-api-3

对于 Google Maps Api 来说相当新。我有一组数据想要循环浏览并绘制在 map 上。看起来相当简单,但我发现的所有多标记教程都相当复杂。

让我们使用 Google 网站上的数据数组作为示例:

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

最佳答案

这是我可以将其简化为的最简单的:

<!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>

👨‍💻 Edit/fork on a Codepen →

屏幕截图

Google Maps Multiple Markers

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

Mozilla Dev Center: Working with Closures

关于javascript - Google Maps JS API v3 - 简单的多标记示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45989626/

相关文章:

javascript - 如何按空格分割字符串,而不是由指定字符包裹?

google-maps - Google Map Animate ImageMapType 叠加层

google-maps - 确定坐标是否在 Google map 范围内?

javascript - 非规范化属性值 - 将驼峰式值转换为短划线分隔值

javascript - jquery异常

database - Postgis ST_DIstance 查询返回不准确的结果

javascript - 如何防止谷歌地理编码器从其他国家返回结果

android - Google Maps v2 - 设置我的位置并放大

javascript - Google Maps API V3 - 无论如何检索自动完成结果而不是下拉呈现它?

javascript - React 中的状态正在返回到原始值