// UPDATED (old method left commented out below updated method) // convert Bing address to lat/lon public MyWaypoint Geocode(string address) { //MessageBox.Show($"Geocode method called for !! {address} "); // FOR DEBUGGING PURPOSES // create the Geocode request GeocodeRequest locationRequest = new GeocodeRequest { BingMapsKey = m_bingMapKey, MaxResults = 1, IncludeNeighborhood = true, IncludeIso2 = true, Query = address }; //MessageBox.Show("About to execute location request!");// FOR DEBUGGING PURPOSES // execute the response // this call can also use await, but then method would have to be made async Response geocodeResponse = locationRequest.Execute().Result; //MessageBox.Show("Executed location Request!");// FOR DEBUGGING PURPOSES // set lat/lon/altitude of waypoint and return waypoint MyWaypoint returnPoint = new MyWaypoint(); if (geocodeResponse.ResourceSets.Length > 0) { var result = geocodeResponse.ResourceSets[0].Resources[0] as BingMapsRESTToolkit.Location; returnPoint.Latitude = result.Point.Coordinates[0]; returnPoint.Longitude = result.Point.Coordinates[1]; returnPoint.Altitude = 0.0; } //MessageBox.Show("Geocode method done!");// FOR DEBUGGING PURPOSES return(returnPoint); }
public List <MyWaypoint> CreateRoute(MyWaypoint startPoint, MyWaypoint endPoint) { // create route from waypointString RouteRequest routeRequest = new RouteRequest(); // Set the credentials using a valid Bing Maps key routeRequest.Credentials = new BingRouteService.Credentials(); routeRequest.Credentials.ApplicationId = m_bingMapKey; // tell them that we want points along the route routeRequest.Options = new RouteOptions(); routeRequest.Options.RoutePathType = RoutePathType.Points; //Parse user data to create array of waypoints BingRouteService.Waypoint[] waypoints = new BingRouteService.Waypoint[2]; BingRouteService.Waypoint point1 = new BingRouteService.Waypoint(); BingRouteService.Location location1 = new BingRouteService.Location(); location1.Latitude = startPoint.Latitude; location1.Longitude = startPoint.Longitude; point1.Location = location1; point1.Description = "Start"; waypoints[0] = point1; BingRouteService.Waypoint point2 = new BingRouteService.Waypoint(); BingRouteService.Location location2 = new BingRouteService.Location(); location2.Latitude = endPoint.Latitude; location2.Longitude = endPoint.Longitude; point2.Location = location2; point2.Description = "End"; waypoints[1] = point2; routeRequest.Waypoints = waypoints; // Make the calculate route request RouteServiceClient routeService = new RouteServiceClient("BasicHttpBinding_IRouteService"); RouteResponse routeResponse = routeService.CalculateRoute(routeRequest); // pull out the lat/lon values List <MyWaypoint> returnPoints = new List <MyWaypoint>(); if (routeResponse.Result.Legs.Length > 0) { //MessageBox.Show("Distance: " + routeResponse.Result.Summary.Distance.ToString() // + " Time: " + routeResponse.Result.Summary.TimeInSeconds.ToString()); foreach (BingRouteService.Location thisPt in routeResponse.Result.RoutePath.Points) { MyWaypoint thisPoint = new MyWaypoint(); thisPoint.Latitude = thisPt.Latitude; thisPoint.Longitude = thisPt.Longitude; //thisPoint.Altitude = GetAltitude(thisPoint.Latitude, thisPoint.Longitude); thisPoint.Altitude = 0.0; returnPoints.Add(thisPoint); } } return(returnPoints); }
// convert address to lat/lon public MyWaypoint Geocode(string address) { GeocodeRequest locationRequest = new GeocodeRequest(); // Set the credentials using a valid Bing Maps key locationRequest.Credentials = new BingGeocodeService.Credentials(); locationRequest.Credentials.ApplicationId = m_bingMapKey; locationRequest.Query = address; // Make the calculate route request GeocodeServiceClient geocodeService = new BingGeocodeService.GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); GeocodeResponse geocodeResponse = geocodeService.Geocode(locationRequest); MyWaypoint returnPoint = new MyWaypoint(); if (geocodeResponse.Results.Length > 0) { returnPoint.Latitude = geocodeResponse.Results[0].Locations[0].Latitude; returnPoint.Longitude = geocodeResponse.Results[0].Locations[0].Longitude; //returnPoint.Altitude = GetAltitude(returnPoint.Latitude, returnPoint.Longitude); returnPoint.Altitude = 0.0; } return(returnPoint); }
// UPDATED (old method is left commented out below updated method) // create route between 2 waypoints using Bing maps public List <MyWaypoint> CreateRoute(MyWaypoint startPoint, MyWaypoint endPoint) { //MessageBox.Show("CreateRoute method called!");// FOR DEBUGGING PURPOSES // create route from waypointString RouteRequest routeRequest = new RouteRequest() { // create Start and End SimpleWaypoints by passing in lat/lon of startPoint and endPoint Waypoints = new List <SimpleWaypoint>() { new SimpleWaypoint(startPoint.Latitude, startPoint.Longitude), new SimpleWaypoint(endPoint.Latitude, endPoint.Longitude) }, BingMapsKey = m_bingMapKey }; // define response (we want Route Path) routeRequest.RouteOptions = new RouteOptions(); routeRequest.RouteOptions.RouteAttributes = new List <RouteAttributeType>() { RouteAttributeType.RoutePath }; routeRequest.RouteOptions.Optimize = RouteOptimizationType.Distance; // create Route request //MessageBox.Show("Executing route request!"); var routeResponse = routeRequest.Execute().Result; //MessageBox.Show("Executed route request!"); // show message if route not returned? if (routeResponse.ResourceSets.Length <= 0) { System.Console.WriteLine("No Path Found"); return(null); } // pull out the lat/lon values List <MyWaypoint> returnPoints = new List <MyWaypoint>(); var route = routeResponse.ResourceSets[0].Resources[0] as Route; // var result = routeResponse.ResourceSets[0].Resources as BingMapsRESTToolkit.Location[]; //MessageBox.Show("Distance: " + routeResponse.Result.Summary.Distance.ToString() // + " Time: " + routeResponse.Result.Summary.TimeInSeconds.ToString()); // define and add points to returnPoints foreach (var point in route.RoutePath.Line.Coordinates) { MyWaypoint myWaypoint = new MyWaypoint(); myWaypoint.Latitude = point[0]; myWaypoint.Longitude = point[1]; //thisPoint.Altitude = GetAltitude(thisPoint.Latitude, thisPoint.Longitude); myWaypoint.Altitude = 0.0; returnPoints.Add(myWaypoint); } //MessageBox.Show("CreateRoute method finished!"); //FOR DEBUGGING PURPOSES return(returnPoints); }
// call Bing REST service with start and end lat/lon private List <MyWaypoint> GetRoute(MyWaypoint startPoint, MyWaypoint endPoint) { string urlString = "http://dev.virtualearth.net/REST/V1/Routes/Driving?o=xml&wp.0=" + startPoint.Latitude.ToString() + "," + startPoint.Longitude.ToString() + "&wp.1=" + endPoint.Latitude.ToString() + "," + endPoint.Longitude.ToString() + "&rpo=Points&key=" + m_bingMapKey; Uri directionRequest = new Uri(urlString); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(directionRequest); request.Method = "GET"; // get response try { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string content = string.Empty; using (Stream stream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(stream)) { content = sr.ReadToEnd(); } } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(content); XmlNodeList pointList = xmlDoc.GetElementsByTagName("Point"); // pull out the lat/lon values List <MyWaypoint> returnPoints = new List <MyWaypoint>(); foreach (XmlNode thisWaypoint in pointList) { MyWaypoint thisPoint = new MyWaypoint(); thisPoint.Latitude = Convert.ToDouble(thisWaypoint.ChildNodes[0].InnerText); thisPoint.Longitude = Convert.ToDouble(thisWaypoint.ChildNodes[1].InnerText); //thisPoint.Altitude = GetAltitude(thisPoint.Latitude, thisPoint.Longitude); thisPoint.Altitude = Convert.ToDouble(altOffsetTextBox.Text); returnPoints.Add(thisPoint); } return(returnPoints); } catch (Exception) { MessageBox.Show("No route found from " + fromTextBox.Text + " to " + toTextBox.Text); return(null); } }
// old method /* public MyWaypoint Geocode(string address) * { * GeocodeRequest locationRequest = new GeocodeRequest(); * * // Set the credentials using a valid Bing Maps key * locationRequest.Credentials = new BingGeocodeService.Credentials(); * locationRequest.Credentials.ApplicationId = m_bingMapKey; * locationRequest.Query = address; * * // Make the calculate route request * GeocodeServiceClient geocodeService = new BingGeocodeService.GeocodeServiceClient("BasicHttpBinding_IGeocodeService"); * GeocodeResponse geocodeResponse = geocodeService.Geocode(locationRequest); * * MyWaypoint returnPoint = new MyWaypoint(); * if (geocodeResponse.Results.Length > 0) * { * returnPoint.Latitude = geocodeResponse.Results[0].Locations[0].Latitude; * returnPoint.Longitude = geocodeResponse.Results[0].Locations[0].Longitude; * //returnPoint.Altitude = GetAltitude(returnPoint.Latitude, returnPoint.Longitude); * returnPoint.Altitude = 0.0; * } * * return returnPoint; * } */ // convert object location to lat/lon public MyWaypoint Geocode(IAgStkObject stkObject) { IAgDataPrvFixed dataprov = stkObject.DataProviders["LLA State"] as IAgDataPrvFixed; IAgDrResult result = dataprov.Exec(); Array lat = result.DataSets.GetDataSetByName("Lat").GetValues(); Array lon = result.DataSets.GetDataSetByName("Lon").GetValues(); MyWaypoint returnPoint = new MyWaypoint(); returnPoint.Latitude = (double)lat.GetValue(0); returnPoint.Longitude = (double)lon.GetValue(0); returnPoint.Altitude = 0.0; return(returnPoint); }
// convert address to lat/lon private MyWaypoint Geocode(string address) { // build URL string addressPadded = address.Replace(",", "%20").Replace(" ", "%20"); string urlString = "http://dev.virtualearth.net/REST/v1/Locations/" + addressPadded + "?o=xml&maxResults=1&key=" + m_bingMapKey; Uri geocodeRequest = new Uri(urlString); // send request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(geocodeRequest); request.Method = "GET"; // get response HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string content = string.Empty; using (Stream stream = response.GetResponseStream()) { using (StreamReader sr = new StreamReader(stream)) { content = sr.ReadToEnd(); } } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(content); MyWaypoint returnPoint = new MyWaypoint(); // check results were found if (xmlDoc.GetElementsByTagName("EstimatedTotal")[0].InnerText != "0") { returnPoint.Latitude = Convert.ToDouble(xmlDoc.GetElementsByTagName("Latitude")[0].InnerText); returnPoint.Longitude = Convert.ToDouble(xmlDoc.GetElementsByTagName("Longitude")[0].InnerText); } return(returnPoint); }
private void Button1_Click(object sender, EventArgs e) { // check custom Bing Maps Key XmlDocument configDoc = new XmlDocument(); configDoc.Load(Path.Combine(Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).ToString(), "BingMapsKey.config")); string mapKey = configDoc.GetElementsByTagName("BingMapKey")[0].InnerText; if (mapKey != "XXX") { m_bingMapKey = mapKey; } if (mapKey == "XXX") { MessageBox.Show("A valid Bing Maps key was not provided. Obtain one from https://msdn.microsoft.com/en-us/library/ff428642.aspx and load it into BingMapsKey.config"); return; } // check if scenario is open if (m_root.CurrentScenario == null) { MessageBox.Show("no scenario is open."); return; } // check if using address if (trafficDirectionsTabControl.SelectedIndex == 0) { // directions #region empty address error check if (fromTextBox.Text == "") { MessageBox.Show("no start address entered"); return; } if (toTextBox.Text == "") { MessageBox.Show("no end address entered"); return; } #endregion // get lat/lon from addresses MyWaypoint startPoint = Geocode(fromTextBox.Text); MyWaypoint endPoint = Geocode(toTextBox.Text); #region address found error check if (startPoint.Longitude == 0.0 && startPoint.Latitude == 0.0 && startPoint.Altitude == 0.0) { MessageBox.Show("start address not found"); return; } if (endPoint.Longitude == 0.0 && endPoint.Latitude == 0.0 && endPoint.Altitude == 0.0) { MessageBox.Show("end address not found"); return; } #endregion AddRoute(startPoint, endPoint, nameTextBox.Text); } // check if using points if (trafficDirectionsTabControl.SelectedIndex == 1) { // START IAgStkObject oStart = m_root.GetObjectFromPath(fromObjectComboBox.Items[fromObjectComboBox.SelectedIndex].ToString()); object startLat = 0; object startLon = 0; double startAlt = 0; switch (oStart.ClassType) { case AgESTKObjectType.eFacility: ((IAgFacility)oStart).Position.QueryPlanetodetic(out startLat, out startLon, out startAlt); break; case AgESTKObjectType.eTarget: ((IAgTarget)oStart).Position.QueryPlanetodetic(out startLat, out startLon, out startAlt); break; case AgESTKObjectType.ePlace: ((IAgPlace)oStart).Position.QueryPlanetodetic(out startLat, out startLon, out startAlt); break; } MyWaypoint start = new MyWaypoint(); start.Latitude = Convert.ToDouble(startLat); start.Longitude = Convert.ToDouble(startLon); start.Altitude = Convert.ToDouble(startAlt); // STOP IAgStkObject oStop = m_root.GetObjectFromPath(toObjectComboBox.Items[toObjectComboBox.SelectedIndex].ToString()); object stopLat = 0.0; object stopLon = 0.0; double stopAlt = 0.0; switch (oStop.ClassType) { case AgESTKObjectType.eFacility: ((IAgFacility)oStop).Position.QueryPlanetodetic(out stopLat, out stopLon, out stopAlt); break; case AgESTKObjectType.eTarget: ((IAgTarget)oStop).Position.QueryPlanetodetic(out stopLat, out stopLon, out stopAlt); break; case AgESTKObjectType.ePlace: ((IAgPlace)oStop).Position.QueryPlanetodetic(out stopLat, out stopLon, out stopAlt); break; } MyWaypoint stop = new MyWaypoint(); stop.Latitude = Convert.ToDouble(stopLat); stop.Longitude = Convert.ToDouble(stopLon); stop.Altitude = Convert.ToDouble(stopAlt); AddRoute(start, stop, nameTextBox.Text); } // check if using traffic if (trafficDirectionsTabControl.SelectedIndex == 2) { // traffic #region empty lat/lon textbos check if (minLatTextBox.Text == "") { MessageBox.Show("no southern limit specified"); return; } if (maxLatTextBox.Text == "") { MessageBox.Show("no northern limit specified"); return; } if (minLonTextBox.Text == "") { MessageBox.Show("no eastern limit specified"); return; } if (maxLonTextBox.Text == "") { MessageBox.Show("no western limit specified"); return; } #endregion Double minLat = Convert.ToDouble(minLatTextBox.Text); Double maxLat = Convert.ToDouble(maxLatTextBox.Text); Double minLon = Convert.ToDouble(minLonTextBox.Text); Double maxLon = Convert.ToDouble(maxLonTextBox.Text); Random rand = new Random(DateTime.Now.Millisecond); for (int i = 0; i < Convert.ToInt32(numVehicleTextBox.Text); i++) { MyWaypoint startPoint = new MyWaypoint(); startPoint.Latitude = minLat + rand.NextDouble() * (maxLat - minLat); startPoint.Longitude = minLon + rand.NextDouble() * (maxLon - minLon); MyWaypoint endPoint = new MyWaypoint(); endPoint.Latitude = minLat + rand.NextDouble() * (maxLat - minLat); endPoint.Longitude = minLon + rand.NextDouble() * (maxLon - minLon); AddRoute(startPoint, endPoint, nameTextBox.Text + i.ToString()); } } }
private void AddRoute(MyWaypoint startPoint, MyWaypoint endPoint, string gvName) { List <MyWaypoint> routePoints = GetRoute(startPoint, endPoint); // create new GV and add the waypoints if (m_root.CurrentScenario.Children.Contains(AgESTKObjectType.eGroundVehicle, gvName)) { MessageBox.Show(gvName + " already exists, please pick a different name"); } else { if (routePoints != null && routePoints.Count > 0) { double turnRadius = 2.0; // meter double granularity = 1.1; // meter m_root.UnitPreferences.SetCurrentUnit("Distance", "m"); switch (speedUnitsComboBox.SelectedItem.ToString()) { case "km/h": //m_root.UnitPreferences.SetCurrentUnit("Distance", "km"); m_root.UnitPreferences.SetCurrentUnit("Time", "hr"); //turnRadius /= 1000.0; //granularity /= 1000.0; speedUnitMultiplier = 1000.0; break; case "mph": //m_root.UnitPreferences.SetCurrentUnit("Distance", "mi"); m_root.UnitPreferences.SetCurrentUnit("Time", "hr"); //turnRadius /= 1609.44; //granularity /= 1609.44; speedUnitMultiplier = 1609.44; break; case "m/s": //m_root.UnitPreferences.SetCurrentUnit("Distance", "m"); m_root.UnitPreferences.SetCurrentUnit("Time", "sec"); speedUnitMultiplier = 1.0; break; } switch (altUnitsComboBox.SelectedItem.ToString()) { case "m": altUnitMultiplier = 1.0; break; case "km": altUnitMultiplier = 1000.0; break; case "ft": altUnitMultiplier = 0.3048; break; } IAgStkObject gvObject = m_root.CurrentScenario.Children.New(AgESTKObjectType.eGroundVehicle, gvName); IAgGroundVehicle gv = gvObject as IAgGroundVehicle; gv.SetRouteType(AgEVePropagatorType.ePropagatorGreatArc); IAgVePropagatorGreatArc prop = gv.Route as IAgVePropagatorGreatArc; foreach (MyWaypoint thisPt in routePoints) { IAgVeWaypointsElement thisVeWaypoint = prop.Waypoints.Add(); thisVeWaypoint.Latitude = thisPt.Latitude; thisVeWaypoint.Longitude = thisPt.Longitude; thisVeWaypoint.Altitude = thisPt.Altitude * altUnitMultiplier; thisVeWaypoint.Speed = Convert.ToDouble(speedTextBox.Text) * speedUnitMultiplier; thisVeWaypoint.TurnRadius = turnRadius; } if (terrainCheckBox.Checked) { prop.SetAltitudeRefType(AgEVeAltitudeRef.eWayPtAltRefTerrain); IAgVeWayPtAltitudeRefTerrain altRef = prop.AltitudeRef as IAgVeWayPtAltitudeRefTerrain; altRef.Granularity = granularity; altRef.InterpMethod = AgEVeWayPtInterpMethod.eWayPtEllipsoidHeight; } prop.Propagate(); } } }