npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

leaflet-polylabel

v2.0.2

Published

A JavaScript leaflet library for finding optimal label positions inside polygons.

Downloads

7

Readme

Leaflet Polylabel Plugin

A plugin by syonfox, with thanks to everyone behind Polylabel and Leaflet, and many more.

MIT / WTFPL

GitHub Repo Example Npm

Todo

  • Clean up and document more

Installation

npm install leaflet-polylabel
cp node_modules/endpoint-polylabel/dist/L.polylabel.js src/lib/L.polylabel.js

Include

<script src="/lib/L.polylabel.js"></script>
<div id="map"></div>

Usage

let map = L.map("#map");

// Function to fetch and label GeoJSON data
async function labelGeoJson(url) {
    let res = await fetch(url);
    let data = await res.json();

    window.ll = L.polylabel(data, {
        pointToLayer: (gj, ll) => L.circleMarker(ll, {
            radius: gj.properties.population ? Math.pow(gj.properties[order], 0.2) - 1 : 1
        }),
        labelProp: 'NAME',
        labelFunc: l => (`${l.feature.properties[field]} (${formatNumber(l.feature.properties[order])})`),
        labelPos: 'cc',
        labelStyle: { textTransform: 'uppercase', fontWeight: 'bold' },
        style: (f, l) => {
            return {
                color: "#000",
                weight: 2,
                fillColor: "#fff"
            };
        },
        priorityProp: order,
        stretchRatio: 1.5
    }).addTo(map).bindPopup(l => generateCountryCard(l.feature.properties));
}

// Call the function with your GeoJSON URL
labelGeoJson("https://ne.freemap.online/110m/physical/ne_110m_lakes.json");

Options

L.polylabel(data, options)

The L.polylabel function extends Leaflet's labeling capabilities using the Polylabel algorithm. It adds labels to your GeoJSON data with enhanced placement and styling options.

Options

  • pointToLayer: Function to convert GeoJSON point feature to a leaflet layer.
  • labelProp: Property name in GeoJSON features to use as the label text.
  • labelFunc: Function to format the label text.
  • labelPos: Position of the label. Default is 'cc' (center-center).
  • labelStyle: CSS style for the label text.
  • style: Function to style the feature layers.
  • priorityProp: Property name to determine the rendering priority of labels.
  • stretchRatio: Ratio to stretch the label for better fit. Default is 1.5.

Example

L.polylabel(data, {
    pointToLayer: (gj, ll) => L.circleMarker(ll, {
        radius: gj.properties.population ? Math.pow(gj.properties[order], 0.2) - 1 : 1
    }),
    labelProp: 'NAME',
    labelFunc: l => (`${l.feature.properties[field]} (${formatNumber(l.feature.properties[order])})`),
    labelPos: 'cc',
    labelStyle: { textTransform: 'uppercase', fontWeight: 'bold' },
    style: (f, l) => ({
        color: "#000",
        weight: 2,
        fillColor: "#fff"
    }),
    priorityProp: order,
    stretchRatio: 1.5
}).addTo(map).bindPopup(l => generateCountryCard(l.feature.properties));

This plugin enhances Leaflet's labeling capabilities by leveraging the Polylabel algorithm to ensure optimal label placement within complex polygons. The added stretchRatio option allows for better control over label stretching to fit within larger polygons.

Other work

https://plnkr.co/edit/grF2TZdRS6P9YqW9?preview https://observablehq.com/@kotelnikov/labeling-with-stretched-polylabel-updated https://ica-adv.copernicus.org/articles/4/8/2023/ica-adv-4-8-2023.pdf

polylabel Build Status

A fast algorithm for finding polygon pole of inaccessibility, the most distant internal point from the polygon outline (not to be confused with centroid), implemented as a JavaScript library. Useful for optimal placement of a text label on a polygon.

It's an iterative grid algorithm, inspired by paper by Garcia-Castellanos & Lombardo, 2007. Unlike the one in the paper, this algorithm:

  • guarantees finding global optimum within the given precision
  • is many times faster (10-40x)

How the algorithm works

This is an iterative grid-based algorithm, which starts by covering the polygon with big square cells and then iteratively splitting them in the order of the most promising ones, while aggressively pruning uninteresting cells.

  1. Generate initial square cells that fully cover the polygon (with cell size equal to either width or height, whichever is lower). Calculate distance from the center of each cell to the outer polygon, using negative value if the point is outside the polygon (detected by ray-casting).
  2. Put the cells into a priority queue sorted by the maximum potential distance from a point inside a cell, defined as a sum of the distance from the center and the cell radius (equal to cell_size * sqrt(2) / 2).
  3. Calculate the distance from the centroid of the polygon and pick it as the first "best so far".
  4. Pull out cells from the priority queue one by one. If a cell's distance is better than the current best, save it as such. Then, if the cell potentially contains a better solution that the current best (cell_max - best_dist > precision), split it into 4 children cells and put them in the queue.
  5. Stop the algorithm when we have exhausted the queue and return the best cell's center as the pole of inaccessibility. It will be guaranteed to be a global optimum within the given precision.

image

JavaScript Usage

Given polygon coordinates in GeoJSON-like format and precision (1.0 by default), Polylabel returns the pole of inaccessibility coordinate in [x, y] format.

var p = polylabel(polygon, 1.0);

TypeScript

TypeScript type definitions are available via npm install --save @types/polylabel.

C++ Usage

It is recommended to install polylabel via mason. You will also need to install its dependencies: geometry.hpp and variant.

#include <mapbox/polylabel.hpp>

int main() {
    mapbox::geometry::polygon<double> polygon = readPolygon(); // Get polygon data from somewhere.
    mapbox::geometry::point<double> p = mapbox::polylabel(polygon, 1.0);
    return 0;
}

Ports to other languages