Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

leaflet Js custom control button add (text, hover)

I followed this control-button-leaflet tutorial and it worked for me. Now I want to:

  1. show some text when i hover over the button (like with the zoom buttons)
  2. Change the color of the button when i hover over it
  3. be able to write text inside the button instead of an image.

Here's the code:

    var customControl =  L.Control.extend({        
      options: {
        position: 'topleft'
      },

      onAdd: function (map) {
        var container = L.DomUtil.create('div', 'leaflet-bar leaflet-control leaflet-control-custom');

        container.style.backgroundColor = 'white';     
        container.style.backgroundImage = "url(http://t1.gstatic.com/images?q=tbn:ANd9GcR6FCUMW5bPn8C4PbKak2BJQQsmC-K9-mbYBeFZm1ZM2w2GRy40Ew)";
        container.style.backgroundSize = "30px 30px";
        container.style.width = '30px';
        container.style.height = '30px';

        container.onclick = function(){
          console.log('buttonClicked');
        }

        return container;
      }
    });

    var map;

    var readyState = function(e){
      map = new L.Map('map').setView([48.935, 18.14], 14);
      L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
      map.addControl(new customControl());
    }

    window.addEventListener('DOMContentLoaded', readyState);
like image 854
Jeremy Hunts Avatar asked Aug 10 '15 16:08

Jeremy Hunts


1 Answers

It seems you more need a Button than a div:

    var container = L.DomUtil.create('input');
    container.type="button";
  1. Then you can easily set a mouseover text:

    container.title="No cat";
    
  2. And some Text instead of an image:

    container.value = "42";
    
  3. And you can use the mouse events to style the button:

    container.onmouseover = function(){
      container.style.backgroundColor = 'pink'; 
    }
    container.onmouseout = function(){
      container.style.backgroundColor = 'white'; 
    }
    

(you could of course do this last part with css, might be more elegant)

Full example: http://codepen.io/anon/pen/oXVMvy

like image 125
Krxldfx Avatar answered Sep 19 '22 07:09

Krxldfx