2 * L.PolylineUtil contains utilify functions for polylines, two methods
3 * are added to the L.Polyline object to support creation of polylines
4 * from an encoded string and converting existing polylines to an
7 * - L.Polyline.fromEncoded(encoded [, options]) returns a L.Polyline
8 * - L.Polyline.encodePath() returns a string
11 * http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/\
14 /*jshint browser:true, debug: true, strict:false, globalstrict:false, indent:4, white:true, smarttabs:true*/
15 /*global L:true, console:true*/
18 // Inject functionality into Leaflet
20 if (!(L.Polyline.prototype.fromEncoded)) {
21 L.Polyline.fromEncoded = function (encoded, options) {
22 return new L.Polyline(L.PolylineUtil.decode(encoded), options);
25 if (!(L.Polygon.prototype.fromEncoded)) {
26 L.Polygon.fromEncoded = function (encoded, options) {
27 return new L.Polygon(L.PolylineUtil.decode(encoded), options);
32 encodePath: function () {
33 return L.PolylineUtil.encode(this.getLatLngs());
37 if (!L.Polyline.prototype.encodePath) {
38 L.Polyline.include(encodeMixin);
40 if (!L.Polygon.prototype.encodePath) {
41 L.Polygon.include(encodeMixin);
48 L.PolylineUtil.encode = function (latlngs) {
52 var encoded_points = "";
54 for (i = 0; i < latlngs.length; i++) {
55 var lat = latlngs[i].lat;
56 var lng = latlngs[i].lng;
57 var late5 = Math.floor(lat * 1e5);
58 var lnge5 = Math.floor(lng * 1e5);
64 L.PolylineUtil.encodeSignedNumber(dlat) +
65 L.PolylineUtil.encodeSignedNumber(dlng);
67 return encoded_points;
70 // This function is very similar to Google's, but I added
71 // some stuff to deal with the double slash issue.
72 L.PolylineUtil.encodeNumber = function (num) {
73 var encodeString = "";
74 var nextValue, finalValue;
76 nextValue = (0x20 | (num & 0x1f)) + 63;
77 encodeString += (String.fromCharCode(nextValue));
80 finalValue = num + 63;
81 encodeString += (String.fromCharCode(finalValue));
85 // This one is Google's verbatim.
86 L.PolylineUtil.encodeSignedNumber = function (num) {
87 var sgn_num = num << 1;
91 return (L.PolylineUtil.encodeNumber(sgn_num));
94 L.PolylineUtil.decode = function (encoded) {
95 var len = encoded.length;
101 while (index < len) {
106 b = encoded.charCodeAt(index++) - 63;
107 result |= (b & 0x1f) << shift;
110 var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
116 b = encoded.charCodeAt(index++) - 63;
117 result |= (b & 0x1f) << shift;
120 var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
123 latlngs.push(new L.LatLng(lat * 1e-5, lng * 1e-5));