Friday, December 12, 2014
Distance Between 2 cities, using Google Distance Matrix, in c#
public Double GetDistanceInMilesBetweenTwoCities( string city1, string city2 )
{
////Pass request to google api with origin and destination details(Map Coords)
HttpWebRequest request =
( HttpWebRequest )WebRequest.Create( "http://maps.googleapis.com/maps/api/distancematrix/json?origins="
+ city1 + "&destinations=" + city2 + "&mode=Car&language=us-en&sensor=false" );
HttpWebResponse response = ( HttpWebResponse )request.GetResponse();
using ( var streamReader = new StreamReader( response.GetResponseStream() ) )
{
var json = streamReader.ReadToEnd();
if ( !string.IsNullOrEmpty( json ) )
{
//Uses the NewtonSoft Json library that is shipped in vs 2013, the .N3.5 version to match this service. (thank you stack overflow!) - EWB
Parent parent = JsonConvert.DeserializeObject<Parent>( json );
if ( parent.rows[ 0 ].elements[ 0 ].status.ToUpper() != "OK" )
{
throw new Exception("Invalid City Name please try again");
}
Double distInKM = parent.rows[ 0 ].elements[ 0 ].distance.value;
return DistanceCoversion.ConvertMetersToMiles( distInKM );
}
}
return -1;
}
public class DistanceCoversion
{
<snip>
public static Double ConvertMetersToMiles( Double meters )
{
//
// Multiply by this constant.
//
return (meters/1000) * 0.621371192;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment