只能在Google Map API v3上切换一次标记

时间:2015-11-21 03:46:05

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

我使用Google Map API v3设置了一个简单的Google Map界面,并希望实现一个可以切换标记的功能,但它无法正常运行。关闭图层后我无法打开它。

var request;
var places;
var map;
var markers = [];
var myLatLng = {lat: 34, lng: 38};

// load database and parse into entries
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest();
} else {
    request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET', 'places.json');
request.onreadystatechange = function() {
    if ((request.readyState ===4) && (request.status===200)) {
        places = JSON.parse(request.responseText);
        initMap();
        console.log(places);
    }
}
request.send();

function initMap() {
    // map options
    var mapOptions = {
        zoom: 6,
        center: myLatLng,
        mapTypeControl: true,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };
    // initialise the map
    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    // add markers
    for (var i = 0; i < places.length; i++) {
        // the place
        var place = places[i];
        // place co-ordinates
        var latlng = new google.maps.LatLng(place.latitude, place.longitude);
        var marker = new google.maps.Marker({
            position: latlng,
            map: map, 
            title: place.city
        });
        markers.push(marker);
        var infowindow = new google.maps.InfoWindow;
        google.maps.event.addListener(marker, 'click', (function(marker){ 
            return function() {
                infowindow.open(map,marker);
            };
        })(marker));
    }
}

function toggleMarkers() {
    for (var i = 0; i < markers.length; i++) {
        if (markers[i].getMap() === null) {
            markers[i].setMap(map);
        } else {
            console.log(markers[0].setMap())
            markers[i].setMap(null);
        }
    }
}

在HTML中调用ToggleMarkers函数。

<!DOCTYPE html>
<head>
    <!-- scripts -->
    <script src="script2.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false&key="API Key"&callback=initMap"></script>
</head>
<body>
    <div id="panel">
      <button onclick="toggleMarkers()">Toggle Markers</button>
    </div>
    <div id="map"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的map变量是initMap函数的本地变量。

改变这个:

function initMap() {
  // map options
  var mapOptions = {
      zoom: 6,
      center: myLatLng,
      mapTypeControl: true,
      mapTypeId: google.maps.MapTypeId.HYBRID
  };
  // initialise the map
  var map = new google.maps.Map(document.getElementById('map'), mapOptions);

致:

function initMap() {
    // map options
    var mapOptions = {
        zoom: 6,
        center: myLatLng,
        mapTypeControl: true,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };
    // initialise the global map variable
    map = new google.maps.Map(document.getElementById('map'), mapOptions);

proof of concept fiddle

代码段

var request;
var places;
var map;
var markers = [];
var myLatLng = {
  lat: 34,
  lng: 38
};

function initMap() {
  var mapOptions = {
    zoom: 6,
    center: myLatLng,
    mapTypeControl: true,
    mapTypeId: google.maps.MapTypeId.HYBRID
  };
  // initialise the map
  map = new google.maps.Map(document.getElementById('map'), mapOptions);
  // add markers
  for (var i = 0; i < places.length; i++) {
    // the place
    var place = places[i];
    // place co-ordinates
    var latlng = new google.maps.LatLng(place.latitude, place.longitude);
    var marker = new google.maps.Marker({
      position: latlng,
      map: map,
      title: place.city
    });
    var infowindow = new google.maps.InfoWindow();
    var content = place.city + "<br>" + latlng.toUrlValue(6);
    google.maps.event.addListener(marker, 'click', (function(marker, content) {
      return function() {
        infowindow.setContent(content);
        infowindow.open(map, marker);
      };
    })(marker, content));
    markers.push(marker);
  }
}

function toggleMarkers() {
  for (var i = 0; i < markers.length; i++) {
    if (markers[i].getMap() === null) {
      markers[i].setMap(map);
    } else {
      markers[i].setMap(null);
    }
  }
}
google.maps.event.addDomListener(window, "load", initMap);
// load database and parse into entries
// store all entires as in var "places"
var places = [{
  city: "Lebanon",
  latitude: 33.854721,
  longitude: 35.862285
}, {
  city: "Damascus, Syria",
  latitude: 33.5138073,
  longitude: 36.2765279
}, {
  city: "Amman, Jordan",
  latitude: 31.9565783,
  longitude: 35.9456951
}];
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="panel">
  <button onclick="toggleMarkers()">Toggle Markers</button>
</div>
<div id="map"></div>