Leaflet Custom Control position: center

2019-06-27 04:12发布

问题:

we are hooking up an eye-tracker to control the leaflet map (pan, zoom etc.) We would like to have a custom control that appears at the center of the map (for menu functions) Currently Leaflet does not support position: 'center') (topleft, etc. is supported) ideas?

回答1:

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%;
}


回答2:

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%);
}


标签: leaflet