最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Google Maps close previous Infowindow when another marker is clicked - Stack Overflow

programmeradmin2浏览0评论

Consider the following locations:

 var locations =
        [{ "id": 1, "ReferenceNumber": "52525252525", "Address" : "School" , "Latitude": "21.585486", "Longitude": "50.258745" },
         { "id": 2, "ReferenceNumber": "6262626262", "Address" : "University", "Latitude": "21.54484411", "Longitude": "50.14846648" },
         { "id": 3, "ReferenceNumber": "424242424", "Address": "PUMPING STATION ", "Latitude": "21.9856341", "Longitude": "61.2587466" }];

With the below code, clicking multiple Markers will open multiple Infowindows. How can I prevent this to happen and make sure the previous Infowindow is closed before a new one is open?

$.each(locations, function(i, item) {

    var marker = new google.maps.Marker({
        'position': new google.maps.LatLng(item.Latitude, item.Longitude),
        'map': map,
        'title': item.Latitude + "," + item.Longitude
    });

    marker.setIcon('.png')

    var infowindow = new google.maps.InfoWindow({
        content: "<div class='infoDiv'><h3>Reference#: </h3> <h6>" + item.ReferenceNumber + "<h3>Location: </h3> <h6>" + item.Address + "</div></div>"
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
    });

    google.maps.event.addListener(map, "click", function(event) {
        infowindow.close();
        //autoCenter();
    });
})

Any help would be highly appreciated.

Consider the following locations:

 var locations =
        [{ "id": 1, "ReferenceNumber": "52525252525", "Address" : "School" , "Latitude": "21.585486", "Longitude": "50.258745" },
         { "id": 2, "ReferenceNumber": "6262626262", "Address" : "University", "Latitude": "21.54484411", "Longitude": "50.14846648" },
         { "id": 3, "ReferenceNumber": "424242424", "Address": "PUMPING STATION ", "Latitude": "21.9856341", "Longitude": "61.2587466" }];

With the below code, clicking multiple Markers will open multiple Infowindows. How can I prevent this to happen and make sure the previous Infowindow is closed before a new one is open?

$.each(locations, function(i, item) {

    var marker = new google.maps.Marker({
        'position': new google.maps.LatLng(item.Latitude, item.Longitude),
        'map': map,
        'title': item.Latitude + "," + item.Longitude
    });

    marker.setIcon('http://maps.google./mapfiles/ms/icons/red-dot.png')

    var infowindow = new google.maps.InfoWindow({
        content: "<div class='infoDiv'><h3>Reference#: </h3> <h6>" + item.ReferenceNumber + "<h3>Location: </h3> <h6>" + item.Address + "</div></div>"
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
    });

    google.maps.event.addListener(map, "click", function(event) {
        infowindow.close();
        //autoCenter();
    });
})

Any help would be highly appreciated.

Share Improve this question edited Jan 18, 2023 at 9:45 MrUpsidown 22.5k15 gold badges83 silver badges140 bronze badges asked Apr 21, 2017 at 14:02 MoeezMoeez 47811 gold badges60 silver badges170 bronze badges 3
  • When you ask a question, please provide a Minimal, Complete, and Verifiable example that allows others to reproduce the issue. – MrUpsidown Commented Apr 21, 2017 at 16:21
  • possible duplicate of Close all other InfoWindows when one is clicked – geocodezip Commented Apr 21, 2017 at 19:30
  • possible duplicate of close InfoWindow before open another – geocodezip Commented Apr 21, 2017 at 19:31
Add a ment  | 

1 Answer 1

Reset to default 10

Don't create multiple Infowindows if you only need one to be open at a time. You only need one instance of the Infowindow object and set its content depending on which Marker you click by using the setContent() method.

You also need to use a closure around your marker click listener. Something like that:

google.maps.event.addListener(marker, 'click', (function(marker) {

  return function() {

    // Something here
  }

})(marker));

More information here: Using Closures in Event Listeners

Working example below (with jQuery)

function initialize() {

  var mapOptions = {
    zoom: 5,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    center: new google.maps.LatLng(1, 1)
  };

  var locations = [
    [new google.maps.LatLng(0, 0), 'Marker 1', 'Infowindow content for Marker 1'],
    [new google.maps.LatLng(0, 1), 'Marker 2', 'Infowindow content for Marker 2'],
    [new google.maps.LatLng(0, 2), 'Marker 3', 'Infowindow content for Marker 3'],
    [new google.maps.LatLng(1, 0), 'Marker 4', 'Infowindow content for Marker 4'],
    [new google.maps.LatLng(1, 1), 'Marker 5', 'Infowindow content for Marker 5'],
    [new google.maps.LatLng(1, 2), 'Marker 6', 'Infowindow content for Marker 6']
  ];

  var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  var infowindow = new google.maps.InfoWindow();

  $.each(locations, function(i, item) {

    var marker = new google.maps.Marker({
      position: item[0],
      map: map,
      title: item[1],
    });

    google.maps.event.addListener(marker, 'click', (function(marker) {

      return function() {
        infowindow.setContent(item[2]);
        infowindow.open(map, marker);
      }

    })(marker));
  });

}

google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas {
  height: 150px;
}
<div id="map-canvas"></div>

<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis./maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

And here is the same solution in Vanilla Javascript (no jQuery)

function initialize() {

    var mapOptions = {
        zoom: 5,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: new google.maps.LatLng(1, 1)
    };

    var locations = [
        [new google.maps.LatLng(0, 0), 'Marker 1', 'Infowindow content for Marker 1'],
        [new google.maps.LatLng(0, 1), 'Marker 2', 'Infowindow content for Marker 2'],
        [new google.maps.LatLng(0, 2), 'Marker 3', 'Infowindow content for Marker 3'],
        [new google.maps.LatLng(1, 0), 'Marker 4', 'Infowindow content for Marker 4'],
        [new google.maps.LatLng(1, 1), 'Marker 5', 'Infowindow content for Marker 5'],
        [new google.maps.LatLng(1, 2), 'Marker 6', 'Infowindow content for Marker 6']
    ];

    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    var infowindow = new google.maps.InfoWindow();

    for (var i = 0; i < locations.length; i++) {

        var marker = new google.maps.Marker({
            position: locations[i][0],
            map: map,
            title: locations[i][1]
        });

        google.maps.event.addListener(marker, 'click', (function (marker, i) {

            return function () {
                infowindow.setContent(locations[i][2]);
                infowindow.open(map, marker);
            }

        })(marker, i));
    }
}

initialize();
#map-canvas {
  height: 150px;
}
<div id="map-canvas"></div>

<script src="https://maps.googleapis./maps/api/js?libraries=places&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>

发布评论

评论列表(0)

  1. 暂无评论