谷歌Maps 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来显示名称。


当前回答

在程序中添加标记非常简单。你只需要添加以下代码:

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

当你构造一个标记时,下面的字段是特别重要和经常设置的:

position(必选)指定标识标记初始位置的LatLng。检索LatLng的一种方法是使用地理编码服务。 map(可选)指定放置标记的map。如果在构建标记时没有指定映射,则会创建标记,但不会附加到(或显示在)映射上。稍后可以通过调用标记的setMap()方法添加标记。

注意,在本例中,标题字段设置了将作为工具提示显示的标记标题。

您可以在这里查阅谷歌api文档。


这是在地图中设置一个标记的完整示例。注意,你必须用你的谷歌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>


现在,如果你想在map中绘制数组的标记,你应该这样做:

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]
      });
   }
}

这个例子给出了如下结果:


你也可以在你的pin中添加一个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: 'Hello World!'
    });

你可以在这里找到谷歌关于infoWindows的文档。


现在,我们可以在标记像这样“点击”时打开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.
            });

注意,您可以在谷歌developer中获得一些关于Listener的文档。


最后,如果用户点击它,我们可以在标记中绘制一个infoWindow。这是我的完整代码:

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

通常,你会得到这样的结果:

其他回答

来自谷歌Map 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]
    });
  }
}

我知道这个答案太迟了。但我希望这也能帮助到其他开发者。: -) 下面的代码将使用信息窗口在谷歌地图上添加多个标记。 这段代码可以用来在地图上绘制任意数量的标记。 请将您的谷歌映射API键放在此代码的正确位置。(我已将其标记为“您的API密钥”)


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Google Map</title>
    <style>
        #map{
            height: 600px;
            width: 100%;
        }
    </style>
</head>
<body>

<h1>My Google Map`</h1>
<div id="map"></div>


    <script>
        function initMap(){
          //Map options
            var options = {
                zoom:9,
                center:{lat:42.3601, lng:-71.0589}
            }
            // new map
            var map = new google.maps.Map(document.getElementById('map'), options);
            // customer marker
            var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/parking_lot_maps.png';
            //array of Marrkeers
            var markers = [
              {
                coords:{lat: 42.4668, lng: -70.9495},img:iconBase,con:'<h3> This Is your Content <h3>'
              },
              {
                coords:{lat: 42.8584, lng: -70.9300},img:iconBase,con:'<h3> This Is your Content <h3>'
              },
              {
                coords:{lat: 42.7762, lng: -71.0773},img:iconBase,con:'<h3> This Is your Content <h3>'
              }
            ];

            //loopthrough markers
            for(var i = 0; i <markers.length; i++){
              //add markeers
              addMarker(markers[i]);
            }

            //function for the plotting markers on the map
            function addMarker (props){
              var marker = new google.maps.Marker({
                position: props.coords,
                map:map,
                icon:props.img
              });
              var infoWindow = new google.maps.InfoWindow({
                content:props.con,
              });
              marker.addListener("click", () => {
                infoWindow.open(map, marker);
              });
            }
        }
    </script>

    <script
      src="https://maps.googleapis.com/maps/api/js?key=**YourAPIKey**&callback=initMap"
      defer
    ></script>

</body>
</html>

根据Daniel Vassallo的回答,下面是一个以更简单的方式处理闭包问题的版本。

因为所有的标记都有一个单独的InfoWindow,而且JavaScript并不关心你是否给对象添加了额外的属性,你所需要做的就是给标记的属性添加一个InfoWindow,然后调用InfoWindow本身的.open() !

编辑:有了足够的数据,页面加载可能会花费很多时间,因此与其使用标记构造InfoWindow,不如只在需要时进行构造。注意,用于构造InfoWindow的任何数据都必须作为属性(data)追加到Marker。还要注意,在第一次单击事件之后,infoWindow将作为它的标记的属性持久化,因此浏览器不需要不断地重构。

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'), {
  center: new google.maps.LatLng(-33.92, 151.25)
});

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,
    data: {
      name: locations[i][0]
    }
  });
  marker.addListener('click', function() {
    if(!this.infoWindow) {
      this.infoWindow = new google.maps.InfoWindow({
        content: this.data.name;
      });
    }
    this.infoWindow.open(map,this);
  })
}

下面是另一个使用唯一标题和infoWindow文本加载多个标记的示例。使用最新的谷歌映射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个标记的截图:

它将自动随机化Lat/Lng,使其独一无二。如果你想测试500、1000、xxx标记和性能,这个例子将非常有用。

下面是一个几乎完整的示例javascript函数,它允许在JSONObject中定义多个标记。

它将只显示在地图边界内的标记。

这很重要,这样你就不用做额外的工作了。

你也可以设置一个标记的限制,这样你就不会显示一个极端数量的标记(如果有可能在你的使用);

如果地图中心的变化不超过500米,就不会显示标记。 这很重要,因为如果用户单击标记并在此过程中意外地拖动了地图,您不希望地图重新加载标记。

我将这个函数附加到地图的空闲事件侦听器,因此标记只在地图空闲时显示,并在不同的事件后重新显示标记。

活动屏幕截图 在信息窗口中显示更多内容的屏幕截图有一个小变化。 粘贴自pastbin.com

<script src=“//pastebin.com/embed_js/uWAbRxfg”></script>