Search code examples
javascripttimerleafletpopup

How to autoclose a Leaflet popup with timer when mouse move out marker


It's possible to set an autoclose timer for a popup on a marker in leaflet.

var marker1 = L.marker([46.26734, 12.328876], {icon: myIcon4}).on('mouseover', function(e){var popup = L.popup().setLatLng(e.latlng).setContent('Luoghi, Cose, Strade<br>Diga del Vajont').openOn(mappa_percorsi);}).on('click', function(e){var popup = L.popup().setLatLng(e.latlng).setContent('<a class="image-popup-no-margins hover-title" href="https://atorinfriul.it/html/gpx/Luoghi_Cose_Strade__Diga_Vajont_NOT_MINIMIZED.php"     Target="_blank" title="Diga del Vajont">   <img loading="lazy"  src="https://atorinfriul.it/html/images/luoghi_cose_strade/Fumetto-diga-del-vajont.jpg" style="width:150px;" alt="Responsive image"></a> <div class="hover-image"><img loading="lazy"  src="https://atorinfriul.it/html/images/luoghi_cose_strade/Fumetto-diga-del-vajont.jpg" alt="Responsive image"></div>').openOn(mappa_percorsi);}).addTo(LuoghiCoseStrade);

In this example, overing marker, open a popup with this message "Luoghi, Cose, Strade - Diga del Vajont".
Clicking on marker, a new popup is show, with an image inside it, and overing image, open a modal of image zoomed up and clicking open image on a new tab.

Problem is, that if an user over the marker (opening popup) then move on rest of map, popup stay on until a new marker is overed or a click on the map is done.

That's why I want to add a timer.

I have tried severals solutions without benefits
Putting this code, I obtain to close popup, but loose possibility, after clicking to navigate in secondary popup (that one with image).

marker1.on('mouseout', function (e) {mappa_percorsi.closePopup();});

I tryed to use this, but get an error (my js and leaflet knowledge is too limited to solve)

setTimeout(function() { popup.close();}, 5000);

Any suggestion is wellcome.

Thanks

Following is a almost working example to try to explain better thanks

       var marker = L.marker([46.26734, 12.328876], {icon: myIcon2}).on('mouseover', function(e){var popup = L.popup().setLatLng(e.latlng).setContent('Luoghi, Cose, Strade<br>Diga del Vajont').openOn(mymap);}).on('click', function(e){var popup = L.popup().setLatLng(e.latlng).setContent('<a class="image-popup-no-margins hover-title" href="https://atorinfriul.it/html/gpx/Luoghi_Cose_Strade__Diga_Vajont_NOT_MINIMIZED.php"     Target="_blank" title="Diga del Vajont">   <img loading="lazy"  src="https://atorinfriul.it/html/images/luoghi_cose_strade/Fumetto-diga-del-vajont.jpg" style="width:150px;" alt="Responsive image"></a> <div class="hover-image"><img loading="lazy"  src="https://atorinfriul.it/html/images/luoghi_cose_strade/Fumetto-diga-del-vajont.jpg" alt="Responsive image"></div>').openOn(mymap);}).addTo(mymap);
<!DOCTYPE html>
<html lang="it">
<head>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">

  <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" integrity="sha512-hoalWLoI8r4UszCkZ5kL8vayOGVae1oxXe/2A4AO6J9+580uKHDO3JdHb7NzwwzK5xr/Fs0W40kiNHxM9vyTtQ==" crossorigin="" />
  <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha512-BB3hKbKWOc9Ez/TAwyWxNXeoV9c1v6FIeYiBieIWkpLjauysF18NzgR1MBNBXf8/KABdlkX68nAhlwcDFLGPCQ==" crossorigin=""></script>

  <style >

    .mappa_global{max-width: 1350px;
      width: 100%;
      min-height: 85vh;
      height: 100%;
      border-radius: 25px;
      padding-left: 2%;
      padding-right: 2%;
      margin: 0px auto;
      position: relative;
      z-index: 1;}



  </style>

</head>
<!-- indispensabile onload per caricare lo script dei video nella hero -->
<body  class="my_width">


<div>
<div class="p25_bis">
  <div id="map_canvas" class="mappa_global" class="lazyload" ></div>
</div>
<script>


var mbAttr = 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>';
var mbUrl = 'https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw';

var Streets = L.tileLayer(mbUrl, {id: 'mapbox/streets-v11', tileSize: 512, zoomOffset: -1, attribution: mbAttr});

var Osm = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 19,
attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
});

var Esri_NatGeoWorldMap = L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}', {
attribution: 'Tiles &copy; Esri &mdash; National Geographic, Esri, DeLorme, NAVTEQ, UNEP-WCMC, USGS, NASA, ESA, METI, NRCAN, GEBCO, NOAA, iPC',
maxZoom: 16
});

var OpenTopoMap = L.tileLayer('https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png', {
maxZoom: 17,
attribution: 'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, <a href="http://viewfinderpanoramas.org">SRTM</a> | Map style: &copy; <a href="https://opentopomap.org">OpenTopoMap</a> (<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)'
});

var Stamen_Toner = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}{r}.{ext}', {
attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
subdomains: 'abcd',
minZoom: 0,
maxZoom: 20,
ext: 'png'
});

var mymap = L.map('map_canvas', {
center: [46.26734, 12.328876],
zoom: 9,
layers: [Stamen_Toner]
});

var baseLayers = {
'Toner': Stamen_Toner,
'OpenTopoMap': OpenTopoMap,
'OpenStreetMap': Osm,
'Streets': Streets,
'National Geographic': Esri_NatGeoWorldMap
};

var layerControl = L.control.layers(baseLayers).addTo(mymap);

  var myIcon2 = L.icon({
    iconUrl: 'https://unpkg.com/[email protected]/dist/images/marker-icon.png',
      iconSize: [40, 40], // size of the icon
      });


      // arrivo Percorso


</script>


</div>





<!-- jQuery 1.7.2+ or Zepto.js 1.0+ -->
<script src="https://atorinfriul.netsons.org/html/js/jquery.min.js"></script>

<!-- Magnific Popup core JS file -->



</body>
</html>


Solution

  • You almost did it. If I get you right you want to close only the mouseover popup when leaving the layer. you can define a variable to check which popup is opened and then write a function to close it on mouse leave.

    var whichPopup = 0;
    var marker = L.marker([46.26734, 12.328876], {icon: myIcon2}).on('mouseover', function(e){popup = L.popup().setLatLng(e.latlng).setContent('Luoghi, Cose, Strade<br>Diga del Vajont').openOn(mymap);whichPopup = 1;}).on('click', function(e){var popup2 = L.popup().setLatLng(e.latlng).setContent('<a class="image-popup-no-margins hover-title" href="https://atorinfriul.it/html/gpx/Luoghi_Cose_Strade__Diga_Vajont_NOT_MINIMIZED.php"     Target="_blank" title="Diga del Vajont">   <img loading="lazy"  src="https://atorinfriul.it/html/images/luoghi_cose_strade/Fumetto-diga-del-vajont.jpg" style="width:150px;" alt="Responsive image"></a> <div class="hover-image"><img loading="lazy"  src="https://atorinfriul.it/html/images/luoghi_cose_strade/Fumetto-diga-del-vajont.jpg" alt="Responsive image"></div>').openOn(mymap);whichPopup = 0}).addTo(mymap);
    
    marker.on('mouseout', function (e) {
        if (whichPopup == 1){
            setTimeout(function() { mymap.closePopup();}, 5000);
        }
    });