Debian Codegraph @

dist/leaflet.geometryutil.js

raw symbols SCIP
1 // Packaging/modules magic dance.
2 (function (factory) {
3 var L;
4 if (typeof define === 'function' && define.amd) {
5 // AMD
6 define(['leaflet'], factory);
7 } else if (typeof module !== 'undefined') {
8 // Node/CommonJS
9 L = require('leaflet');
10 module.exports = factory(L);
11 } else {
12 // Browser globals
13 if (typeof window.L === 'undefined')
14 throw 'Leaflet must be loaded first';
15 factory(window.L);
16 }
17 }(function (L) {
18 "use strict";
19
20 /**
21 * @fileOverview Leaflet Geometry utilities for distances and linear referencing.
22 * @name L.GeometryUtil
23 */
24
25 L.GeometryUtil = L.extend(L.GeometryUtil || {}, {
26
27 /**
28 Shortcut function for planar distance between two {L.LatLng} at current zoom.
29 @param {L.Map} map
30 @param {L.LatLng} latlngA
31 @param {L.LatLng} latlngB
32 @returns {Number} in pixels
33 */
34 distance: function (map, latlngA, latlngB) {
35 return map.latLngToLayerPoint(latlngA).distanceTo(map.latLngToLayerPoint(latlngB));
36 },
37
38 /**
39 Shortcut function for planar distance between a {L.LatLng} and a segment (A-B).
40 @param {L.Map} map
41 @param {L.LatLng} latlng
42 @param {L.LatLng} latlngA
43 @param {L.LatLng} latlngB
44 @returns {Number} in pixels
45 */
46 distanceSegment: function (map, latlng, latlngA, latlngB) {
47 var p = map.latLngToLayerPoint(latlng),
48 p1 = map.latLngToLayerPoint(latlngA),
49 p2 = map.latLngToLayerPoint(latlngB);
50 return L.LineUtil.pointToSegmentDistance(p, p1, p2);
51 },
52
53 /**
54 Shortcut function for converting distance to readable distance.
55 @param {Number} distance
56 @param {String} unit ('metric' or 'imperial')
57 @returns {Number} in yard or miles
58 */
59 readableDistance: function (distance, unit) {
60 var isMetric = (unit !== 'imperial'),
61 distanceStr;
62 if (isMetric) {
63 // show metres when distance is < 1km, then show km
64 if (distance > 1000) {
65 distanceStr = (distance / 1000).toFixed(2) + ' km';
66 }
67 else {
68 distanceStr = Math.ceil(distance) + ' m';
69 }
70 }
71 else {
72 distance *= 1.09361;
73 if (distance > 1760) {
74 distanceStr = (distance / 1760).toFixed(2) + ' miles';
75 }
76 else {
77 distanceStr = Math.ceil(distance) + ' yd';
78 }
79 }
80 return distanceStr;
81 },
82
83 /**
84 Returns true if the latlng belongs to segment.
85 param {L.LatLng} latlng
86 @param {L.LatLng} latlngA
87 @param {L.LatLng} latlngB
88 @param {?Number} [tolerance=0.2]
89 @returns {boolean}
90 */
91 belongsSegment: function(latlng, latlngA, latlngB, tolerance) {
92 tolerance = tolerance === undefined ? 0.2 : tolerance;
93 var hypotenuse = latlngA.distanceTo(latlngB),
94 delta = latlngA.distanceTo(latlng) + latlng.distanceTo(latlngB) - hypotenuse;
95 return delta/hypotenuse < tolerance;
96 },
97
98 /**
99 * Returns total length of line
100 * @param {L.Polyline|Array<L.Point>|Array<L.LatLng>}
101 * @returns {Number} in meters
102 */
103 length: function (coords) {
104 var accumulated = L.GeometryUtil.accumulatedLengths(coords);
105 return accumulated.length > 0 ? accumulated[accumulated.length-1] : 0;
106 },
107
108 /**
109 * Returns a list of accumulated length along a line.
110 * @param {L.Polyline|Array<L.Point>|Array<L.LatLng>}
111 * @returns {Number} in meters
112 */
113 accumulatedLengths: function (coords) {
114 if (typeof coords.getLatLngs == 'function') {
115 coords = coords.getLatLngs();
116 }
117 if (coords.length === 0)
118 return [];
119 var total = 0,
120 lengths = [0];
121 for (var i = 0, n = coords.length - 1; i< n; i++) {
122 total += coords[i].distanceTo(coords[i+1]);
123 lengths.push(total);
124 }
125 return lengths;
126 },
127
128 /**
129 Returns the closest point of a {L.LatLng} on the segment (A-B)
130 @param {L.Map} map
131 @param {L.LatLng} latlng
132 @param {L.LatLng} latlngA
133 @param {L.LatLng} latlngB
134 @returns {L.LatLng}
135 */
136 closestOnSegment: function (map, latlng, latlngA, latlngB) {
137 var maxzoom = map.getMaxZoom();
138 if (maxzoom === Infinity)
139 maxzoom = map.getZoom();
140 var p = map.project(latlng, maxzoom),
141 p1 = map.project(latlngA, maxzoom),
142 p2 = map.project(latlngB, maxzoom),
143 closest = L.LineUtil.closestPointOnSegment(p, p1, p2);
144 return map.unproject(closest, maxzoom);
145 },
146
147 /**
148 Returns the closest latlng on layer.
149 @param {L.Map} map
150 @param {Array<L.LatLng>|L.PolyLine} layer - Layer that contains the result.
151 @param {L.LatLng} latlng
152 @param {?boolean} [vertices=false] - Whether to restrict to path vertices.
153 @returns {L.LatLng}
154 */
155 closest: function (map, layer, latlng, vertices) {
156 if (typeof layer.getLatLngs != 'function')
157 layer = L.polyline(layer);
158
159 var latlngs = layer.getLatLngs().slice(0),
160 mindist = Infinity,
161 result = null,
162 i, n, distance;
163
164 // Lookup vertices
165 if (vertices) {
166 for(i = 0, n = latlngs.length; i < n; i++) {
167 var ll = latlngs[i];
168 distance = L.GeometryUtil.distance(map, latlng, ll);
169 if (distance < mindist) {
170 mindist = distance;
171 result = ll;
172 result.distance = distance;
173 }
174 }
175 return result;
176 }
177
178 if (layer instanceof L.Polygon) {
179 latlngs.push(latlngs[0]);
180 }
181
182 // Keep the closest point of all segments
183 for (i = 0, n = latlngs.length; i < n-1; i++) {
184 var latlngA = latlngs[i],
185 latlngB = latlngs[i+1];
186 distance = L.GeometryUtil.distanceSegment(map, latlng, latlngA, latlngB);
187 if (distance <= mindist) {
188 mindist = distance;
189 result = L.GeometryUtil.closestOnSegment(map, latlng, latlngA, latlngB);
190 result.distance = distance;
191 }
192 }
193 return result;
194 },
195
196 /**
197 Returns the closest layer to latlng among a list of layers.
198 @param {L.Map} map
199 @param {Array<L.ILayer>} layers
200 @param {L.LatLng} latlng
201 @returns {object} with layer, latlng and distance or {null} if list is empty;
202 */
203 closestLayer: function (map, layers, latlng) {
204 var mindist = Infinity,
205 result = null,
206 ll = null,
207 distance = Infinity;
208
209 for (var i = 0, n = layers.length; i < n; i++) {
210 var layer = layers[i];
211 // Single dimension, snap on points, else snap on closest
212 if (typeof layer.getLatLng == 'function') {
213 ll = layer.getLatLng();
214 distance = L.GeometryUtil.distance(map, latlng, ll);
215 }
216 else {
217 ll = L.GeometryUtil.closest(map, layer, latlng);
218 if (ll) distance = ll.distance; // Can return null if layer has no points.
219 }
220 if (distance < mindist) {
221 mindist = distance;
222 result = {layer: layer, latlng: ll, distance: distance};
223 }
224 }
225 return result;
226 },
227
228 /**
229 Returns the closest position from specified {LatLng} among specified layers,
230 with a maximum tolerance in pixels, providing snapping behaviour.
231 @param {L.Map} map
232 @param {Array<ILayer>} layers - A list of layers to snap on.
233 @param {L.LatLng} latlng - The position to snap.
234 @param {?Number} [tolerance=Infinity] - Maximum number of pixels.
235 @param {?boolean} [withVertices=true] - Snap to layers vertices.
236 @returns {object} with snapped {LatLng} and snapped {Layer} or null if tolerance exceeded.
237 */
238 closestLayerSnap: function (map, layers, latlng, tolerance, withVertices) {
239 tolerance = typeof tolerance == 'number' ? tolerance : Infinity;
240 withVertices = typeof withVertices == 'boolean' ? withVertices : true;
241
242 var result = L.GeometryUtil.closestLayer(map, layers, latlng);
243 if (!result || result.distance > tolerance)
244 return null;
245
246 // If snapped layer is linear, try to snap on vertices (extremities and middle points)
247 if (withVertices && typeof result.layer.getLatLngs == 'function') {
248 var closest = L.GeometryUtil.closest(map, result.layer, result.latlng, true);
249 if (closest.distance < tolerance) {
250 result.latlng = closest;
251 result.distance = L.GeometryUtil.distance(map, closest, latlng);
252 }
253 }
254 return result;
255 },
256
257 /**
258 Returns the Point located on a segment at the specified ratio of the segment length.
259 @param {L.Point} pA
260 @param {L.Point} pB
261 @param {Number} the length ratio, expressed as a decimal between 0 and 1, inclusive.
262 @returns {L.Point} the interpolated point.
263 */
264 interpolateOnPointSegment: function (pA, pB, ratio) {
265 return L.point(
266 (pA.x * (1 - ratio)) + (ratio * pB.x),
267 (pA.y * (1 - ratio)) + (ratio * pB.y)
268 );
269 },
270
271 /**
272 Returns the coordinate of the point located on a line at the specified ratio of the line length.
273 @param {L.Map} map
274 @param {Array<L.LatLng>|L.PolyLine} latlngs
275 @param {Number} the length ratio, expressed as a decimal between 0 and 1, inclusive
276 @returns {Object} an object with latLng ({LatLng}) and predecessor ({Number}), the index of the preceding vertex in the Polyline
277 (-1 if the interpolated point is the first vertex)
278 */
279 interpolateOnLine: function (map, latLngs, ratio) {
280 latLngs = (latLngs instanceof L.Polyline) ? latLngs.getLatLngs() : latLngs;
281 var n = latLngs.length;
282 if (n < 2) {
283 return null;
284 }
285
286 if (ratio === 0) {
287 return {
288 latLng: latLngs[0] instanceof L.LatLng ? latLngs[0] : L.latLng(latLngs[0]),
289 predecessor: -1
290 };
291 }
292 if (ratio == 1) {
293 return {
294 latLng: latLngs[latLngs.length -1] instanceof L.LatLng ? latLngs[latLngs.length -1] : L.latLng(latLngs[latLngs.length -1]),
295 predecessor: latLngs.length - 2
296 };
297 }
298
299 // ensure the ratio is between 0 and 1;
300 ratio = Math.max(Math.min(ratio, 1), 0);
301
302 // project the LatLngs as Points,
303 // and compute total planar length of the line at max precision
304 var maxzoom = map.getMaxZoom();
305 if (maxzoom === Infinity)
306 maxzoom = map.getZoom();
307 var pts = [];
308 var lineLength = 0;
309 for(var i = 0; i < n; i++) {
310 pts[i] = map.project(latLngs[i], maxzoom);
311 if(i > 0)
312 lineLength += pts[i-1].distanceTo(pts[i]);
313 }
314
315 var ratioDist = lineLength * ratio;
316 var a = pts[0],
317 b = pts[1],
318 distA = 0,
319 distB = a.distanceTo(b);
320 // follow the line segments [ab], adding lengths,
321 // until we find the segment where the points should lie on
322 var index = 1;
323 for (; index < n && distB < ratioDist; index++) {
324 a = b;
325 distA = distB;
326 b = pts[index];
327 distB += a.distanceTo(b);
328 }
329 // compute the ratio relative to the segment [ab]
330 var segmentRatio = ((distB - distA) !== 0) ? ((ratioDist - distA) / (distB - distA)) : 0;
331 var interpolatedPoint = L.GeometryUtil.interpolateOnPointSegment(a, b, segmentRatio);
332 return {
333 latLng: map.unproject(interpolatedPoint, maxzoom),
334 predecessor: index-2
335 };
336 },
337
338 /**
339 Returns a float between 0 and 1 representing the location of the
340 closest point on polyline to the given latlng, as a fraction of total 2d line length.
341 (opposite of L.GeometryUtil.interpolateOnLine())
342 @param {L.Map} map
343 @param {L.PolyLine} polyline
344 @param {L.LatLng} latlng
345 @returns {Number}
346 */
347 locateOnLine: function (map, polyline, latlng) {
348 var latlngs = polyline.getLatLngs();
349 if (latlng.equals(latlngs[0]))
350 return 0.0;
351 if (latlng.equals(latlngs[latlngs.length-1]))
352 return 1.0;
353
354 var point = L.GeometryUtil.closest(map, polyline, latlng, false),
355 lengths = L.GeometryUtil.accumulatedLengths(latlngs),
356 total_length = lengths[lengths.length-1],
357 portion = 0,
358 found = false;
359 for (var i=0, n = latlngs.length-1; i < n; i++) {
360 var l1 = latlngs[i],
361 l2 = latlngs[i+1];
362 portion = lengths[i];
363 if (L.GeometryUtil.belongsSegment(point, l1, l2)) {
364 portion += l1.distanceTo(point);
365 found = true;
366 break;
367 }
368 }
369 if (!found) {
370 throw "Could not interpolate " + latlng.toString() + " within " + polyline.toString();
371 }
372 return portion / total_length;
373 },
374
375 /**
376 Returns a clone with reversed coordinates.
377 @param {L.PolyLine} polyline
378 @returns {L.PolyLine}
379 */
380 reverse: function (polyline) {
381 return L.polyline(polyline.getLatLngs().slice(0).reverse());
382 },
383
384 /**
385 Returns a sub-part of the polyline, from start to end.
386 If start is superior to end, returns extraction from inverted line.
387 @param {L.Map} map
388 @param {L.PolyLine} latlngs
389 @param {Number} start ratio, expressed as a decimal between 0 and 1, inclusive
390 @param {Number} end ratio, expressed as a decimal between 0 and 1, inclusive
391 @returns {Array<L.LatLng>}
392 */
393 extract: function (map, polyline, start, end) {
394 if (start > end) {
395 return L.GeometryUtil.extract(map, L.GeometryUtil.reverse(polyline), 1.0-start, 1.0-end);
396 }
397
398 // Bound start and end to [0-1]
399 start = Math.max(Math.min(start, 1), 0);
400 end = Math.max(Math.min(end, 1), 0);
401
402 var latlngs = polyline.getLatLngs(),
403 startpoint = L.GeometryUtil.interpolateOnLine(map, polyline, start),
404 endpoint = L.GeometryUtil.interpolateOnLine(map, polyline, end);
405 // Return single point if start == end
406 if (start == end) {
407 var point = L.GeometryUtil.interpolateOnLine(map, polyline, end);
408 return [point.latLng];
409 }
410 // Array.slice() works indexes at 0
411 if (startpoint.predecessor == -1)
412 startpoint.predecessor = 0;
413 if (endpoint.predecessor == -1)
414 endpoint.predecessor = 0;
415 var result = latlngs.slice(startpoint.predecessor+1, endpoint.predecessor+1);
416 result.unshift(startpoint.latLng);
417 result.push(endpoint.latLng);
418 return result;
419 },
420
421 /**
422 Returns true if first polyline ends where other second starts.
423 @param {L.PolyLine} polyline
424 @param {L.PolyLine} other
425 @returns {bool}
426 */
427 isBefore: function (polyline, other) {
428 if (!other) return false;
429 var lla = polyline.getLatLngs(),
430 llb = other.getLatLngs();
431 return (lla[lla.length-1]).equals(llb[0]);
432 },
433
434 /**
435 Returns true if first polyline starts where second ends.
436 @param {L.PolyLine} polyline
437 @param {L.PolyLine} other
438 @returns {bool}
439 */
440 isAfter: function (polyline, other) {
441 if (!other) return false;
442 var lla = polyline.getLatLngs(),
443 llb = other.getLatLngs();
444 return (lla[0]).equals(llb[llb.length-1]);
445 },
446
447 /**
448 Returns true if first polyline starts where second ends or start.
449 @param {L.PolyLine} polyline
450 @param {L.PolyLine} other
451 @returns {bool}
452 */
453 startsAtExtremity: function (polyline, other) {
454 if (!other) return false;
455 var lla = polyline.getLatLngs(),
456 llb = other.getLatLngs(),
457 start = lla[0];
458 return start.equals(llb[0]) || start.equals(llb[llb.length-1]);
459 },
460
461 /**
462 Returns horizontal angle in degres between two points.
463 @param {L.Point} a
464 @param {L.Point} b
465 @returns {float}
466 */
467 computeAngle: function(a, b) {
468 return (Math.atan2(b.y - a.y, b.x - a.x) * 180 / Math.PI);
469 },
470
471 /**
472 Returns slope (Ax+B) between two points.
473 @param {L.Point} a
474 @param {L.Point} b
475 @returns {Object} with ``a`` and ``b`` properties.
476 */
477 computeSlope: function(a, b) {
478 var s = (b.y - a.y) / (b.x - a.x),
479 o = a.y - (s * a.x);
480 return {'a': s, 'b': o};
481 },
482
483 /**
484 Returns LatLng of rotated point around specified LatLng center.
485 @param {L.LatLng} latlngPoint: point to rotate
486 @param {double} angleDeg: angle to rotate in degrees
487 @param {L.LatLng} latlngCenter: center of rotation
488 @returns {L.LatLng} rotated point
489 */
490 rotatePoint: function(map, latlngPoint, angleDeg, latlngCenter) {
491 var maxzoom = map.getMaxZoom();
492 if (maxzoom === Infinity)
493 maxzoom = map.getZoom();
494 var angleRad = angleDeg*Math.PI/180,
495 pPoint = map.project(latlngPoint, maxzoom),
496 pCenter = map.project(latlngCenter, maxzoom),
497 x2 = Math.cos(angleRad)*(pPoint.x-pCenter.x) - Math.sin(angleRad)*(pPoint.y-pCenter.y) + pCenter.x,
498 y2 = Math.sin(angleRad)*(pPoint.x-pCenter.x) + Math.cos(angleRad)*(pPoint.y-pCenter.y) + pCenter.y;
499 return map.unproject(new L.Point(x2,y2), maxzoom);
500 },
501
502 /**
503 Returns the bearing in degrees clockwise from north (0 degrees)
504 from the first L.LatLng to the second, at the first LatLng
505 @param {L.LatLng} latlng1: origin point of the bearing
506 @param {L.LatLng} latlng2: destination point of the bearing
507 @returns {float} degrees clockwise from north.
508 */
509 bearing: function(latlng1, latlng2) {
510 var rad = Math.PI / 180,
511 lat1 = latlng1.lat * rad,
512 lat2 = latlng2.lat * rad,
513 lon1 = latlng1.lng * rad,
514 lon2 = latlng2.lng * rad,
515 y = Math.sin(lon2 - lon1) * Math.cos(lat2),
516 x = Math.cos(lat1) * Math.sin(lat2) -
517 Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);
518
519 var bearing = ((Math.atan2(y, x) * 180 / Math.PI) + 360) % 360;
520 return bearing >= 180 ? bearing-360 : bearing;
521 },
522
523 /**
524 Returns the point that is a distance and heading away from
525 the given origin point.
526 @param {L.LatLng} latlng: origin point
527 @param {float}: heading in degrees, clockwise from 0 degrees north.
528 @param {float}: distance in meters
529 @returns {L.latLng} the destination point.
530 Many thanks to Chris Veness at http://www.movable-type.co.uk/scripts/latlong.html
531 for a great reference and examples.
532 */
533 destination: function(latlng, heading, distance) {
534 heading = (heading + 360) % 360;
535 var rad = Math.PI / 180,
536 radInv = 180 / Math.PI,
537 R = 6378137, // approximation of Earth's radius
538 lon1 = latlng.lng * rad,
539 lat1 = latlng.lat * rad,
540 rheading = heading * rad,
541 sinLat1 = Math.sin(lat1),
542 cosLat1 = Math.cos(lat1),
543 cosDistR = Math.cos(distance / R),
544 sinDistR = Math.sin(distance / R),
545 lat2 = Math.asin(sinLat1 * cosDistR + cosLat1 *
546 sinDistR * Math.cos(rheading)),
547 lon2 = lon1 + Math.atan2(Math.sin(rheading) * sinDistR *
548 cosLat1, cosDistR - sinLat1 * Math.sin(lat2));
549 lon2 = lon2 * radInv;
550 lon2 = lon2 > 180 ? lon2 - 360 : lon2 < -180 ? lon2 + 360 : lon2;
551 return L.latLng([lat2 * radInv, lon2]);
552 }
553 });
554
555 return L.GeometryUtil;
556
557 }));