Leaflet Text Path
HTML
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.css">
<script src="http://cdn.leafletjs.com/leaflet-0.6.4/leaflet.js"></script>
<div id="map"></div>
CSS
#map{
width: 100%;
height: 400px
}
JavaScript
/*
* Inspired by Tom Mac Wright article :
* http://mapbox.com/osmdev/2012/11/20/getting-serious-about-svg/
*/
var PolylineTextPath = {
__updatePath: L.Polyline.prototype._updatePath,
__bringToFront: L.Polyline.prototype.bringToFront,
__onAdd: L.Polyline.prototype.onAdd,
__onRemove: L.Polyline.prototype.onRemove,
onAdd: function (map) {
this.__onAdd.call(this, map);
this._textRedraw();
},
onRemove: function (map) {
map = map || this._map;
if (map && this._textNode)
map._pathRoot.removeChild(this._textNode);
this.__onRemove.call(this, map);
},
bringToFront: function () {
this.__bringToFront.call(this);
this._textRedraw();
},
_updatePath: function () {
this.__updatePath.call(this);
this._textRedraw();
},
_textRedraw: function () {
var text = this._text,
options = this._textOptions;
if (text) {
this.setText(null).setText(text, options);
}
},
setText: function (text, options) {
this._text = text;
this._textOptions = options;
var defaults = {repeat: false, fillColor: 'black', attributes: {}};
options = L.Util.extend(defaults, options);
/* If empty text, hide */
if (!text) {
if (this._textNode)
this._map._pathRoot.removeChild(this._textNode);
return this;
}
text = text.replace(/ /g, '\u00A0'); // Non breakable spaces
var id = 'pathdef-' + L.Util.stamp(this);
var svg = this._map._pathRoot;
this._path.setAttribute('id', id);
if (options.repeat) {
/* Compute single pattern length */
var pattern = L.Path.prototype._createElement('text');
for (var attr in options.attributes)
pattern.setAttribute(attr, options.attributes[attr]);
...