简体   繁体   中英

Change position of leaflet label

I'd like to add labels to my leaflet-markers, and then position them above and horizontally centered for the marker icon.

With the labelAnchor option in the Leaflet.label plugin I can manually adjust every label so that I get what I want, and for now I've added a fixed width to my labels so that I know the text will be centered. But there must be a better way to achieve this?

http://jsfiddle.net/NYGvibeke/frUf4/3/

<style type="text/css">

  .labeltext { width: 120px; text-align: center; border:none; }

</style>

<script type="text/javascript">

    var myIcon = L.icon({
        iconUrl: 'http://icons.iconarchive.com/icons/visualpharm/icons8-metro-       style/512/Maps-and-Geolocation-Marker-icon.png',
        iconSize:     [18, 30], 
        iconAnchor:   [10, 30], 
        labelAnchor: [-80, -40]
    });

    var layer = new L.StamenTileLayer("toner-lite", {maxZoom: 10});
    var map = new L.Map("map", {
        center: new L.LatLng(30, 100),
        zoom: 4,
        maxZoom: 12,
        minZoom: 2
    });

    map.addLayer(layer);

    var marker1 = L.marker([25, 100], {icon: myIcon}).bindLabel('This is a label text', { noHide: true, className: 'labeltext'}).addTo(map);

</script>

Change

.labeltext { width: 120px}

to

.labeltext { width: auto}

The auto value will dynamically size the width of the label.

UPDATE

Actually, that's only part of it. Here's the rest in a jsfiddle . Basically, you need to dynamically assign the position based on the number of characters. It takes a little bit of calibration (depending on font typeface/size), but here's what I came up with for labelAnchor :

[-label[0].length*2.5-20, -40]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM