Class Length

 1 /*
 2  * Copyright (c) 2016 Vivid Solutions.
 3  *
 4  * All rights reserved. This program and the accompanying materials
 5  * are made available under the terms of the Eclipse Public License 2.0
 6  * and Eclipse Distribution License v. 1.0 which accompanies this distribution.
 7  * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v20.html
 8  * and the Eclipse Distribution License is available at
 9  *
10  * http://www.eclipse.org/org/documents/edl-v10.php.
11  */
12 package org.locationtech.jts.algorithm;
13  
14 import org.locationtech.jts.geom.Coordinate;
15 import org.locationtech.jts.geom.CoordinateSequence;
16  
17 /**
18  * Functions for computing length.
19  * 
20  * @author Martin Davis
21  *
22  */
23 public class Length {
24  
25   /**
26    * Computes the length of a linestring specified by a sequence of points.
27    * 
28    * @param pts the points specifying the linestring
29    * @return the length of the linestring
30    */
31   public static double ofLine(CoordinateSequence pts)
32   {
33     // optimized for processing CoordinateSequences
34     int n = pts.size();
35     if (n <= 1)
36       return 0.0;
37   
38     double len = 0.0;
39   
40     Coordinate p = new Coordinate();
41     pts.getCoordinate(0, p);
42     double x0 = p.x;
43     double y0 = p.y;
44   
45     for (int i = 1; i < n; i++) {
46       pts.getCoordinate(i, p);
47       double x1 = p.x;
48       double y1 = p.y;
49       double dx = x1 - x0;
50       double dy = y1 - y0;
51   
52       len += Math.sqrt(dx * dx + dy * dy);
53   
54       x0 = x1;
55       y0 = y1;
56     }
57     return len;
58   }
59  
60 }
61