Mouse over popup on leaflet.js marker

10,904

Solution 1

Attaching a popup to a marker is fairly easy. It is done by calling the bindPopup method of your L.Marker instance. Per default a popup opens on the click event of the L.Marker instance and closes on the click event of your L.Map instance. Now if you want to do something when a popup opens you can listen to the popupopen event of your L.Map instance.

When you want fetch external data in the background on the popupopen event that is usually done via XHR/AJAX. You can write your own logic or use something like jQuery's XHR/AJAX methods like $.getJSON. Once you receive response data you can then update your popup's content.

In code with comments to explain further:

// A new marker 
var marker = new L.Marker([40.7127, -74.0059]).addTo(map);

// Bind popup with content
marker.bindPopup('No data yet, please wait...');

// Listen for the popupopen event on the map
map.on('popupopen', function(event){
  // Grab the latitude and longitude from the popup
  var ll = event.popup.getLatLng();
  // Create url to use for getting the data
  var url = 'http://api.openweathermap.org/data/2.5/weather?lat='+ll.lat+'&lon='+ll.lng;
  // Fetch the data with the created url
  $.getJSON(url, function(response){
    // Use response data to update the popup's content
    event.popup.setContent('Temperature: ' + response.main.temp);
  });
});

// Listen for the popupclose event on the map
map.on('popupclose', function(event){
  // Restore previous content
  event.popup.setContent('No data yet, please wait...');
});

Here's a working example on Plunker: http://plnkr.co/edit/oq7RO5?p=preview

After comments:

If you want to open the popup on hover instead of click you can add this:

marker.on('mouseover', function(event){
  marker.openPopup();
});

If you want to close the popup when you stop hovering instead of map click add this:

marker.on('mouseout', function(event){
  marker.closePopup();
});

Here's an updated example: http://plnkr.co/edit/wlPV4F?p=preview

Solution 2

I got fed up with fighting with leaflet's built in functionality. The first thing I did was use the alt option to assign a key to the marker:

var myLocation = myMap.addLayer(L.marker(lat,lng],{icon: icon,alt: myKey}))

The next thing was assign an id using this alt and a title via jQuery (why you can't do that by default irritates me):

$('img[alt='+myKey+']').attr('id','marker_'+myKey).attr('title',sRolloverContent)

Then, I used jQuery tooltip (html will only render this way):

$('#marker_'+myKey).tooltip({
    content: sRolloverContent
})

Also, by using the jQuery tooltip instead of the click-only bindPopup, I am able to fire the tooltip from my list, where the row has a matching key id:

$('.search-result-list').live('mouseover',function(){
    $('#marker_'+$(this).attr('id')).tooltip('open')
})

$('.search-result-list').live('mouseout',function(){
    $('#marker_'+$(this).attr('id')).tooltip('close')
})

By adding the id, I can easily use jQuery to do whatever I want, like highlight a list of locations when the marker is hovered:

$('#marker_'+iFireRescue_id).on('mouseover',function(){
    ('tr#'+getIndex($(this).attr('id'))).removeClass('alt').removeClass('alt-not').addClass('highlight')
})

$('#marker_'+myKey).on('mouseout',function(){
    $('tr#'+getIndex($(this).attr('id'))).removeClass('highlight')
    $('#search-results-table tbody tr:odd').addClass('alt')
    $('#search-results-table tbody tr:even').addClass('alt-not')
})
Share:
10,904
user3349850
Author by

user3349850

javascript enthusiastic....

Updated on July 13, 2022

Comments

  • user3349850
    user3349850 almost 2 years

    How can I add a mouse over pop up on leaflet.js marker . the pop up data will be dynamic.

    I have a service which returns a lat & lon positions which will mark on a map.

    I would require a popup on mouse over a marker . the event should send the lat and long position for ex to : http://api.openweathermap.org/data/2.5/weather?lat=40&lon=-100 the data from service should be in popup content. I have tried but cant build the pop up content dynamically each marker

    Please do the needful.

    below is the code i have used for markers statesdata is array which stores the lat and longitude values

    for ( var i=0; i < totalLength1; i++ ) {
                             var LamMarker = new L.marker([statesData1[i].KK, statesData1[i].LL]).on('contextmenu',function(e) {
                                 onClick(this, i);                  
                            }).on('click',function(e) {
                            onClick1(this, i)                   
                            });
                            marker_a1.push(LamMarker);
                            map.addLayer(marker_a1[i]);
    

    on click we call click1 function on context of marker we call click function

    How can i add a pop on mouse over passing lat and long from the above code?

  • user3349850
    user3349850 over 8 years
    Thanks a ton for your reply. small change is i am expecting is the popup on mouse over event rather than the click event on marker . because i was using click event for other purpose.Please do the needful
  • iH8
    iH8 over 8 years
    No thanks, you're always welcome. You could however consider to mark the answer as accepted so that other users with a similar problem can find a tested/working solution too. See: stackoverflow.com/help/someone-answers About the mouseover, i've edited my question and added a solution for it. Good luck!