Skip to content

Instantly share code, notes, and snippets.

@eXponenta
Last active October 11, 2024 16:02
Show Gist options
  • Save eXponenta/abda14e7c03f76c906a8f5f230061b1a to your computer and use it in GitHub Desktop.
Save eXponenta/abda14e7c03f76c906a8f5f230061b1a to your computer and use it in GitHub Desktop.
const TextPath = L.CircleMarker.extend({
options: {
text: "",
size: 10,
font: "serif",
weight: 1,
},
initialize(...args) {
L.CircleMarker.prototype.initialize.call( this, ...args );
this._radius = this.options.size;
this._actualSize = false;
},
_updateSize() {
if ( this._actualSize || !this._renderer || !this.options.text) {
return;
}
const ctx = this._renderer._ctx;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = (this.options.size || 0) + "px " + this.options.font;
const size = ctx.measureText( this.options.text );
this._radius = size.width;
this._actualSize = true;
},
_project() {
this._point = this._map.latLngToLayerPoint(this._latlng);
this._updateSize();
this._updateBounds();
},
_updatePath() {
this._updateSize();
this._updateText();
},
_updateText() {
const renderer = this._renderer;
if (!renderer._drawing || this._empty()) { return; }
const p = this._point;
/**
* @type { CanvasRenderingContext2D }
*/
const ctx = renderer._ctx;
const r = Math.max(Math.round(this._radius), 1);
const s = (Math.max(Math.round(this._radiusY), 1) || r) / r;
const text = this.options.text;
if ( text ) {
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = (this.options.size || 0) + "px " + this.options.font;
ctx.fillStyle = this.options.fillColor || this.options.color;
ctx.fillText( text, p.x, p.y / s );
}
if (s !== 1 ) {
ctx.save();
ctx.scale(1, s);
}
ctx.beginPath();
ctx.rect(
p.x - 1.2 * this._radius / 2,
p.y - 1.2 * this.options.size / 2,
1.2 * this._radius,
1.2 * this.options.size
);
if (s !== 1 ) {
ctx.restore();
}
renderer._fillStroke(ctx, this);
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment