Free cookie consent management tool by TermsFeed Policy Generator

source: branches/RoutePlanning/HeuristicLab.Problems.RoutePlanning/3.3/Osm/Utils.cs @ 8471

Last change on this file since 8471 was 8462, checked in by spimming, 12 years ago

#1894:

  • calculate distance in kilometers for two locations
  • generate IGraph from a datasource
  • adapted test program
File size: 2.3 KB
Line 
1using System;
2using System.Collections.Generic;
3
4namespace HeuristicLab.Problems.RoutePlanning.Osm {
5  public static class Utils {
6    public static double Distance(PointD p1, PointD p2) {
7      double dx = p2.X - p1.X;
8      double dy = p2.Y - p1.Y;
9      return Math.Sqrt(dx * dx + dy * dy);
10    }
11
12    public static double LocationDistance(PointD p1, PointD p2) {
13      // The Haversine formula
14      /* dlon = lon2 - lon1
15            dlat = lat2 - lat1
16            a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2
17            c = 2 * atan2(sqrt(a), sqrt(1-a))
18            d = R * c
19       */
20
21      double lat1Rad = p1.Y * (Math.PI / 180.0);
22      double long1Rad = p1.X * (Math.PI / 180.0);
23      double lat2Rad = p2.Y * (Math.PI / 180.0);
24      double long2Rad = p2.X * (Math.PI / 180.0);
25
26      double longitude = long2Rad - long1Rad;
27      double latitude = lat2Rad - lat1Rad;
28
29      double a = Math.Pow(Math.Sin(latitude / 2.0), 2.0) +
30                   Math.Cos(lat1Rad) * Math.Cos(lat2Rad) *
31                   Math.Pow(Math.Sin(longitude / 2.0), 2.0);
32
33      double c = 2.0 * Math.Asin(Math.Sqrt(a));
34
35      const double earthRadiusKms = 6376.5;
36      double distance = earthRadiusKms * c;
37
38      return distance;
39    }
40
41    public static double PathLength(IList<PointD> points) {
42      double length = 0;
43      for (int i = 1; i < points.Count; i++) {
44        length += Distance((PointD)points[i - 1], (PointD)points[i]);
45      }
46      return length;
47    }
48
49    public static RectangleD FindBox(IList<PointD> points) {
50      double minX = double.MaxValue;
51      double maxX = double.MinValue;
52      double minY = double.MaxValue;
53      double maxY = double.MinValue;
54
55      foreach (PointD p in points) {
56        if (p.X < minX)
57          minX = p.X;
58        if (p.X > maxX)
59          maxX = p.X;
60
61        if (p.Y < minY)
62          minY = p.Y;
63        if (p.Y > maxY)
64          maxY = p.Y;
65      }
66      return new RectangleD(minX, minY, maxX - minX, maxY - minY);
67    }
68
69    public static double PathDistance(IList<PointD> path1, IList<PointD> path2) {
70      double distance = 0;
71      for (int i = 0; i < path1.Count; i++) {
72        distance += Distance((PointD)path1[i], (PointD)path2[i]);
73      }
74      return distance / path1.Count;
75    }
76  }
77}
78
Note: See TracBrowser for help on using the repository browser.