CalculateRoute
In this code, we also request a map (MapSize >0) of the route in addition to turn-by-turn directions.
private void btnCalculateRoute_Click(object sender, EventArgs e)
{
btnCalculateRoute.Enabled = false;
try
{
routeRequest = new TestInternal.ts.RouteSpecification();
routeRequest.RouteOptions = new ts.RouteOptions();
routeRequest.RouteOptions.DistanceUnit = ts.DistanceUnit.Mile;
routeRequest.RouteOptions.MapSize = new ts.MapSize();
routeRequest.RouteOptions.MapSize.Height = 200;
routeRequest.RouteOptions.MapSize.Width = 400;
//Let's create 2 locations for example
int count = 2;
//Create an array of locations
routeRequest.Locations = new TestInternal.ts.Location[count];
Random rnd = new Random();
for (int i = 0; i < count; i++)
{
TestInternal.ts.Location loc = new TestInternal.ts.Location();
loc.Name = string.Format("Loc_{0}", i + 1);
// in this sample we use latitude & longitude but you can use the
// Address property of location to geocode your location on-the-fly.
loc.LatLong = new TestInternal.ts.LatLong();
if (i == 0)
{
loc.LatLong.Latitude = 38.931594;
loc.LatLong.Longitude = -77.27602;
}
else
{
loc.LatLong.Latitude = 38.938467;
loc.LatLong.Longitude = -77.164874;
}
//Add location to array.
routeRequest.Locations[i] = loc;
}
try
{
client.Timeout = 1000 * 60 * 30;//30 minutes
TestInternal.ts.RouteResult result = client.CalculateRoute(routeRequest);
if (result.Status == TestInternal.ts.OperationStatus.Success)
{
StringBuilder sb = new StringBuilder();
string path = "c:\\temp\\route";
if (Directory.Exists(path))
Directory.Delete(path, true);
Directory.CreateDirectory(path);
for (int i = 0; i < result.Route.RouteLegs.Length; i++)
{
sb.AppendFormat("---------------------Leg:{0}\r\n", i);
ts.RouteLeg rl = result.Route.RouteLegs[i];
for (int j = 0; j < rl.Itinerary.Items.Length; j++)
{
ts.RouteItineraryItem ri = rl.Itinerary.Items[j];
sb.AppendFormat("{0}\t [{1:f2},{2}]\r\n", ri.Text, ri.Distance, ri.Time);
}
if (rl.Map != null)
{
byte[] bytes = Convert.FromBase64String(rl.Map);
using (MemoryStream ms = new MemoryStream(bytes))
{
Image mapImage = Image.FromStream(ms);
mapImage.Save(path + "\\Leg" + i + ".png");
}
}
}
if (result.Route.Map != null)
{
byte[] bytes = Convert.FromBase64String(result.Route.Map);
using (MemoryStream ms = new MemoryStream(bytes))
{
Image mapImage = Image.FromStream(ms);
mapImage.Save(path + "\\Route.png");
}
}
txtResult.Text = sb.ToString();
return;
}
else//(result.Status == WebRef.ts.OperationStatus.SuccessWithErrors)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Status:{0}\r\n", result.Status);
foreach (TestInternal.ts.Error i in result.Errors)
{
sb.AppendFormat("{0}\r\n", i.Message);
}
txtResult.Text = sb.ToString();
//Show result with error. Some of locations can be skipped or errors.
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
finally
{
btnCalculateRoute.Enabled = true;
}
}