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


657

对Google Maps Api来说还很新。我有一个要循环浏览并在地图上绘制的数据数组。看起来很简单,但是我发现的所有多标记教程都很复杂。

让我们以来自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。

Answers:


1128

这是我可以简化为的最简单的方法:

<!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?sensor=false" 
          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>

a Codepen上编辑/分叉→

屏幕截图

Google Maps多个标记

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

❯Mozilla 开发人员中心:处理闭包


4
@RaphaelDDL:是的,需要这些括号才能实际调用无名函数。由于JavaScript的工作方式(由于闭包),需要传递参数。有关示例和更多信息,请参见我对这个问题的回答:stackoverflow.com/a/2670420/222908
Daniel Vassallo 2012年

好的答案,但是可以进一步简化。由于所有标记都具有单独的InfoWindows,并且JavaScript不在乎是否向对象添加额外的属性,因此您所需要做的就是InfoWindow在标记的属性中添加,然后.open()从自身调用InfoWindow。我会在此处发布更改,但所做的修改足够大,因此我可以发布自己的答案
马修·科尔达罗

为什么不使用new MarkerClusterer()大规模性能崩溃呢?查看ChirsSwires答案。
DevWL

嗨@ Daniel Vassallo,我也有同样的要求在我的离子角项目中显示多个标记。请帮助我,我已经问过一个关于stackoverflow的问题。这是问题链接:stackoverflow.com/questions/57985967/…–
Saif

有用。谢谢。您将如何从Google地图中删除标记,因为您使用的是标记的单个实例并在循环中初始化。请分享您的想法。
卡姆列什

59

这是使用唯一标记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

它将自动随机化纬度/经度以使其唯一。如果要测试500、1000,xxx标记和性能,此示例将非常有帮助。


1
在发布复制和粘贴多个问题的样板/惯用答案时要小心,这些问题通常会被社区标记为“垃圾邮件”。如果您这样做,通常意味着问题是重复的,因此应将其标记为重复。
凯夫

1
infoWindow每个标记都会弹出很多,并且infoWindow如果当前显示另一个,则不会隐藏其他标记。这真的很有帮助:)
肯尼卡2014年

@Anup,如果您只是阅读问题并发表评论,那会更好。问题是问“多个标记示例”是随机的还是您自己的。
马丹萨普塔

同样,为什么不将其new MarkerClusterer()用于大规模的绩效破产呢?查看ChirsSwires答案。
DevWL '19

1
@DevWL,它在2013年得到了答复。您可以自由更新。
马丹·萨普柯塔

39

我想把它放在这里,因为对于那些开始使用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>

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

这些实现不仅大大提高了客户端性能,而且在许多情况下还导致更简单,更混乱的UI以及更大规模的数据摘要。

其他实现可以从Google获得。

希望这对一些较新的映射有所帮助。


2
谢谢,很大的帮助!通过首先制作google.map数据点,然后将其传递到映射库(在本例中为MarketCluster进行绘制),性能会有数量级或大小上的差异。大约有150,000个数据点,“ Daniel Vassallo”的第一篇文章耗时约2分钟,即5秒钟。谢谢一堆“太古”!
Waqas 2014年

1
我以为这是个好地方,我可以想象大多数人会首先在与Google地图相关的页面上登陆该页面,其次是“为什么我的地图需要这么长时间才能加载”。
ChrisSwires 2014年

@Monic无论您的数据集是什么,它只是一个占位符变量。
ChrisSwires

20

异步版本:

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

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

8
此答案不包括infoWindow部分
onurmatik 2011年

@omat奇怪的是,谷歌自己的文档并不建议必须有一个infoWindow部分。但是尽管如此,它对我也
不起作用

11

这是我写的另一种保存地图资源的版本,将信息窗口指针放在标记的实际纬度和长度上,同时在显示信息窗口时暂时隐藏标记。

它还取消了标准“标记”的分配,并通过在标记创建时将新标记直接分配给标记数组来加快处理速度。但是请注意,标记和信息窗口均已添加了其他属性,因此这种方法有点不合常规……但这就是我!

在这些信息窗口问题中从未提到过,标准信息窗口不是放置在标记点的纬度和经度上,而是放置在标记图像的顶部。标记的可见性必须隐藏才能正常工作,否则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]
    ];
    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);
  })
})

