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个回答

4

Daniel Vassallo的答案之后,这里有一个更简单处理闭包问题的版本。

由于每个标记都会有一个独立的InfoWindow,而且JavaScript对于在对象中添加额外属性并不关心,所以您只需要将InfoWindow添加到Marker属性中,然后从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);
  })
}

3
  • 我知道这个答案太晚了,但希望这可以帮助其他开发者。 :-)
  • 以下代码将在谷歌地图上添加多个标记,并附带信息窗口。
  • 此代码可用于在地图上绘制任意数量的标记。
  • 请将您的Google地图API密钥放置在代码的正确位置。(我已将其标记为"Your API Key")
<!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>

2
以下是一个几乎完整的 JavaScript 函数示例,可以允许在 JSONObject 中定义多个标记。
它只会显示地图范围内的标记。这很重要,因为您不希望多做无用功。
您还可以设置标记的限制,以避免显示过多的标记(如果在您的使用中有可能出现这种情况);
如果地图中心没有移动超过500米,则也不会显示标记。这很重要,因为如果用户单击标记并在此同时意外拖动地图,则不希望地图重新加载标记。
我将此函数附加到地图的空闲事件侦听器上,因此标记仅在地图空闲时显示,并在其他事件后重新显示标记。
在操作屏幕截图中,信息窗口中的内容稍有改变。 enter image description here 以上内容来自 pastbin.com。

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


2
最近在当前地图标记和聚合算法的修改中最简单的是:
改动项:https://developers.google.com/maps/documentation/javascript/marker-clustering 图片展示如下:enter image description here
<!DOCTYPE Html>
<html>
<head>
<meta Content-Security-Policy="default-src  'self'; script-src 'self' 'unsafe-eval' https://*/;">
<link type="text/css" href="http://www.mapsmarker.com/wp-content/uploads/leaflet-maps-marker-icons/bar_coktail.png">
<link rel="icon" href="data:,">
<title>App</title>
</head>
<style type="text/css">
   #map {
    height: 500
}
</style>

<body>
<div id='map' style="width:100%; height:400px"></div>
<script type='text/javascript'>
    function initMap() {
        maps = new google.maps.Map(document.getElementById('map'), {
            center: new google.maps.LatLng(12.9824855, 77.637094),
            zoom: 5,
            disableDefaultUI: false,
            mapTypeId: google.maps.MapTypeId.HYBRID
        });
        var labels='ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        var markerImage = 'http://www.mapsmarker.com/wp-content/uploads/leaflet-maps-marker-icons/bar_coktail.png';
        marker = locations.map(function (location, i) {
            return new google.maps.Marker({
                position: new google.maps.LatLng(location.lat, location.lng),
                map: maps,
                title: "Map",
                label: labels[i % labels.length],
                icon: markerImage
            });
        });

        var markerCluster = new MarkerClusterer(maps, marker, {
            imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
        });
    }
    var locations = [
            { lat: 12.9824855, lng: 77.637094},
            { lat: 11.9824855, lng: 77.154312 },
            { lat: 12.8824855, lng: 77.637094},
            { lat: 10.8824855, lng: 77.054312 },
            { lat: 12.9824855, lng: 77.637094},
            { lat: 11.9824855, lng: 77.154312 },
            { lat: 12.8824855, lng: 77.637094},
            { lat: 13.8824855, lng: 77.054312 },
            { lat: 14.9824855, lng: 54.637094},
            { lat: 15.9824855, lng: 54.154312 },
            { lat: 16.8824855, lng: 53.637094},
            { lat: 17.8824855, lng: 52.054312 },
            { lat: 18.9824855, lng: 51.637094},
            { lat: 19.9824855, lng: 69.154312 },
            { lat: 20.8824855, lng: 68.637094},
            { lat: 21.8824855, lng: 67.054312 },
            { lat: 12.9824855, lng: 76.637094},
            { lat: 11.9824855, lng: 75.154312 },
            { lat: 12.8824855, lng: 74.637094},
            { lat: 10.8824855, lng: 74.054312 },
            { lat: 12.9824855, lng: 73.637094},
            { lat: 3.9824855, lng: 72.154312 },
            { lat: 2.8824855, lng: 71.637094},
            { lat: 1.8824855, lng: 70.054312 }
        ];

</script>
<script src="https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js">
</script>
<script src="https:maps.googleapis.com/maps/api/js?key=AIzaSyDWu6_Io9xA1oerfOxE77YAv31etN4u3Dw&callback=initMap">
</script>
<script type='text/javascript'></script>

0

这是一个在Reactjs中使用多个标记的示例。

enter image description here

以下是地图组件

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,
};


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