Skip to content

Instantly share code, notes, and snippets.

@Tom-Millard
Created October 16, 2014 14:20
Show Gist options
  • Save Tom-Millard/dea4b9ceae0b920c6a8f to your computer and use it in GitHub Desktop.
Save Tom-Millard/dea4b9ceae0b920c6a8f to your computer and use it in GitHub Desktop.
Distance between two points by postcode
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
namespace distance
{
class distance
{
const double PIx = 3.141592653589793;
private double LatFrom = 0;
private double LonFrom = 0;
private double LatTo = 0;
private double LonTo = 0;
private string PostCodeFrom = "";
private string PostCodeTo = "";
public distance(string PostCodeFrom, string PostCodeTo)
{
this.PostCodeFrom = PostCodeFrom;
this.PostCodeTo = PostCodeTo;
PostCodeFrom = PostCodeFrom.Replace(" ", "%20");
PostCodeTo = PostCodeTo.Replace(" ", "%20");
string from = "http://maps.google.com/maps/geo?q=" + PostCodeFrom + "&output=xml";
string To = "http://maps.google.com/maps/geo?q=" + PostCodeTo + "&output=xml";
if (string.IsNullOrEmpty(from)) return;
if (string.IsNullOrEmpty(To)) return;
XmlDocument xmlDocFrom = new XmlDocument();
xmlDocFrom.Load(from);
XmlDocument xmlDocTo = new XmlDocument();
xmlDocTo.Load(To);
XmlNodeList GetFromCords = xmlDocFrom.GetElementsByTagName("coordinates");
XmlNodeList GetToCords = xmlDocTo.GetElementsByTagName("coordinates");
Console.WriteLine("xml From " + GetFromCords[0].InnerText);
Console.WriteLine("xml To " + GetToCords[0].InnerText);
string[] FromSplit = GetFromCords[0].InnerText.Split(',');
string[] ToSplit = GetToCords[0].InnerText.Split(',');
LonFrom = ConvertToDouble(FromSplit[0].Trim());
LatFrom = ConvertToDouble(FromSplit[1].Trim());
LonTo = ConvertToDouble(ToSplit[0].Trim());
LatTo = ConvertToDouble(ToSplit[1].Trim());
double result = 0.0;
Console.WriteLine("From " + LonFrom + ", " + LatTo);
Console.WriteLine("To " + LonTo + "," + LonTo);
result = CalcDistance(LatFrom, LonFrom, LatTo, LonTo);
Console.WriteLine(result + "m");
Console.ReadLine();
}
private double DistanceBetweenTwoPlaces()
{
return 0.0;
}
private double ConvertToDouble(string x)
{
double y = 0.0;
try
{
y = Convert.ToDouble(x);
}
catch (FormatException)
{
return y;
}
return y;
}
public double Radians(double x)
{
return x * PIx / 180;
}
public double CalcDistance(double lat1, double long1, double lat2, double long2)
{
int R = 3959;
double dLat = Radians(lat1 - lat2);
double dLon = Radians(long1 - long2);
double latOne = Radians(lat1);
double latTwo = Radians(lat2);
double a = Math.Sin(dLat/2) * Math.Sin(dLat/2) +
Math.Sin(dLon/2) * Math.Sin(dLon/2) * Math.Cos(latOne) * Math.Cos(latTwo);
double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
return Math.Round(R * c, 2);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment