Leaflet Custom Control position: center

Adding a custom control on a map on leaflet is performed like that .

For instance for a logo :

var logo= L.control({
    position : 'topleft'
});
logo.onAdd = function(map) {
    this._div = L.DomUtil.create('div', 'myControl');
    var img_log = "<div class="myClass"><img src=\"images/logo.png\"></img></div>";

    this._div.innerHTML = img_log;
    return this._div;

}
logo.addTo(map);

Then, you can add CSS style to myClass to center it: (this part has not been tested by myself)

.myClass {
   padding-top:50%;
   padding-left: 50%;
}

You can simply override the .leaflet-left class to this, and your control will be centered horizontally.

.leaflet-left {
    left: 50%;
    transform: translate(-50%, 0%);
}

And to center vertically, just override the class .leaflet-top to this:

.leaflet-top {
    top: 50%;
    transform: translate(0%, -50%);
}

NOTE: These changes will affect other controls on the map such as zoom controls.

EDIT:

If you want to add the functionality to leaflet so that the other controls arent affected, you can do this:

leaflet.js: Beginning at line 4900 I believe?

t("top", "left"),
t("top", "right"),
t("bottom", "left"),
t("bottom", "right"),

Add these two lines:

t("top", "center"),
t("bottom", "center")

This would allow for use of positions 'topcenter' and 'bottomcenter'

Then simply add css class for 'leaflet-center':

.leaflet-center {
    left: 50%;
    transform: translate(-50%, 0%);
}

I get this is an old topic, but anyhow, here is my workaround.

Add some css :

.leaflet-center {
    left: 50%;
    transform: translate(-50%, 0%);
}

.leaflet-middle {
    top: 50%;
    position: absolute;
    z-index: 1000;
    pointer-events: none;
  transform: translate(0%, -50%);

}

.leaflet-center.leaflet-middle {
  transform: translate(-50%, -50%);
}

and patch a the position method.

L.Map.include({
  _initControlPos: function () {
    var corners = this._controlCorners = {},
      l = 'leaflet-',
      container = this._controlContainer =
        L.DomUtil.create('div', l + 'control-container', this._container);

    function createCorner(vSide, hSide) {
      var className = l + vSide + ' ' + l + hSide;

      corners[vSide + hSide] = L.DomUtil.create('div', className, container);
    }

    createCorner('top', 'left');
    createCorner('top', 'right');
    createCorner('bottom', 'left');
    createCorner('bottom', 'right');

    createCorner('top', 'center');
    createCorner('middle', 'center');
    createCorner('middle', 'left');
    createCorner('middle', 'right');
    createCorner('bottom', 'center');
  }
});

Now you have 5 new positions to use.

Tags:

Leaflet