6

链接

演示链接

完整的HTML代码

  • 单击或悬停时显示InfoWindow。
  • 仅显示一个InfoWindow

在此处输入图片说明

    <!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
所做的出色

5

在程序中添加标记非常容易。您可以添加以下代码:

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

构造标记时,以下字段特别重要,并且通常会设置这些字段:

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

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

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


这是在地图上设置一个标记的完整示例。要小心满了,你必须更换YOUR_API_KEY你的谷歌API密钥

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

这个例子给我以下结果:

在此处输入图片说明


您也可以在图钉中添加一个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的Google文档。


现在,当标记为“ clik”时,我们可以打开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 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>

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

您的结果


4

Daniel Vassallo的回答之后,这是一个以更简单的方式处理关闭问题的版本。

自从所有标记有个人信息窗口和JavaScript的,因为如果添加额外的属性到对象不关心,所有你需要做的就是添加一个信息窗口标记的属性,然后调用.open()上的信息窗口的本身!

编辑:如果有足够的数据,页面加载可能会花费大量时间,所以与其使用标记构造InfoWindow,不应该仅在需要时进行构造。注意,任何用于构造InfoWindow的数据都必须作为属性()附加到Markerdata。另请注意,在首次单击事件之后,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);
  })
}

2

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

它只会显示地图范围内的标记。

这很重要,因此您无需做额外的工作。

您还可以为标记设置一个限制,这样就不会显示过多的标记(如果使用中可能有问题);

如果地图中心变化不​​超过500米,它也不会显示标记。
这很重要,因为如果用户单击标记并在执行操作时不小心拖动了地图,则您不希望地图重新加载标记。

我将此功能附加到了地图的空闲事件监听器上,因此标记仅在地图空闲时才会显示,并在发生其他事件后重新显示标记。

在动作屏幕快照中,屏幕快照有一点变化,显示了信息窗口中的更多内容。 在此处输入图片说明 从pastbin.com粘贴

<script src="//pastebin.com/embed_js/uWAbRxfg"></script>


0

这是Reactjs中多个标记的示例

在此处输入图片说明

以下是地图组件

import React from 'react';
import PropTypes from 'prop-types';
import { Map, InfoWindow, Marker, GoogleApiWrapper } from 'google-maps-react';

const MapContainer = (props) => {
  const [mapConfigurations, setMapConfigurations] = useState({
    showingInfoWindow: false,
    activeMarker: {},
    selectedPlace: {}
  });

  var points = [
    { lat: 42.02, lng: -77.01 },
    { lat: 42.03, lng: -77.02 },
    { lat: 41.03, lng: -77.04 },
    { lat: 42.05, lng: -77.02 }
  ]
  const onMarkerClick = (newProps, marker) => {};

  if (!props.google) {
    return <div>Loading...</div>;
  }

  return (
    <div className="custom-map-container">
      <Map
        style={{
          minWidth: '200px',
          minHeight: '140px',
          width: '100%',
          height: '100%',
          position: 'relative'
        }}
        initialCenter={{
          lat: 42.39,
          lng: -72.52
        }}
        google={props.google}
        zoom={16}
      >
        {points.map(coordinates => (
          <Marker
            position={{ lat: coordinates.lat, lng: coordinates.lng }}
            onClick={onMarkerClick}
            icon={{
              url: 'https://res.cloudinary.com/mybukka/image/upload/c_scale,r_50,w_30,h_30/v1580550858/yaiwq492u1lwuy2lb9ua.png',
            anchor: new google.maps.Point(32, 32), // eslint-disable-line
            scaledSize: new google.maps.Size(30, 30)  // eslint-disable-line
            }}
            name={name}
          />))}
        <InfoWindow
          marker={mapConfigurations.activeMarker}
          visible={mapConfigurations.showingInfoWindow}
        >
          <div>
            <h1>{mapConfigurations.selectedPlace.name}</h1>
          </div>
        </InfoWindow>
      </Map>
    </div>
  );
};

export default GoogleApiWrapper({
  apiKey: process.env.GOOGLE_API_KEY,
  v: '3'
})(MapContainer);

MapContainer.propTypes = {
  google: PropTypes.shape({}).isRequired,
};
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.