我添加了新标记并将其推入markers [],但无法在地图上再次显示它们。我已阅读可能的论坛和主题(谷歌开发人员等),但无法弄清楚。任何帮助和建议,将不胜感激。提前致谢。



        var map;
		var markers = [];	//markers is an array variable with global scope
		var myLatLng = {lat: 40.6069135, lng: 22.9566052};
		//var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		//var labelIndex = 0;

		var locations = [
		  ['First Fire Station', 40.635325, 22.955178],
		  ['Second Fire Station', 40.645071, 22.926711],
		  ['Third Fire Station', 40.599891, 22.956932],
		  ['Observer 1', 40.631225, 23.031213],
		  ['Observer 2', 40.604363, 23.032420]
		];

		function initMap() {
			var infowindow = new google.maps.InfoWindow();

			var map = new google.maps.Map(document.getElementById('map'), {
				zoom: 12,
				center: myLatLng,
				mapTypeControl: true,
				mapTypeControlOptions: {
					style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
					position: google.maps.ControlPosition.TOP_RIGHT,
					mapTypeIds: ['roadmap', 'terrain', 'satellite']
				}
			});

			function placeMarker( loc ) {
				var latLng = new google.maps.LatLng( loc[1], loc[2]);
				var marker = new google.maps.Marker({
					position: latLng,
					map: map
				});

				google.maps.event.addListener(marker, 'click', function(){
					infowindow.close(); // Close previously opened infowindow
					infowindow.setContent( "<div id='infowindow'>"+ loc[0] +"</div>");
					infowindow.open(map, marker);
					});
			}

			for (var i = 0; i < locations.length; i++){
				placeMarker(locations[i]);
			}


			// This event listener will call addMarker() when the map is clicked.
			google.maps.event.addListener(map, 'click', function(event) {
				addMarker(event.latLng, map);
			});
		}

		// Adds a marker to the map and push to the array.
		function addMarker(location, map) {
		  var marker = new google.maps.Marker({
			position: location,
			//label: labels[labelIndex++ % labels.length],
			map: map
		  });
		  markers.push(marker);
		}

		// Sets the map on all markers in the array.
		function setMapOnAll(map) {
		  for (var i = 0; i < markers.length; i++) {
			markers[i].setMap(map);
		  }
		}

		// Removes the markers from the map, but keeps them in the array.
		function clearMarkers() {
		  setMapOnAll(null);
		}

		// Shows any markers currently in the array.
		function showMarkers() {
		  setMapOnAll(map);
		}

		// Deletes all markers in the array by removing references to them.
		function deleteMarkers() {
		  clearMarkers();
		  markers = [];
		}

<!DOCTYPE html>
<html>
  <head>
    <title>cl 1.2</title>
    <meta name="viewport" content="initial-scale=1.0">
    <meta charset="utf-8">
    <script async defer src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
	<script src="script.js"></script>
    <script async defer>
    </script>
      <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGHuOFn-gCv9AUDNclsfNDhMvVkkcNU4Y&callback=initMap&libraries=geometry,places">
	</script>
    <style>
      html, body {height: 100%; margin: 0; padding: 0;}
      #map {height: 100%;}
	  #infowindow {padding: 10;}
	  #floating-panel {position: absolute; top: 50px; left: 40%; z-index: 5; background-color: #fff; padding: 5px; border: 1px solid #999; text-align: center; font-family: 'Roboto','sans-serif'; line-height: 30px; padding-left: 10px;}
    </style>
  </head>
  <body>
	<div id="map"></div>
	<div id="infowindow"></div>
	<div id="floating-panel">
            <input onclick="clearMarkers();" type=button value="Hide Markers">
            <input onclick="showMarkers();" type=button value="Show All Markers">
            <input onclick="deleteMarkers();" type=button value="Delete Markers">
    </div>
  </body>
</html>

最佳答案

您需要初始化全局映射变量。

更改:

var map;
function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {


至:

var map;
function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {


代码段:



var map;
var markers = []; //markers is an array variable with global scope
var myLatLng = {
  lat: 40.6069135,
  lng: 22.9566052
};
//var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
//var labelIndex = 0;

var locations = [
  ['First Fire Station', 40.635325, 22.955178],
  ['Second Fire Station', 40.645071, 22.926711],
  ['Third Fire Station', 40.599891, 22.956932],
  ['Observer 1', 40.631225, 23.031213],
  ['Observer 2', 40.604363, 23.032420]
];

function initMap() {
  var infowindow = new google.maps.InfoWindow();

  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: myLatLng,
    mapTypeControl: true,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
      position: google.maps.ControlPosition.TOP_RIGHT,
      mapTypeIds: ['roadmap', 'terrain', 'satellite']
    }
  });

  function placeMarker(loc) {
    var latLng = new google.maps.LatLng(loc[1], loc[2]);
    var marker = new google.maps.Marker({
      position: latLng,
      map: map
    });

    google.maps.event.addListener(marker, 'click', function() {
      infowindow.close(); // Close previously opened infowindow
      infowindow.setContent("<div id='infowindow'>" + loc[0] + "</div>");
      infowindow.open(map, marker);
    });
  }

  for (var i = 0; i < locations.length; i++) {
    placeMarker(locations[i]);
  }


  // This event listener will call addMarker() when the map is clicked.
  google.maps.event.addListener(map, 'click', function(event) {
    addMarker(event.latLng, map);
  });
}

// Adds a marker to the map and push to the array.
function addMarker(location, map) {
  var marker = new google.maps.Marker({
    position: location,
    //label: labels[labelIndex++ % labels.length],
    map: map
  });
  markers.push(marker);
}

// Sets the map on all markers in the array.
function setMapOnAll(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
  }
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setMapOnAll(null);
}

// Shows any markers currently in the array.
function showMarkers() {
  setMapOnAll(map);
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
  clearMarkers();
  markers = [];
}

<!DOCTYPE html>
<html>

<head>
  <title>cl 1.2</title>
  <meta name="viewport" content="initial-scale=1.0">
  <meta charset="utf-8">
  <script async defer src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGHuOFn-gCv9AUDNclsfNDhMvVkkcNU4Y&callback=initMap&libraries=geometry,places">
  </script>
  <style>
    html,
    body {
      height: 100%;
      margin: 0;
      padding: 0;
    }
    #map {
      height: 100%;
    }
    #infowindow {
      padding: 10;
    }
    #floating-panel {
      position: absolute;
      top: 50px;
      left: 40%;
      z-index: 5;
      background-color: #fff;
      padding: 5px;
      border: 1px solid #999;
      text-align: center;
      font-family: 'Roboto', 'sans-serif';
      line-height: 30px;
      padding-left: 10px;
    }
  </style>
</head>

<body>
  <div id="map"></div>
  <div id="infowindow"></div>
  <div id="floating-panel">
    <input onclick="clearMarkers();" type=button value="Hide Markers">
    <input onclick="showMarkers();" type=button value="Show All Markers">
    <input onclick="deleteMarkers();" type=button value="Delete Markers">
  </div>
</body>

</html>

10-06 04:46