public double getDistance(PointLatLng p1, PointLatLng p2) { GMapRoute route = new GMapRoute("getDistance"); route.Points.Add(p1); route.Points.Add(p2); double distance = route.Distance; route.Clear(); route = null; return distance; }
public PlaybackSbxjHelper(RMap map,IContainer c) { _map = map; playOverlay = map.FindOverlay("play"); if (playOverlay == null) { playOverlay = new GMapOverlay(map, "play"); map.Overlays.Add(playOverlay); playRoute = new GMapRoute(new List<GMap.NET.PointLatLng>(), "play"); playRoute.Stroke.Color = Color.Red; playRoute.Stroke.Width = 3; playOverlay.Routes.Add(playRoute); } car = new GMapMarkerGoogleGreen(new GMap.NET.PointLatLng(0, 0)); car.ToolTipMode = MarkerTooltipMode.Always; car.ToolTipText = "man"; car.ToolTip.Format.Alignment = StringAlignment.Near; playOverlay.Markers.Add(car); queue_pos = new Queue<gps_position>(); dataTimer = new Timer(); dataTimer.Tick += new EventHandler(dataTimer_Tick); dataTimer.Interval = 1; playTimer = new Timer(); playTimer.Tick += new EventHandler(playTimer_Tick); playTimer.Interval = 1000; }
public RoutePointMarker(GMap.NET.PointLatLng p, int routePointIndex, GMapRoute route) : base(p) { _route = route; _routePointIndex = routePointIndex; base.Size = new Size(8, 8); base.Offset = new Point((-1) * base.Size.Width / 2, (-1) * base.Size.Height / 2); }
public static GMapRoute GetRouteFromKml(string fileName) { try { //XDocument root = XDocument.Load(new System.IO.StreamReader(fileName)); XElement root = XElement.Load(new System.IO.StreamReader(fileName)); IEnumerable<string> coordinates = from c in root.Descendants(XName.Get("coordinates", root.Name.NamespaceName)) select (string)c; foreach (string c in coordinates) { List<PointLatLng> points = new List<GMap.NET.PointLatLng>(); string[] ss = c.Split(new char[] { ' ', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries); foreach (string sss in ss) { string[] ss2 = sss.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); points.Add(new PointLatLng(Convert.ToDouble(ss2[1]), Convert.ToDouble(ss2[0]))); } GMapRoute rt = new GMapRoute(points, string.Empty); { rt.Stroke = new Pen(Color.FromArgb(144, Color.Red)); rt.Stroke.Width = 5; rt.Stroke.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; } return rt; } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } return null; }
private void MapControl_OnRouteEnter(GMapRoute item) { if (marker != null) item.Overlay.Markers.Remove(marker); var point = item.Overlay.Control.PointToClient(Control.MousePosition); var pos = item.Overlay.Control.FromLocalToLatLng(point.X, point.Y); marker = new GMapMarkerRect(pos) { ToolTipMode = MarkerTooltipMode.Always, ToolTipText = createMessage(item.Tag), IsHitTestVisible = false }; item.Overlay.Markers.Add(marker); }
private void timer1_Tick(object sender, EventArgs e) { GMap.NET.WindowsForms.Markers.GMarkerGoogle curPos = new GMap.NET.WindowsForms.Markers.GMarkerGoogle(initialPoint, GMap.NET.WindowsForms.Markers.GMarkerGoogleType.blue_pushpin); path = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRoute(initialPoint, finalPoint, false, false, 15); GMapRoute route = new GMapRoute(path.Points, "My route"); overlayRoute.Routes.Clear(); overlayRoute.Routes.Add(route); areaMap.Overlays.Add(overlayRoute); label10.Text = (path.Distance * 1000).ToString(); areaMap.Refresh(); }
public static void DrawMap(GMapControl map, List<Point> points, Color color, bool includeMarkers) { Pen pen = new Pen(color, 3.0f); List<PointLatLng> allMapPoints = points.Select(point => new PointLatLng(point.Latitude, point.Longitude)).ToList(); GMapRoute route = new GMapRoute(allMapPoints, "Route"); route.Stroke = pen; map.ZoomAndCenterRoute(route); GMapOverlay overlay = new GMapOverlay(map, "Overlay"); if (includeMarkers) { overlay.Markers.Add(new GMap.NET.WindowsForms.Markers.GMapMarkerGoogleGreen(new PointLatLng(allMapPoints.First().Lat, allMapPoints.First().Lng))); overlay.Markers.Add(new GMap.NET.WindowsForms.Markers.GMapMarkerGoogleRed(new PointLatLng(allMapPoints.Last().Lat, allMapPoints.Last().Lng))); } overlay.Routes.Add(route); map.Overlays.Add(overlay); }
void BuildRoute() { if (markersOverlay.Markers.Count > 0) { List<PointLatLng> points = new List<PointLatLng>(); for (int i = 0; i < markersOverlay.Markers.Count; i++) { points.Add(markersOverlay.Markers[i].Position); } GMapRoute route = new GMapRoute(points, "myRoute"); routeOverlay.Routes.Clear(); routeOverlay.Routes.Add(route); MainMap.Overlays.Add(routeOverlay); MainMap.UpdateRouteLocalPosition(route); } }
public static void Build(ref GMapOverlay OverlayOut) { // Here loop through defined state borders and display them on the map foreach (SystemAdaptationDataSet.StateBorder State in SystemAdaptationDataSet.StateBorderDataSet) { System.Collections.Generic.List<PointLatLng> SectorPointList = new System.Collections.Generic.List<PointLatLng>(); foreach (GeoCordSystemDegMinSecUtilities.LatLongClass SectorPoint in State.StateBorderPoints) { SectorPointList.Add(new PointLatLng(SectorPoint.GetLatLongDecimal().LatitudeDecimal, SectorPoint.GetLatLongDecimal().LongitudeDecimal)); } GMapRoute StateBoundaryData = new GMapRoute(SectorPointList, State.StateName); StateBoundaryData.Stroke.Width = DisplayAttributes.GetDisplayAttribute(DisplayAttributes.DisplayItemsType.StateBorder).LineWidth; StateBoundaryData.Stroke.DashStyle = DisplayAttributes.GetDisplayAttribute(DisplayAttributes.DisplayItemsType.StateBorder).LineStyle; StateBoundaryData.Stroke.Color = DisplayAttributes.GetDisplayAttribute(DisplayAttributes.DisplayItemsType.StateBorder).LineColor; OverlayOut.Routes.Add(StateBoundaryData); } }
void refreshRoute() { List<PointLatLng> linePoints = new List<PointLatLng>(); foreach (GMapMarker m in routes.Markers) { m.Tag = linePoints.Count; linePoints.Add(m.Position); m.ToolTipMode = MarkerTooltipMode.Never; } if (routes.Markers.Count > 1) { routes.Markers[routes.Markers.Count - 1].ToolTipMode = MarkerTooltipMode.Always; } if (linePoints.Count > 0) { GMapRoute route = new GMapRoute(linePoints, "distance"); route.Stroke.Width = 4; routes.Routes.Clear(); routes.Routes.Add(route); } }
public void AddRoute(List<PointLatLng> route) { // add route GMapRoute r = new GMapRoute(route, "test"); routes.Routes.Add(r); //// add route start/end marks //GMapMarker m1 = new GMapMarkerGoogleRed(start); //m1.ToolTipText = "Start: " + start.ToString(); //m1.TooltipMode = MarkerTooltipMode.Always; //GMapMarker m2 = new GMapMarkerGoogleGreen(end); //m2.ToolTipText = "End: " + end.ToString(); //m2.TooltipMode = MarkerTooltipMode.Always; //objects.Markers.Add(m1); //objects.Markers.Add(m2); MainMap.ZoomAndCenterRoute(r); }
private void destinationMenuItem_Click(object sender, EventArgs e) { GMarkerGoogle marker = new GMarkerGoogle(gPoint, GMarkerGoogleType.red); markers.Markers.Add(marker); PointLatLng start = new PointLatLng(markers.Markers[0].Position.Lat, markers.Markers[0].Position.Lng); PointLatLng end = new PointLatLng(markers.Markers[1].Position.Lat, markers.Markers[1].Position.Lng); MapRoute route = GMap.NET.MapProviders.GoogleMapProvider.Instance.GetRoute( start, end, false, false, 14 ); GMapRoute r = new GMapRoute(route.Points, "My route"); GMapOverlay routesOverlay = new GMapOverlay("routes"); routesOverlay.Routes.Add(r); myMap.Overlays.Add(routesOverlay); // Térkép frissítése a route felrakása után, különben csak egy zoomolás után látszik a route. myMap.UpdateRouteLocalPosition(r); myMap.Invalidate(); }
public void AddRoute(MapRoute MapRoute, GMapRoute Route, Color RouteColor) { AddRoute((int)MapRoute, Route, RouteColor); }
private void drawObject(xObject x) { xObGroup obGr = _Dh.getGroupById(x.ObGroupId); GMapOverlay ov = _Dh.getOverlay(TheMap, obGr); switch (obGr.GroupType) { case ObjectType.DOT: GMarkerGoogle marker = null; PointLatLng point = x.Coordinates[0]; if (obGr.Appendix.Length > 5) { Bitmap bmp; using (var ms = new MemoryStream(Convert.FromBase64String(obGr.Appendix))) { bmp = new Bitmap(ms); } marker = new GMarkerGoogle(point, bmp); } else { marker = new GMarkerGoogle(point, GMarkerGoogleType.green); } MarkerTooltipMode mode = MarkerTooltipMode.Always; marker.ToolTip = new GMapBaloonToolTip(marker); marker.ToolTipMode = mode; Brush ToolTipBackColor = new SolidBrush(Color.Transparent); marker.ToolTipText = x.Name; x.Marker = marker; ov.Markers.Add(x.Marker); TheMap.UpdateMarkerLocalPosition(x.Marker); break; case ObjectType.ROUTE: GMapRoute route = new GMapRoute(x.Coordinates, x.Name); route.Stroke = obGr.Pen; route.IsHitTestVisible = true; x.Marker = new GMarkerGoogle(route.Points[0], new Bitmap(1, 1)) { Tag = x.Name, IsVisible = false, ToolTipMode = MarkerTooltipMode.Always, ToolTipText = x.Name }; x.Route = route; ov.Routes.Add(x.Route); x.Route.Overlay.Markers.Add(x.Marker); break; case ObjectType.POLYGON: var polygon = new GMapPolygon(x.Coordinates, x.Name); polygon.Fill = new SolidBrush(Color.FromArgb(50, obGr.Pen.Color)); polygon.Stroke = obGr.Pen; polygon.IsHitTestVisible = true; x.Marker = new GMarkerGoogle(polygon.Points[0], new Bitmap(1, 1)) { Tag = x.Name, IsVisible = false, ToolTipMode = MarkerTooltipMode.Always, ToolTipText = x.Name }; x.Polygon = polygon; ov.Polygons.Add(x.Polygon); x.Polygon.Overlay.Markers.Add(x.Marker); break; } }
private void LoadTracksForDriver(int driverId) { tracksOverlay.Clear(); tracksDistance.Clear(); //Load tracks var driverRow = (yTreeViewDrivers.RepresentationModel.ItemsList as IList <Vodovoz.ViewModel.WorkingDriverVMNode>).FirstOrDefault(x => x.Id == driverId); int colorIter = 0; foreach (var routeId in driverRow.RouteListsIds) { var pointList = _trackRepository.GetPointsForRouteList(uow, routeId.Key); if (pointList.Count == 0) { continue; } var points = pointList.Select(p => new PointLatLng(p.Latitude, p.Longitude)); var route = new GMapRoute(points, routeId.ToString()); route.Stroke = new System.Drawing.Pen(GetTrackColor(colorIter)); colorIter++; route.Stroke.Width = 4; route.Stroke.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; tracksDistance.Add(MakeDistanceLayout(route)); tracksOverlay.Routes.Add(route); } //LoadAddresses foreach (var point in yTreeAddresses.RepresentationModel.ItemsList as IList <DriverRouteListAddressVMNode> ) { if (point.Address == null) { logger.Warn("Для заказа №{0}, отсутствует точка доставки. Поэтому добавление маркера пропущено.", point.OrderId); continue; } if (point.Address.Latitude.HasValue && point.Address.Longitude.HasValue) { GMarkerGoogleType type; switch (point.Status) { case RouteListItemStatus.Completed: type = GMarkerGoogleType.green_small; break; case RouteListItemStatus.EnRoute: type = GMarkerGoogleType.gray_small; break; case RouteListItemStatus.Canceled: type = GMarkerGoogleType.purple_small; break; case RouteListItemStatus.Overdue: type = GMarkerGoogleType.red_small; break; default: type = GMarkerGoogleType.none; break; } var addressMarker = new GMarkerGoogle(new PointLatLng((double)point.Address.Latitude, (double)point.Address.Longitude), type); addressMarker.ToolTipText = $"{point.Address.ShortAddress}\nВремя доставки: {point.Time?.Name ?? "Не назначено"}"; tracksOverlay.Markers.Add(addressMarker); } } buttonCleanTrack.Sensitive = true; }
public void ReDrawgMap() { string lat, lon, poiname; PointLatLng center_position = _mapcontrol.Position; //_markers.Clear(); _mapcontrol.Overlays.Clear(); _mapcontrol.Position = center_position; //_mapcontrol.ShowCenter = false; _overmarkers = new GMapOverlay("markers"); _overroutes = new GMapOverlay("routes"); _overpolys = new GMapOverlay("polygons"); _mapcontrol.Overlays.Add(_overmarkers); _mapcontrol.Overlays.Add(_overroutes); _mapcontrol.Overlays.Add(_overpolys); // Map POI int poicount = _wpg.POICount(); for (int i = 0; i < poicount; i++) { GMapMarker marker; POIPoints pnt = _wpg.POIPointAt(i); poiname = pnt.name; //if (i == 0) _mapcontrol.Position = new global::GMap.NET.PointLatLng(pnt.lat, pnt.lon); if (pnt.selected) { marker = new GMarkerGoogle(new PointLatLng(pnt.lat, pnt.lon), _poi_selected_image); } else { marker = new GMarkerGoogle(new PointLatLng(pnt.lat, pnt.lon), _poi_image); } //GMarkerGoogleType.blue_pushpin); marker.Offset = new Point(-16, -16); marker.ToolTipText = poiname; marker.Tag = poiname; marker.IsVisible = pnt.visible; //marker.IsVisible = true; marker.IsHitTestVisible = true; _overmarkers.Markers.Add(marker); } // Map Path int pathcount = _wpg.PathCount(); for (int i = 0; i < pathcount; i++) { Models.Path path = _wpg.PathAt(i); bool path_visible = path.visible; bool path_selected = path.selected; string name = path.name; LinkedList <WayPoints> wplist = path.waypoints; if (wplist != null) { int wpcount = wplist.Count; List <PointLatLng> points = new List <PointLatLng>(); int count = 0; foreach (WayPoints wp in wplist) { points.Add(new PointLatLng(wp.lat, wp.lon)); GMapMarker marker; if (path_selected | wp.selected) { _drone_image = _drone_image_selected; _drone_image = RotateImage(_drone_image_selected, wp.head); marker = new GMarkerGoogle(new PointLatLng(wp.lat, wp.lon), _drone_image); //GMarkerGoogleType.red_pushpin); } else { _drone_image = _drone_image_notselected; _drone_image = RotateImage(_drone_image_notselected, wp.head); marker = new GMarkerGoogle(new PointLatLng(wp.lat, wp.lon), _drone_image); //GMarkerGoogleType.blue_pushpin); } //marker.Size = new Size(64,64); marker.Offset = new Point(-16, -16); marker.Tag = Convert.ToString(i) + "." + Convert.ToString(count); marker.IsVisible = path_visible; marker.ToolTipText = "WP(" + Convert.ToString(count) + ") - Alt:" + Convert.ToString(wp.alt); _overmarkers.Markers.Add(marker); GMAPWPMarker wpmarker = new GMAPWPMarker(); wpmarker.path = i; wpmarker.wp = count; wpmarker.marker = marker; wpmarker.selected = wp.selected; _markers.Add(wpmarker); count++; } GMapRoute route = new GMapRoute(points, name); route.Stroke = new Pen(Color.Blue, 2); route.Tag = i; route.IsVisible = path_visible; route.IsHitTestVisible = true; _overroutes.Routes.Add(route); } //gMap.Overlays.Add(overroutes); //gMap.Overlays.Add(markers); } //gMap.Overlays.Add(markers); // Map Polygon int polycount = _wpg.ShapeCount(); for (int i = 0; i < polycount; i++) { Models.Shape polyshape = _wpg.ShapeAt(i); string name = polyshape.name; LinkedList <PolyPoint> wplist = polyshape.points; int wpcount = wplist.Count; List <PointLatLng> points = new List <PointLatLng>(); foreach (PolyPoint wp in wplist) { points.Add(new PointLatLng(wp.lat, wp.lon)); } GMapPolygon poly = new GMapPolygon(points, name); if (polyshape.selected) { poly.Stroke = new Pen(Color.Red, 1); } else { poly.Stroke = new Pen(Color.Yellow, 1); } poly.Fill = new SolidBrush(Color.FromArgb(25, Color.Yellow)); poly.Tag = polyshape.name; poly.IsVisible = polyshape.visible; poly.IsHitTestVisible = true; _overpolys.Polygons.Add(poly); } _mapcontrol.Position = center_position; }
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { marcadores.Clear(); int index = dataRutas.CurrentRow.Index; Servicio temporal = user.ServiciosRegistrados[index]; if (temporal.TipoServ.Equals(Servicio.SERVICIO_DE_COMPRA)) { String[] inicio = temporal.Partida.Split('*'); double i1 = Double.Parse(inicio[0]); double i2 = Double.Parse(inicio[1]); string[] fin = temporal.Destino.Split('*'); double f1 = Double.Parse(fin[0]); double f2 = Double.Parse(fin[1]); PointLatLng start = new PointLatLng(i1, i2); PointLatLng end = new PointLatLng(f1, f2); GMapMarker partida; partida = new GMarkerGoogle(start, GMarkerGoogleType.red); partida.ToolTipText = "Partida"; partida.ToolTipMode = MarkerTooltipMode.Always; marcadores.Markers.Add(partida); GMapMarker destino; destino = new GMarkerGoogle(end, GMarkerGoogleType.red); destino.ToolTipText = "Destino"; destino.ToolTipMode = MarkerTooltipMode.Always; marcadores.Markers.Add(destino); gMapRutas.Overlays.Add(marcadores); gMapRutas.Refresh(); gMapRutas.ReloadMap(); } else { if (temporal.Ruta == null) { generarRuta(temporal.Partida, temporal.Destino); } else { GMapRoute ruta = temporal.Ruta; String[] inicio = temporal.Partida.Split('*'); double i1 = Double.Parse(inicio[0]); double i2 = Double.Parse(inicio[1]); string[] fin = temporal.Destino.Split('*'); double f1 = Double.Parse(fin[0]); double f2 = Double.Parse(fin[1]); PointLatLng start = new PointLatLng(i1, i2); PointLatLng end = new PointLatLng(f1, f2); GMapMarker partida; partida = new GMarkerGoogle(start, GMarkerGoogleType.red); partida.ToolTipText = "Partida"; partida.ToolTipMode = MarkerTooltipMode.Always; marcadores.Markers.Add(partida); GMapMarker destino; destino = new GMarkerGoogle(end, GMarkerGoogleType.red); destino.ToolTipText = "Destino"; destino.ToolTipMode = MarkerTooltipMode.Always; marcadores.Markers.Add(destino); marcadores.Routes.Add(ruta); gMapRutas.Overlays.Add(marcadores); gMapRutas.ZoomAndCenterRoute(ruta); gMapRutas.ReloadMap(); } } }
public void importShapeCallback(string path, string layer, Color color) { Bitmap bitmap = null; ShapeReader shape = new ShapeReader(path); GMapOverlay overlay = new GMapOverlay(layer); gMap.Overlays.Add(overlay); shape.errorHandler += errorHandlerCallback; shape.read(); ESRIShapeFile s = shape.getShape(); if (s.ShapeType == 3 || s.ShapeType == 13) { GMapRoute line_layer; PolyLineZ[] polyLines = s.PolyLineZ; foreach (PolyLineZ polyLine in polyLines) { PointLatLng[] points = polyLine.points; line_layer = new GMapRoute(points, "lines"); //TODO get carriage number line_layer.Stroke = new Pen(color, 1); overlay.Routes.Add(line_layer); } } else if (s.ShapeType == 1) { ShapeFile.Point[] points = s.Point; bitmap = ColorTable.getBitmap(ColorTable.ColorCrossDict, color.Name, 4); int id = 0; foreach (ShapeFile.Point point in points) { PointLatLng pointLatLng = new PointLatLng(point.y, point.x); MarkerTag tag = new MarkerTag(color.Name, id); tag.Dictionary = ColorTable.ColorCrossDict; GMapMarker marker = new GMarkerGoogle(pointLatLng, bitmap); marker.Tag = tag; overlay.Markers.Add(marker); id++; } GMapMarker[] markersArr = overlay.Markers.ToArray <GMapMarker>(); mOverlayDict.Add(layer, markersArr); } else if (s.ShapeType == 8) { MultiPoint[] points = s.MultiPoint; bitmap = ColorTable.getBitmap(ColorTable.ColorCrossDict, color.Name, 4); int id = 0; foreach (MultiPoint point in points) { PointLatLng[] pointsLatLng = point.points; foreach (PointLatLng p in pointsLatLng) { MarkerTag tag = new MarkerTag(color.Name, id); tag.Dictionary = ColorTable.ColorCrossDict; GMapMarker marker = new GMarkerGoogle(p, bitmap); marker.Tag = tag; overlay.Markers.Add(marker); id++; } } GMapMarker[] markersArr = overlay.Markers.ToArray <GMapMarker>(); mOverlayDict.Add(layer, markersArr); } addListItem(ColorTable.ColorCrossDict, overlay, color.Name); //if (bitmap != null) //{ // imageList.Images.Add(bitmap); //} //ListViewItem layerItem = new ListViewItem(overlay.Id, layerCount); //layerCount++; //layerItem.Text = overlay.Id; //layerItem.Checked = true; //mOverlay = overlay; //listLayers.SmallImageList = imageList; //listLayers.Items.Add(layerItem); ////addListItem(ColorTable.ColorCrossDict, overlay, color.Name); //overlay.IsVisibile = true; //mOverlay.IsVisibile = true; ////shape.readDBF(); }
void DrawMap() { try { DateTime starttime = DateTime.MinValue; DateTime workingtime = starttime; DateTime lastdrawn = DateTime.MinValue; List<PointLatLng> routelist = new List<PointLatLng>(); //zg1.GraphPane.GraphObjList.Clear(); foreach (var item in logdata) { if (item.msgtype == "GPS") { var ans = getPointLatLng(item); if (ans.HasValue) { routelist.Add(ans.Value); } } } mapoverlay.Routes.Clear(); GMapRoute route = new GMapRoute(routelist, "route"); mapoverlay.Routes.Add(route); myGMAP1.ZoomAndCenterRoute(route); myGMAP1.RoutesEnabled = true; } catch (Exception ex) { log.Error(ex); } }
private void MapControl_OnRouteClick(GMapRoute item, MouseEventArgs e) { CustomMessageBox.Show(createMessage(item.Tag), "Info", MessageBoxButtons.OK); }
private void MapControl_OnRouteLeave(GMapRoute item) { item.Overlay.Markers.Remove(marker); marker = null; }
/// <summary> /// Plot the series. This will remove all the old series. Then add the /// new series lines. /// </summary> /// <param name="stData">Ship Track data.</param> private void PlotMapData(List <ShipTrackData> stDataList) { // Init the value double avgMag = 0.0; double avgDir = 0.0; // Keep Track of previous point to draw // the ship track line //LatLon prevLatLon = new LatLon { Latitude = 0.0, Longitude = 0.0, IsGood = false }; IList <PointLatLng> points = new List <PointLatLng>(); // Last point ShipTrackData lastGoodShipTrack = null; foreach (ShipTrackData stData in stDataList) { avgMag = stData.VelMagDir.AvgMagnitude; avgDir = stData.VelMagDir.AvgDirectionYNorth; LatLon currLatLon = stData.GetLatLon(); if (currLatLon.IsGood) { // Add the point to the route points.Add(new PointLatLng(currLatLon.Latitude, currLatLon.Longitude)); // Convert the value to color from the color map System.Windows.Media.SolidColorBrush brush = new System.Windows.Media.SolidColorBrush(ColorHM.GetColorForValue(avgMag, _MinValue, _MaxValue)); // Mark GMapMarker marker = new GMapMarker(new GMap.NET.PointLatLng(currLatLon.Latitude, currLatLon.Longitude)); //System.Windows.Media.BrushConverter converter = new System.Windows.Media.BrushConverter(); if (_SelectedPlotOption == PLOT_OPTION_QUIVER) { // Degrees to radian double angle = Math.PI * avgDir / 180.0; marker.Shape = new Line { X1 = 0, Y1 = 0, X2 = (Math.Abs(avgMag) * MagScale) * Math.Cos(angle), Y2 = -((Math.Abs(avgMag) * MagScale) * Math.Sin(angle)), // Flip the sign StrokeThickness = 3, Stroke = brush, ToolTip = string.Format("[{0}] [{1}] Mag: {2} Dir: {3} Range: {4} Heading: {5}", stData.EnsNum, stData.DateTime, avgMag.ToString("0.0"), avgDir.ToString("0.0"), stData.AvgRange.ToString("0.0"), stData.Heading.ToString("0.0")), Name = string.Format("Line_{0}", stData.EnsNum) }; marker.ZIndex = (int)MapLayers.Quiver; } else if (_SelectedPlotOption == PLOT_OPTION_VELOCITY_RECTANGLE) { marker.Shape = new Rectangle { Width = 20 * MagScale, Height = 20 * MagScale, Fill = brush, Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Transparent), ToolTip = string.Format("[{0}] [{1}] Mag: {2} Dir: {3} Range: {4} Heading: {5}", stData.EnsNum, stData.DateTime, avgMag.ToString("0.0"), avgDir.ToString("0.0"), stData.AvgRange.ToString("0.0"), stData.Heading.ToString("0.0")), Name = string.Format("Rect_Vel_{0}", stData.EnsNum) }; marker.ZIndex = (int)MapLayers.Velocity_Rectangle; } else if (_SelectedPlotOption == PLOT_OPTION_BT_RANGE) { // Convert the average Range to color from the color map brush = new System.Windows.Media.SolidColorBrush(ColorHM.GetColorForValue(stData.AvgRange, _MinValue, _MaxValue)); marker.Shape = new Rectangle { Width = 20 * MagScale, Height = 20 * MagScale, Fill = brush, Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Transparent), ToolTip = string.Format("[{0}] [{1}] Mag: {2} Dir: {3} Range: {4} Heading: {5}", stData.EnsNum, stData.DateTime, avgMag.ToString("0.0"), avgDir.ToString("0.0"), stData.AvgRange.ToString("0.0"), stData.Heading.ToString("0.0")), Name = string.Format("Rect_Range_{0}", stData.EnsNum) }; marker.ZIndex = (int)MapLayers.Range_Rectangle; } // Record the last point to get a special marker lastGoodShipTrack = stData; // Add the marker to the list Markers.Add(marker); } } // Plot the path that we taken GMapRoute route = new GMapRoute(points); System.Windows.Media.SolidColorBrush routeBrush = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red); routeBrush.Opacity = 0.4; route.Shape = new System.Windows.Shapes.Path() { StrokeThickness = 3, Stroke = routeBrush, Fill = routeBrush }; route.ZIndex = (int)MapLayers.Ship_Track_Line; Markers.Add(route); // Add a marker for the last point to know which direction it traveled if (lastGoodShipTrack != null) { LatLon lastLatLon = lastGoodShipTrack.GetLatLon(); if (lastLatLon.IsGood) { GMapMarker lastMarker = new GMapMarker(new GMap.NET.PointLatLng(lastLatLon.Latitude, lastLatLon.Longitude)); if (IsLastMarkerEllipse) { lastMarker.Shape = new Ellipse { //Points = trianglePts, RenderTransform = new System.Windows.Media.TranslateTransform(-((1 * LastMarkerScale) / 2), -((1 * LastMarkerScale) / 2)), Width = 1 * LastMarkerScale, Height = 1 * LastMarkerScale, Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Yellow), Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red), ToolTip = string.Format("[{0}] [{1}] Mag: {2} Dir: {3} Range: {4} Heading: {5}", lastGoodShipTrack.EnsNum, lastGoodShipTrack.DateTime, avgMag.ToString("0.0"), avgDir.ToString("0.0"), lastGoodShipTrack.AvgRange.ToString("0.0"), lastGoodShipTrack.Heading.ToString("0.0")) }; } else { System.Windows.Media.PointCollection trianglePts = new System.Windows.Media.PointCollection(); //trianglePts.Add(new Point(0.0, 1.0 * LastMarkerScale)); //trianglePts.Add(new Point(0.0, -1.0 * LastMarkerScale)); //trianglePts.Add(new Point(-1.0 * LastMarkerScale, 0.0)); trianglePts.Add(new Point(-1.0 * LastMarkerScale, 0.0)); trianglePts.Add(new Point(1.0 * LastMarkerScale, 0.0)); trianglePts.Add(new Point(0.0, -1.0 * LastMarkerScale)); lastMarker.Shape = new Polygon { Points = trianglePts, RenderTransform = new System.Windows.Media.RotateTransform(lastGoodShipTrack.Heading), Fill = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Yellow), Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Red), ToolTip = string.Format("[{0}] [{1}] Mag: {2} Dir: {3} Range: {4} Heading: {5}", lastGoodShipTrack.EnsNum, lastGoodShipTrack.DateTime, avgMag.ToString("0.0"), avgDir.ToString("0.0"), lastGoodShipTrack.AvgRange.ToString("0.0"), lastGoodShipTrack.Heading.ToString("0.0")) }; } // Set the zIndex so we can filter the layers lastMarker.ZIndex = (int)MapLayers.Last_Point; // Add the last point to the end Markers.Add(lastMarker); } } // Set the center position Position = GetCenterPoint(Markers); Zoom = 17; }
private void MainMap_OnRouteEnter(GMapRoute item) { item.Stroke.Color = Color.Red; }
private void MainMap_OnRouteLeave(GMapRoute item) { item.Stroke.Color = Color.MidnightBlue; }
private void mainloop() { //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); //System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); threadrun = 1; EndPoint Remote = (EndPoint)(new IPEndPoint(IPAddress.Any, 0)); DateTime lastdata = DateTime.MinValue; DateTime tracklast = DateTime.Now.AddSeconds(0); DateTime tunning = DateTime.Now.AddSeconds(0); DateTime mapupdate = DateTime.Now.AddSeconds(0); DateTime vidrec = DateTime.Now.AddSeconds(0); DateTime waypoints = DateTime.Now.AddSeconds(0); DateTime updatescreen = DateTime.Now; DateTime tsreal = DateTime.Now; //comPort.stopall(true); while (threadrun == 1) { if (threadrun == 0) { return; } if (MainV2.comPort.giveComport == true) { System.Threading.Thread.Sleep(50); continue; } if (!MainV2.comPort.BaseStream.IsOpen) { lastdata = DateTime.Now; continue; } // actauly read the packets while (MainV2.comPort.BaseStream.BytesToRead > 0 && MainV2.comPort.giveComport == false) { try { MainV2.comPort.readPacket(); } catch { } } // re-request servo data if (!(lastdata.AddSeconds(8) > DateTime.Now) && MainV2.comPort.BaseStream.IsOpen) { //Console.WriteLine("REQ streams - flightdata"); try { //System.Threading.Thread.Sleep(1000); //comPort.requestDatastream((byte)ArdupilotMega.MAVLink09.MAV_DATA_STREAM.RAW_CONTROLLER, 0); // request servoout MainV2.comPort.requestDatastream(ArdupilotMega.MAVLink.MAV_DATA_STREAM.EXTENDED_STATUS, MainV2.comPort.MAV.cs.ratestatus); // mode MainV2.comPort.requestDatastream(ArdupilotMega.MAVLink.MAV_DATA_STREAM.POSITION, MainV2.comPort.MAV.cs.rateposition); // request gps MainV2.comPort.requestDatastream(ArdupilotMega.MAVLink.MAV_DATA_STREAM.EXTRA1, MainV2.comPort.MAV.cs.rateattitude); // request attitude MainV2.comPort.requestDatastream(ArdupilotMega.MAVLink.MAV_DATA_STREAM.EXTRA2, MainV2.comPort.MAV.cs.rateattitude); // request vfr MainV2.comPort.requestDatastream(ArdupilotMega.MAVLink.MAV_DATA_STREAM.EXTRA3, MainV2.comPort.MAV.cs.ratesensors); // request extra stuff - tridge MainV2.comPort.requestDatastream(ArdupilotMega.MAVLink.MAV_DATA_STREAM.RAW_SENSORS, MainV2.comPort.MAV.cs.ratesensors); // request raw sensor MainV2.comPort.requestDatastream(ArdupilotMega.MAVLink.MAV_DATA_STREAM.RC_CHANNELS, MainV2.comPort.MAV.cs.raterc); // request rc info } catch { log.Error("Failed to request rates"); } lastdata = DateTime.Now.AddSeconds(120); // prevent flooding } if (!MainV2.comPort.logreadmode) System.Threading.Thread.Sleep(100); // max is only ever 10 hz try { //Console.WriteLine(DateTime.Now.Millisecond); updateBindingSource(); // Console.WriteLine(DateTime.Now.Millisecond + " done "); // battery warning. float warnvolt = 0; float.TryParse(MainV2.getConfig("speechbatteryvolt"), out warnvolt); float warnpercent = 0; float.TryParse(MainV2.getConfig("speechbatterypercent"), out warnpercent); if (ArdupilotMega.Controls.OpenGLtest.instance != null) { ArdupilotMega.Controls.OpenGLtest.instance.rpy = new OpenTK.Vector3(MainV2.comPort.MAV.cs.roll, MainV2.comPort.MAV.cs.pitch, MainV2.comPort.MAV.cs.yaw); ArdupilotMega.Controls.OpenGLtest.instance.LocationCenter = new PointLatLngAlt(MainV2.comPort.MAV.cs.lat, MainV2.comPort.MAV.cs.lng, MainV2.comPort.MAV.cs.alt, "here"); } if (tunning.AddMilliseconds(50) < DateTime.Now && CB_tuning.Checked == true) { double time = (Environment.TickCount - tickStart) / 1000.0; if (list1item != null) list1.Add(time, (float)list1item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list2item != null) list2.Add(time, (float)list2item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list3item != null) list3.Add(time, (float)list3item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list4item != null) list4.Add(time, (float)list4item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list5item != null) list5.Add(time, (float)list5item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list6item != null) list6.Add(time, (float)list6item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list7item != null) list7.Add(time, (float)list7item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list8item != null) list8.Add(time, (float)list8item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list9item != null) list9.Add(time, (float)list9item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list10item != null) list10.Add(time, (float)list10item.GetValue((object)MainV2.comPort.MAV.cs, null)); } if (tracklast.AddSeconds(1) < DateTime.Now) { if (MainV2.config["CHK_maprotation"] != null && MainV2.config["CHK_maprotation"].ToString() == "True") { // dont holdinvalidation here setMapBearing(); } if (route == null) { route = new GMapRoute(trackPoints, "track"); routes.Routes.Add(route); } PointLatLng currentloc = new PointLatLng(MainV2.comPort.MAV.cs.lat, MainV2.comPort.MAV.cs.lng); gMapControl1.HoldInvalidation = true; int cnt = 0; while (gMapControl1.inOnPaint == true) { System.Threading.Thread.Sleep(1); cnt++; } while (route.Points.Count > 200) { // trackPoints.RemoveRange(0, trackPoints.Count - int.Parse(MainV2.config["NUM_tracklength"].ToString())); route.Points.RemoveAt(0); } if (MainV2.comPort.MAV.cs.lat != 0) { // trackPoints.Add(currentloc); route.Points.Add(currentloc); } // if (CB_tuning.Checked == false) // draw if in view { while (gMapControl1.inOnPaint == true) { System.Threading.Thread.Sleep(1); } //route = new GMapRoute(route.Points, "track"); //track.Stroke = Pens.Red; //route.Stroke = new Pen(Color.FromArgb(144, Color.Red)); //route.Stroke.Width = 5; //route.Tag = "track"; //updateClearRoutes(); gMapControl1.UpdateRouteLocalPosition(route); if (waypoints.AddSeconds(10) < DateTime.Now) { //Console.WriteLine("Doing FD WP's"); updateMissionRouteMarkers(); foreach (MAVLink.mavlink_mission_item_t plla in MainV2.comPort.MAV.wps.Values) { if (plla.x == 0 || plla.y == 0) continue; if (plla.command == (byte)MAVLink.MAV_CMD.DO_SET_ROI) { addpolygonmarkerred(plla.seq.ToString(), plla.y, plla.x, (int)plla.z, Color.Red, routes); continue; } string tag = plla.seq.ToString(); if (plla.seq == 0 && plla.current != 2) { tag = "Home"; } if (plla.current == 2) { continue; } addpolygonmarker(tag, plla.y, plla.x, (int)plla.z, Color.White, polygons); } RegeneratePolygon(); waypoints = DateTime.Now; } //routes.Polygons.Add(poly); if (route.Points.Count > 0) { // add primary route icon if (routes.Markers.Count != 1) { routes.Markers.Clear(); routes.Markers.Add(new GMapMarkerCross(currentloc)); } if (MainV2.comPort.MAV.cs.mode.ToLower() == "guided" && MainV2.comPort.MAV.GuidedMode.x != 0) { addpolygonmarker("Guided Mode", MainV2.comPort.MAV.GuidedMode.y, MainV2.comPort.MAV.GuidedMode.x, (int)MainV2.comPort.MAV.GuidedMode.z, Color.Blue, routes); } if (MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.ArduPlane || MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.Ateryx) { routes.Markers[0] = (new GMapMarkerPlane(currentloc, MainV2.comPort.MAV.cs.yaw, MainV2.comPort.MAV.cs.groundcourse, MainV2.comPort.MAV.cs.nav_bearing, MainV2.comPort.MAV.cs.target_bearing, gMapControl1) { ToolTipText = MainV2.comPort.MAV.cs.mode + "\n" + MainV2.comPort.MAV.cs.alt.ToString("alt 0") + "\n" + MainV2.comPort.MAV.cs.groundspeed.ToString("gs 0"), ToolTipMode = MarkerTooltipMode.Always }); } else if (MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.ArduRover) { routes.Markers[0] = (new GMapMarkerRover(currentloc, MainV2.comPort.MAV.cs.yaw, MainV2.comPort.MAV.cs.groundcourse, MainV2.comPort.MAV.cs.nav_bearing, MainV2.comPort.MAV.cs.target_bearing, gMapControl1)); } else { routes.Markers[0] = (new GMapMarkerQuad(currentloc, MainV2.comPort.MAV.cs.yaw, MainV2.comPort.MAV.cs.groundcourse, MainV2.comPort.MAV.cs.nav_bearing) { ToolTipText = MainV2.comPort.MAV.cs.mode + "\n" + "alt " + MainV2.comPort.MAV.cs.alt.ToString("0") + "\ngs " + MainV2.comPort.MAV.cs.groundspeed.ToString("0"), ToolTipMode = MarkerTooltipMode.Always }); } if (route.Points[route.Points.Count - 1].Lat != 0 && (mapupdate.AddSeconds(3) < DateTime.Now) && CHK_autopan.Checked) { updateMapPosition(currentloc); mapupdate = DateTime.Now; } if (route.Points.Count == 1 && gMapControl1.Zoom == 3) // 3 is the default load zoom { updateMapPosition(currentloc); updateMapZoom(17); //gMapControl1.ZoomAndCenterMarkers("routes");// ZoomAndCenterRoutes("routes"); } } gMapControl1.HoldInvalidation = false; gMapControl1.Invalidate(); } tracklast = DateTime.Now; } } catch (Exception ex) { Console.WriteLine("FD Main loop exception " + ex.ToString()); } } Console.WriteLine("FD Main loop exit"); }
public Form1() { InitializeComponent(); init_config(); //kay_chart = new kayChart(chart2, 20); chart1.ChartAreas[0].CursorX.IsUserEnabled = true; chart1.ChartAreas[0].CursorX.AutoScroll = true; chart1.ChartAreas[0].AxisX.ScaleView.Zoomable = true; chart1.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true; chart1.ChartAreas[0].AxisX.Maximum = X_RANGE; chart1.ChartAreas[0].AxisX.Minimum = 0; dictionary = new Dictionary <float, RootObject>(); dictionary_marker = new Dictionary <float, GMarkerGoogle>(); carId_to_chart_index_mapper = new Dictionary <float, int>(); carId_speed_mapper = new Dictionary <float, double>(); gmap.MapProvider = GMapProviders.GoogleChinaSatelliteMap; //listBox1.ValueMember = "Key"; //listBox1.DisplayMember = "Value"; carId_speed_mapper.Add(100, 24); //listBox1.DataSource = new BindingSource(carId_speed_mapper, null); // Jervy gym RSU locaiton : 34.678986, -82.847704 // C1 parking lot locaiton : 34.671500, -82.830270 // R2 parking lot : 34.675912, -82.823168 // ADD rsu of Jervy Gym GMapOverlay markersOverlay = new GMapOverlay("markers"); //PointLatLng point = new PointLatLng(34.678986, -82.847704); //GMapMarker marker = new GMapPoint(point, 150); //GMarkerGoogle marker = new GMarkerGoogle(new GMapPoint(point,10), new Bitmap(Properties.Resources.radio_station_2)); //GMarkerGoogle marker = new GMarkerGoogle(new PointLatLng(34.678986, -82.847704), new Bitmap(Properties.Resources.radio_station_2)); //GMarkerGoogle marker = new GMarkerGoogle(new PointLatLng(root.latitude, root.longitude), GMarkerGoogleType.green); //markersOverlay.Markers.Add(marker); // gmap.Overlays.Add(markersOverlay); //marker.ToolTipMode = MarkerTooltipMode.Always; Bitmap rsu_marker = new Bitmap(Properties.Resources.rsu_station_2); GMarkerGoogle j1_marker = new GMarkerGoogle(new PointLatLng(34.678986, -82.847704), rsu_marker); markersOverlay.Markers.Add(j1_marker); gmap.Overlays.Add(markersOverlay); //GMarkerGoogle marker = new GMarkerGoogle(new PointLatLng(root.latitude, root.longitude), GMarkerGoogleType.green); GMarkerGoogle c1_rsu = new GMarkerGoogle(new PointLatLng(34.671500, -82.830270), rsu_marker); markersOverlay.Markers.Add(c1_rsu); gmap.Overlays.Add(markersOverlay); c1_rsu.ToolTipMode = MarkerTooltipMode.Always; GMarkerGoogle r1_rsu = new GMarkerGoogle(new PointLatLng(34.675912, -82.823168), rsu_marker); markersOverlay.Markers.Add(r1_rsu); gmap.Overlays.Add(markersOverlay); r1_rsu.ToolTipMode = MarkerTooltipMode.Always; PointLatLng p1 = new PointLatLng(34.681877, -82.847935); PointLatLng p2 = new PointLatLng(34.670933, -82.835487); //MapRoute route = GoogleMapProvider.Instance.GetRoute(start, end, false, false, 15); MapRoute route = OpenStreetMapProvider.Instance.GetRoute(p1, p2, false, false, 15); GMapRoute r1 = new GMapRoute(route.Points, "My route"); r1.Stroke.Width = 2; r1.Stroke.Color = Color.Orange; GMapOverlay routesOverlay1 = new GMapOverlay("routes"); routesOverlay1.Routes.Add(r1); gmap.Overlays.Add(routesOverlay1); PointLatLng p3 = new PointLatLng(34.678001, -82.818037); //MapRoute route = GoogleMapProvider.Instance.GetRoute(start, end, false, false, 15); MapRoute route2 = OpenStreetMapProvider.Instance.GetRoute(p2, p3, false, false, 15); GMapRoute r2 = new GMapRoute(route2.Points, "My route2"); r2.Stroke.Width = 2; r2.Stroke.Color = Color.Orange; GMapOverlay routesOverlay2 = new GMapOverlay("routes"); routesOverlay2.Routes.Add(r2); gmap.Overlays.Add(routesOverlay2); //marker.ToolTipText = string.Format("RSU"); //data analytics part chart1.Series.Clear(); //chart1.Series.Add("Car 2"); //chart1.Series[1].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Spline; }
/// <summary> /// used to redraw the polygon /// </summary> void RegeneratePolygon() { List<PointLatLng> polygonPoints = new List<PointLatLng>(); if (routes == null) return; foreach (GMapMarker m in polygons.Markers) { if (m is GMapMarkerRect) { m.Tag = polygonPoints.Count; polygonPoints.Add(m.Position); } } if (polygonPoints.Count < 2) return; GMapRoute homeroute = new GMapRoute("homepath"); homeroute.Stroke = new Pen(Color.Yellow, 2); homeroute.Stroke.DashStyle = DashStyle.Dash; // add first point past home homeroute.Points.Add(polygonPoints[1]); // add home location homeroute.Points.Add(polygonPoints[0]); // add last point homeroute.Points.Add(polygonPoints[polygonPoints.Count - 1]); GMapRoute wppath = new GMapRoute("wp path"); wppath.Stroke = new Pen(Color.Yellow, 4); wppath.Stroke.DashStyle = DashStyle.Custom; for (int a = 1; a < polygonPoints.Count; a++) { wppath.Points.Add(polygonPoints[a]); } polygons.Routes.Add(homeroute); polygons.Routes.Add(wppath); }
void DrawMap() { int rtcnt = 0; try { mapoverlay.Routes.Clear(); DateTime starttime = DateTime.MinValue; DateTime workingtime = starttime; DateTime lastdrawn = DateTime.MinValue; List<PointLatLng> routelist = new List<PointLatLng>(); List<int> samplelist = new List<int>(); //zg1.GraphPane.GraphObjList.Clear(); //check if GPS data are available if (!DFLog.logformat.ContainsKey("GPS")) return; int index = DFLog.FindMessageOffset("GPS", "Lat"); if (index == -1) { return; } int index2 = DFLog.FindMessageOffset("GPS", "Lng"); if (index2 == -1) { return; } int index3 = DFLog.FindMessageOffset("GPS", "Status"); if (index3 == -1) { return; } int i = 0; int firstpoint = 0; int b = 0; foreach (var item2 in logdata) { b++; var item = DFLog.GetDFItemFromLine(item2, b); if (item.msgtype == "GPS") { var ans = getPointLatLng(item); if (ans.HasValue) { routelist.Add(ans.Value); samplelist.Add(i); if (routelist.Count > 1000) { //split the route in several small parts (due to memory errors) GMapRoute route_part = new GMapRoute(routelist, "route_" + rtcnt); route_part.Stroke = new Pen(Color.FromArgb(127, Color.Blue), 2); LogRouteInfo lri = new LogRouteInfo(); lri.firstpoint = firstpoint; lri.lastpoint = i; lri.samples.AddRange(samplelist); route_part.Tag = lri; route_part.IsHitTestVisible = true; mapoverlay.Routes.Add(route_part); rtcnt++; //clear the list and set the last point as first point for the next route routelist.Clear(); samplelist.Clear(); firstpoint = i; samplelist.Add(firstpoint); routelist.Add(ans.Value); } } } i++; } GMapRoute route = new GMapRoute(routelist, "route_" + rtcnt); route.Stroke = new Pen(Color.FromArgb(127, Color.Blue), 2); LogRouteInfo lri2 = new LogRouteInfo(); lri2.firstpoint = firstpoint; lri2.lastpoint = i; lri2.samples.AddRange(samplelist); route.Tag = lri2; route.IsHitTestVisible = true; mapoverlay.Routes.Add(route); rtcnt++; myGMAP1.ZoomAndCenterRoute(route); } catch (Exception ex) { log.Error(ex); } if (rtcnt > 0) myGMAP1.RoutesEnabled = true; }
// Map Operators private void map_OnRouteEnter(GMapRoute item) { string dist; if (DistUnits == "Feet") { dist = ((float)item.Distance * 3280.84f).ToString("0.##") + " ft"; } else { dist = ((float)item.Distance * 1000f).ToString("0.##") + " m"; } if (marker != null) { if (routesOverlay.Markers.Contains(marker)) routesOverlay.Markers.Remove(marker); } PointLatLng point = currentMousePosition; marker = new GMapMarkerRect(point); marker.ToolTip = new GMapToolTip(marker); marker.ToolTipMode = MarkerTooltipMode.Always; marker.ToolTipText = "Line: " + dist; routesOverlay.Markers.Add(marker); }
public mainForm() { InitializeComponent(); GPS_pos.Lat = 47.402489; GPS_pos.Lng = 19.071558; #region map_setup // config map MainMap.MinZoom = 1; MainMap.MaxZoom = 20; MainMap.CacheLocation = Path.GetDirectoryName(Application.ExecutablePath) + "/mapcache/"; mapProviders = new GMapProvider[6]; mapProviders[0] = GMapProviders.BingHybridMap; mapProviders[1] = GMapProviders.BingSatelliteMap; mapProviders[2] = GMapProviders.GoogleHybridMap; mapProviders[3] = GMapProviders.GoogleSatelliteMap; mapProviders[4] = GMapProviders.OviHybridMap; mapProviders[5] = GMapProviders.OviSatelliteMap; for (int i = 0; i < 6; i++) { cbMapProviders.Items.Add(mapProviders[i]); } cbMapProviders.SelectedIndex = 1; // map events MainMap.OnPositionChanged += new PositionChanged(MainMap_OnCurrentPositionChanged); MainMap.OnMapZoomChanged += new MapZoomChanged(MainMap_OnMapZoomChanged); MainMap.MouseMove += new MouseEventHandler(MainMap_MouseMove); MainMap.MouseDown += new MouseEventHandler(MainMap_MouseDown); MainMap.MouseUp += new MouseEventHandler(MainMap_MouseUp); MainMap.OnMarkerEnter += new MarkerEnter(MainMap_OnMarkerEnter); MainMap.OnMarkerLeave += new MarkerLeave(MainMap_OnMarkerLeave); currentMarker = new GMapMarkerGoogleRed(MainMap.Position); //MainMap.MapScaleInfoEnabled = true; MainMap.ForceDoubleBuffer = true; MainMap.Manager.Mode = AccessMode.ServerAndCache; MainMap.Position = copterPos; Pen penRoute = new Pen(Color.Yellow, 3); Pen penScale = new Pen(Color.Blue, 3); MainMap.ScalePen = penScale; GMOverlayFlightPath = new GMapOverlay(MainMap, "flightpath"); MainMap.Overlays.Add(GMOverlayFlightPath); GMOverlayWaypoints = new GMapOverlay(MainMap, "waypoints"); MainMap.Overlays.Add(GMOverlayWaypoints); GMOverlayMission = new GMapOverlay(MainMap, "missionroute"); MainMap.Overlays.Add(GMOverlayMission); GMOverlayLiveData = new GMapOverlay(MainMap, "livedata"); MainMap.Overlays.Add(GMOverlayLiveData); m.Position = GPS_pos; mBorders.Position = GPS_pos; mBorders.InnerMarker = m; mBorders.wprad = (int)float.Parse("5"); mBorders.MainMap = MainMap; GMOverlayLiveData.Markers.Add(m); GMOverlayLiveData.Markers.Add(mBorders); GMRouteFlightPath = new GMapRoute(points, "flightpath"); GMRouteFlightPath.Stroke = penRoute; GMOverlayFlightPath.Routes.Add(GMRouteFlightPath); center = new GMapMarkerCross(MainMap.Position); #endregion }
private async void buttonSqlOk_Click(object sender, EventArgs e) { this.markerOverlay.Clear(); this.routesOverlay.Clear(); this.routes = new List <Route>(); List <Query> checkedQueries = checkedListBoxQueries.CheckedItems.Cast <Query>().ToList(); int rowCount = 0; buttonSqlOk.Text = "Töltés..."; buttonSqlOk.Enabled = false; await Task.Run(() => { foreach (Query q in checkedQueries) { List <Location> location = new List <Location>(); try { location = sqlReader.readLocations(q.sql, textBoxQueryVariables.Text); } catch (Exception ex) { MessageBox.Show("Hiba történt a lekérdezés közben: " + ex.Message); } routes.Add(new Route { name = q.name, query = new Query { name = q.name, description = q.description, sql = q.sql, color = q.color }, locations = location }); rowCount += location.Count; } }); tabControlTables.TabPages.Clear(); try { foreach (Route r in routes) { DataGridView dataGridView = new DataGridView(); BindingSource source = new BindingSource(); dataGridView.DataSource = source; dataGridView.Dock = DockStyle.Fill; dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; dataGridView.EditMode = DataGridViewEditMode.EditProgrammatically; dataGridView.CellClick += new DataGridViewCellEventHandler(this.dataGrid_CellClick); dataGrids.Add(dataGridView); TabPage tabPage = new TabPage(r.name); tabPage.Controls.Add(dataGridView); tabControlTables.TabPages.Add(tabPage); foreach (Location l in r.locations) { source.Add(l); } } labelQueryCount.Text = labelQueryCountText + rowCount.ToString(); buttonSqlOk.Text = "Mutat"; buttonSqlOk.Enabled = true; if (radioButtonMarker.Checked) { foreach (Route r in this.routes) { Bitmap m = new Bitmap(10, 10); Graphics g = Graphics.FromImage(m); Color color = (Color)colorConverter.ConvertFromString(r.query.color); Brush brush = new SolidBrush(color); g.FillEllipse(brush, 0f, 0f, 10f, 10f); foreach (Location l in r.locations) { if (l.accuracy > (double)numericUpDownMinAccuracy.Value) { continue; } Marker marker = new Marker(new PointLatLng(l.lat, l.lon), m, l.id, r); markerOverlay.Markers.Add(marker); } } } else if (radioButtonLine.Checked) { foreach (Route r in this.routes) { List <List <PointLatLng> > pointsList = new List <List <PointLatLng> >(); int lastUserId = 0; DateTime lastTimeStamp = new DateTime(); List <PointLatLng> points = new List <PointLatLng>(); pointsList.Add(points); foreach (Location l in r.locations) { if (l.accuracy > (double)numericUpDownMinAccuracy.Value) { continue; } TimeSpan ts = Convert.ToDateTime(l.ts) - lastTimeStamp; if (ts.TotalSeconds < 60.0 && lastUserId == l.userId) { points.Add(new PointLatLng(l.lat, l.lon)); } else { points = new List <PointLatLng>(); pointsList.Add(points); lastUserId = l.userId; } lastTimeStamp = Convert.ToDateTime(l.ts); } GMapRoute route; foreach (List <PointLatLng> p in pointsList) { route = new GMapRoute(p, "myRoute"); route.Stroke = new Pen((Color)colorConverter.ConvertFromString(r.query.color), 2f); markerOverlay.Routes.Add(route); } } } } catch (OutOfMemoryException ex) { MessageBox.Show("A lekérdezés során elfogyott a rendelkezésre álló memória."); } }
public void AddLocation(double lat, double lng,float bearing) { var pt = new PointLatLng(lat, lng); if (gpstrack.Count == 0) { gpstrack.Add(pt); } while (gpstrack.Count > TrackTrip/TrackGap) { gpstrack.RemoveAt(0); } if (CalcDistance(gpstrack[gpstrack.Count - 1], pt) > TrackGap) { gpstrack.Add(pt); if (isTrackShow) { track.Routes.Clear(); GMapRoute gr = new GMapRoute(gpstrack, "Track"); track.Routes.Add(gr); } } NodeMarker.Position = pt; NodeMarker.Bearing = bearing; if (AutoTrack.Checked) MainMap.Position = pt; CultureInfo ci = new CultureInfo("en-us"); string lngstr, latstr; if (pt.Lng > 0) lngstr = pt.Lng.ToString("F06") + " E"; else lngstr = (-pt.Lng).ToString("F06") + " W"; if (pt.Lat > 0) latstr = pt.Lat.ToString("F06") + " N"; else latstr = (-pt.Lat).ToString("F06") + " S"; NodeMarker.ToolTipText = "GPS\r\n经度=" + lngstr + "\r\n纬度=" + latstr; }
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e) { int indice = checkedListBox1.SelectedIndex; if (indice != -1) { if (checkedListBox1.GetItemChecked(0)) { GMapRoute rutaPts = new GMapRoute(ruta2.puntos, "Ruta"); ruta2o.Routes.Add(rutaPts); gMapControl1.Overlays.Add(ruta2o); gMapControl1.Update(); gMapControl1.Zoom = gMapControl1.Zoom + 1; gMapControl1.Zoom = gMapControl1.Zoom - 1; simulacion = true; } else { gMapControl1.Overlays.Remove(ruta2o); } if (checkedListBox1.GetItemChecked(1)) { GMapRoute rutaPts = new GMapRoute(ruta10.puntos, "Ruta"); ruta10o.Routes.Add(rutaPts); gMapControl1.Overlays.Add(ruta10o); gMapControl1.Update(); gMapControl1.Zoom = gMapControl1.Zoom + 1; gMapControl1.Zoom = gMapControl1.Zoom - 1; } else { gMapControl1.Overlays.Remove(ruta10o); gMapControl1.Update(); } if (checkedListBox1.GetItemChecked(2)) { GMapRoute rutaPts = new GMapRoute(ruta12.puntos, "Ruta"); ruta12o.Routes.Add(rutaPts); gMapControl1.Overlays.Add(ruta12o); gMapControl1.Update(); gMapControl1.Zoom = gMapControl1.Zoom + 1; gMapControl1.Zoom = gMapControl1.Zoom - 1; } else { gMapControl1.Overlays.Remove(ruta12o); gMapControl1.Update(); } if (checkedListBox1.GetItemChecked(3)) { GMapRoute rutaPts = new GMapRoute(ruta24.puntos, "Ruta"); ruta24o.Routes.Add(rutaPts); gMapControl1.Overlays.Add(ruta24o); gMapControl1.Update(); gMapControl1.Zoom = gMapControl1.Zoom + 1; gMapControl1.Zoom = gMapControl1.Zoom - 1; } else { gMapControl1.Overlays.Remove(ruta24o); gMapControl1.Update(); } if (checkedListBox1.GetItemChecked(4)) { GMapRoute rutaPts = new GMapRoute(ruta28.puntos, "Ruta"); ruta28o.Routes.Add(rutaPts); gMapControl1.Overlays.Add(ruta28o); gMapControl1.Update(); gMapControl1.Zoom = gMapControl1.Zoom + 1; gMapControl1.Zoom = gMapControl1.Zoom - 1; } else { gMapControl1.Overlays.Remove(ruta28o); gMapControl1.Update(); } if (checkedListBox1.GetItemChecked(5)) { GMapRoute rutaPts = new GMapRoute(ruta31.puntos, "Ruta"); ruta31o.Routes.Add(rutaPts); gMapControl1.Overlays.Add(ruta31o); gMapControl1.Update(); gMapControl1.Zoom = gMapControl1.Zoom + 1; gMapControl1.Zoom = gMapControl1.Zoom - 1; } else { gMapControl1.Overlays.Remove(ruta31o); gMapControl1.Update(); } if (checkedListBox1.GetItemChecked(6)) { GMapRoute rutaPts = new GMapRoute(ruta34.puntos, "Ruta"); ruta34o.Routes.Add(rutaPts); gMapControl1.Overlays.Add(ruta34o); gMapControl1.Update(); gMapControl1.Zoom = gMapControl1.Zoom + 1; gMapControl1.Zoom = gMapControl1.Zoom - 1; } else { gMapControl1.Overlays.Remove(ruta34o); gMapControl1.Update(); } } }
public void BuildgMap() { /* * switch (index) * { * case 0: * _mapcontrol.MapProvider = global::GMap.NET.MapProviders.BingSatelliteMapProvider.Instance; * break; * case 1: * _mapcontrol.MapProvider = global::GMap.NET.MapProviders.GoogleMapProvider.Instance; * break; * case 2: * _mapcontrol.MapProvider = global::GMap.NET.MapProviders.GoogleTerrainMapProvider.Instance; * break; * case 3: * _mapcontrol.MapProvider = global::GMap.NET.MapProviders.GoogleHybridMapProvider.Instance; * break; * case 4: * _mapcontrol.MapProvider = global::GMap.NET.MapProviders.ArcGIS_Topo_US_2D_MapProvider.Instance; * break; * case 5: * _mapcontrol.MapProvider = global::GMap.NET.MapProviders.GoogleSatelliteMapProvider.Instance; * break; * } * * * * global::GMap.NET.GMaps.Instance.Mode = global::GMap.NET.AccessMode.ServerOnly; */ _markers.Clear(); _mapcontrol.Overlays.Clear(); //_mapcontrol.ShowCenter = false; _overmarkers = new GMapOverlay("markers"); _overroutes = new GMapOverlay("routes"); _overpolys = new GMapOverlay("polygons"); _mapcontrol.Overlays.Add(_overmarkers); _mapcontrol.Overlays.Add(_overroutes); _mapcontrol.Overlays.Add(_overpolys); _drone_image_notselected = (Bitmap)Image.FromFile("drone.png", true); _drone_image_selected = (Bitmap)Image.FromFile("drone_selected.png", true); // Map POI int poicount = _wpg.POICount(); for (int i = 0; i < poicount; i++) { GMapMarker marker; POIPoints pnt = _wpg.POIPointAt(i); string poiname = pnt.name; if (i == 0) { _mapcontrol.Position = new global::GMap.NET.PointLatLng(pnt.lat, pnt.lon); } if (pnt.selected) { marker = new GMarkerGoogle(new PointLatLng(pnt.lat, pnt.lon), _poi_selected_image); } else { marker = new GMarkerGoogle(new PointLatLng(pnt.lat, pnt.lon), _poi_image); } // GMarkerGoogleType.blue_pushpin); //marker.Size = new Size(32, 32); marker.Offset = new Point(-16, -16); marker.ToolTipText = poiname; marker.Tag = poiname; marker.IsVisible = pnt.visible; marker.IsHitTestVisible = true; _overmarkers.Markers.Add(marker); } // Map Path int pathcount = _wpg.PathCount(); for (int i = 0; i < pathcount; i++) { Path path = _wpg.PathAt(i); string name = path.name; bool visible = path.visible; LinkedList <WayPoints> wplist = path.waypoints; int wpcount = wplist.Count; List <PointLatLng> points = new List <PointLatLng>(); int count = 0; foreach (WayPoints wp in wplist) { bool selected = wp.selected; points.Add(new PointLatLng(wp.lat, wp.lon)); GMapMarker marker; if (selected) { _drone_image = _drone_image_selected; _drone_image = RotateImage(_drone_image_selected, wp.head); marker = new GMarkerGoogle(new PointLatLng(wp.lat, wp.lon), _drone_image); //GMarkerGoogleType.red_pushpin); } else { _drone_image = _drone_image_notselected; _drone_image = RotateImage(_drone_image_notselected, wp.head); marker = new GMarkerGoogle(new PointLatLng(wp.lat, wp.lon), _drone_image); //GMarkerGoogleType.blue_pushpin); } //marker.Size = new Size(64,64); marker.Position = new PointLatLng(wp.lat, wp.lon); marker.Offset = new Point(-16, -16); marker.Tag = Convert.ToString(i) + "." + Convert.ToString(count); marker.IsVisible = visible; marker.ToolTipText = "WP(" + Convert.ToString(count) + ") - Alt:" + Convert.ToString(wp.alt); _overmarkers.Markers.Add(marker); wp.marker = marker; GMAPWPMarker wpmarker = new GMAPWPMarker(); wpmarker.path = i; wpmarker.wp = count; wpmarker.marker = marker; wpmarker.selected = wp.selected; _markers.Add(wpmarker); count++; } GMapRoute route = new GMapRoute(points, name); route.Stroke = new Pen(Color.Blue, 2); route.Tag = i; route.IsVisible = visible; route.IsHitTestVisible = true; _overroutes.Routes.Add(route); //mapcontrol.Overlays.Add(overroutes); //mapcontrol.Overlays.Add(markers); } //mapcontrol.Overlays.Add(markers); // Map Polygon int polycount = _wpg.ShapeCount(); for (int i = 0; i < polycount; i++) { Shape polyshape = _wpg.ShapeAt(i); string name = polyshape.name; bool visible = polyshape.visible; LinkedList <PolyPoint> wplist = polyshape.points; int wpcount = wplist.Count; List <PointLatLng> points = new List <PointLatLng>(); foreach (PolyPoint wp in wplist) { points.Add(new PointLatLng(wp.lat, wp.lon)); } GMapPolygon poly = new GMapPolygon(points, name); if (polyshape.selected) { poly.Stroke = new Pen(Color.Red, 1); } else { poly.Stroke = new Pen(Color.Yellow, 1); } poly.Fill = new SolidBrush(Color.FromArgb(25, Color.Yellow)); poly.Tag = polyshape.name; poly.IsVisible = visible; _overpolys.Polygons.Add(poly); } if (!Form1.Globals.Map_FirstDraw) { _mapcontrol.Position = Form1.Globals.map_center; Form1.Globals.Map_FirstDraw = false; } _center = _mapcontrol.Position; }
private void InitMap() { gMapCtrl.DragButton = MouseButton.Left; gMapCtrl.Focus(); gMapCtrl.MapProvider = GMapProviders.GoogleMap; PointLatLng startPoint = new PointLatLng(CurrTravel.Cities[0].Coord.latitude, CurrTravel.Cities[0].Coord.longitude); gMapCtrl.Position = startPoint; //Маркеры foreach (City c in CurrTravel.GetRouteCts()) { GMapMarker marker = new GMapMarker(new PointLatLng(c.Coord.latitude, c.Coord.longitude)) { Shape = new Ellipse { Stroke = new SolidColorBrush(Colors.DeepSkyBlue), StrokeThickness = 12 }, Offset = new Point(-6, -6), ZIndex = 2 }; gMapCtrl.Markers.Add(marker); } //Путь City prev = null; foreach (City c in CurrTravel.GetRouteCts()) { if (prev != null) { PointLatLng start = new PointLatLng(prev.Coord.latitude, prev.Coord.longitude); PointLatLng end = new PointLatLng(c.Coord.latitude, c.Coord.longitude); GMapRoute route = null; MapRoute path = GMapProviders.OpenStreetMap.GetRoute(start, end, false, false, 15); if (path != null && path.Distance > 1) { route = new GMapRoute(path.Points) { Shape = new Path() { Stroke = new SolidColorBrush(Colors.DarkViolet), StrokeThickness = 4, Opacity = 0.65 }, ZIndex = 1 }; } else { route = new GMapRoute(new List <PointLatLng>() { start, end }) { Shape = new Path() { Stroke = new SolidColorBrush(Colors.Orange), StrokeThickness = 4, Opacity = 0.65 }, ZIndex = 0 }; } gMapCtrl.Markers.Add(route); } prev = c; } //Прямые линии между точками //GMapRoute route = new GMapRoute(path) { // Shape = new Path() { Stroke = new SolidColorBrush(Colors.Orange), StrokeThickness = 4, }, // ZIndex = 0 //}; //gMapCtrl.Markers.Add(route) //Ненужное //GMapMarker marker = new GMapMarker(startPoint); //marker.Shape = new Control(); //gMapCtrl.Markers.Add(marker); //gMapCtrl.Markers[0].Shape.Visibility = Visibility.Visible; //List<Point> locPath = new List<Point>(); //List<PointLatLng> path = new List<PointLatLng>(); //foreach (City c in CurrTravel.Cities) { // path.Add(new PointLatLng(c.Coord.latitude, c.Coord.longitude)); // locPath.Add(new Point(c.Coord.latitude, c.Coord.longitude)); // gMapCtrl.Markers.Add(new GMapMarker(new PointLatLng(c.Coord.latitude, c.Coord.longitude))); //} //foreach (GMapMarker marker in gMapCtrl.Markers) { // if (marker.Shape != null) // marker.Shape.Visibility = Visibility.Visible; //} //MapRoute route = new MapRoute(path, "First"); //Path path2 = gMapCtrl.CreateRoutePath(locPath); //path2.BeginInit(); //path2.ApplyTemplate(); //path2.BringIntoView(); //gMapCtrl.BringIntoView(); }
private void RenderPath() { GMapRoute path = new GMapRoute(lPointsPath, "Path"); PathOverlay.Clear(); PathOverlay.Routes.Add(path); updateTable(); }
private void button4_Click(object sender, EventArgs e) { try { using (NpgsqlConnection cn = new NpgsqlConnection(Connection.str)) { cn.Open(); //получение области NpgsqlCommand cmd2 = new NpgsqlCommand("select ST_AsText((points).geom) from (select ST_DumpPoints(region_table.region) as points from region_table where region_table.reg_id=(select rental_table.region from rental_table where rental_table.rent_id=" + rentID + ")) as tmp", cn); NpgsqlDataReader reader2 = cmd2.ExecuteReader(); DataTable dt2 = new DataTable(); dt2.Load(reader2); List <PointLatLng> polyPoints = new List <PointLatLng>(); for (int i = 0; i < dt2.Rows.Count; i++) { double[] tempPoints2 = GetPoints(dt2.Rows[i][0].ToString()); polyPoints.Add(new PointLatLng(tempPoints2[0], tempPoints2[1])); } GMapPolygon polygon = new GMapPolygon(polyPoints, "polygon"); polygon.Fill = new SolidBrush(Color.FromArgb(50, Color.Red)); polygon.Stroke = new Pen(Color.Red, 1); overlay.Polygons.Add(polygon); //получение текущего положения автомобиля NpgsqlCommand cmd1 = new NpgsqlCommand("select ST_AsText(point) from track_table where rent_id=" + rentID + " ORDER BY track_time DESC LIMIT 1", cn); var temp = cmd1.ExecuteScalar(); if (temp == null) { throw new Exception("У этого автомобиля ещё нет трека."); } double[] points1 = GetPoints(temp.ToString()); GMapMarker location = new GMarkerGoogle(new PointLatLng(points1[0], points1[1]), GMarkerGoogleType.red); location.ToolTipText = "Автомобиль здесь"; overlay.Markers.Add(location); //получение трека NpgsqlCommand cmd3 = new NpgsqlCommand("select ST_AsText(point) from track_table where rent_id=" + rentID, cn); NpgsqlDataReader reader3 = cmd3.ExecuteReader(); DataTable dt3 = new DataTable(); dt3.Load(reader3); List <PointLatLng> trackPoints = new List <PointLatLng>(); for (int i = 0; i < dt3.Rows.Count; i++) { double[] tempPoints3 = GetPoints(dt3.Rows[i][0].ToString()); trackPoints.Add(new PointLatLng(tempPoints3[0], tempPoints3[1])); } GMapRoute route = new GMapRoute(trackPoints, "route"); route.Stroke = new Pen(Color.Red, 3); overlay.Routes.Add(route); //получение длины трека NpgsqlCommand cmd4 = new NpgsqlCommand("select ST_Length(ST_MakeLine(tmp.point ORDER BY tmp.track_time)) from (select * from track_table where rent_id=" + rentID + ") as tmp", cn); string len = cmd4.ExecuteScalar().ToString(); len = len.Replace(".", ","); DistanceLabel.Text = len + " км"; label1.Visible = true; DistanceLabel.Visible = true; cn.Close(); } } catch (Exception er) { MessageBox.Show(er.Message); } }
void DrawMap() { int a = 0; DateTime starttime = DateTime.MinValue; int startdelta = 0; DateTime workingtime = starttime; DateTime lastdrawn = DateTime.MinValue; List<PointLatLng> routelist = new List<PointLatLng>(); //zg1.GraphPane.GraphObjList.Clear(); foreach (DataGridViewRow datarow in dataGridView1.Rows) { if (datarow.Cells[1].Value.ToString() == "GPS") { if (!logformat.ContainsKey("GPS")) break; int index = FindInArray(logformat["GPS"].FieldNames, "Lat"); if (index == -1) { a++; continue; } int index2 = FindInArray(logformat["GPS"].FieldNames, "Lng"); if (index2 == -1) { a++; continue; } int index3 = FindInArray(logformat["GPS"].FieldNames, "Status"); if (index3 == -1) { a++; continue; } if (double.Parse(datarow.Cells[index3 + 2].Value.ToString()) != 3) { a++; continue; } string lat = datarow.Cells[index+2].Value.ToString(); string lng = datarow.Cells[index2+2].Value.ToString(); PointLatLng pnt = new PointLatLng() { }; pnt.Lat = double.Parse(lat); pnt.Lng = double.Parse(lng); routelist.Add(pnt); } a++; } GMapRoute route = new GMapRoute(routelist,"route"); mapoverlay.Routes.Add(route); myGMAP1.ZoomAndCenterRoute(route); myGMAP1.RoutesEnabled = true; }
void TreceRouteStart(object state) { //UcTraceRoute form = (state as UcTraceRoute); //if (form.InvokeRequired) // form.Invoke(new ParameterizedThreadStart(TreceRouteStart), state); //else //{ textBoxLog.Text = ""; route = null; points.Clear(); routes.Routes.Clear(); traceMep.Overlays.Clear(); IpFromHost Host = new IpFromHost(); GeoDataByIPFromWeb Geo = new GeoDataByIPFromWeb(); Host.GetIpAddress(textBoxUrl.Text); if (Host.HostState) { IpAddresesTraceRoute = GetTraceRoute(Host.NormHost); GMapOverlay markersOverlay = new GMapOverlay("markers"); int index = 0; foreach (var ip in IpAddresesTraceRoute) { Thread.Sleep(600); index++; GeoData GeoObj = Geo.GetData(ip.ToString()); textBoxLog.Text += "\r\n-->" + ip + " #" + index; if (GeoObj.InnerData.GeoInfo.Latitude != null && GeoObj.InnerData.GeoInfo.Latitude != null) { textBoxLog.Text += "\r\n" + GeoObj.InnerData.GeoInfo.Latitude + "\r\n" + GeoObj.InnerData.GeoInfo.Longityde + "\r\n"; double lat = double.Parse(GeoObj.InnerData.GeoInfo.Latitude.Replace(".", ",")); double lng = double.Parse(GeoObj.InnerData.GeoInfo.Longityde.Replace(".", ",")); traceMep.Position = new PointLatLng(lat, lng); bool ifUnique = true; foreach (var point in markersOverlay.Markers) { if (point.Position.Lat == lat && point.Position.Lng == lng) { point.ToolTipText = ip + " #" + index + "\r\n" + point.ToolTipText; ifUnique = false; points.Add(new PointLatLng(lat, lng)); } else { } } if (ifUnique) { points.Add(new PointLatLng(lat, lng)); GMarkerGoogle marker = new GMarkerGoogle ( new PointLatLng(lat, lng), //GMarkerGoogleType.orange new Bitmap(@"none.png") ); marker.ToolTipMode = MarkerTooltipMode.Always; marker.ToolTipText = ip + " #" + index + "\r\n" + GeoObj.InnerData.GeoInfo.CountryName + "\r\n" + GeoObj.InnerData.GeoInfo.City + "\r\n" + GeoObj.InnerData.GeoInfo.isp; marker.ToolTip.Fill = Brushes.WhiteSmoke; marker.ToolTip.Foreground = Brushes.Black; marker.ToolTip.Stroke = Pens.Black; marker.ToolTip.TextPadding = new Size(10, 10); marker.ToolTip.Font = new Font("Arial", (float)7.5, FontStyle.Regular); markersOverlay.Markers.Add(marker); } } else { textBoxLog.Text += "\r\nno geo data\r\n"; } route = new GMapRoute(points, "Route"); route.Stroke = new Pen(Color.Brown, 2); routes.Routes.Add(route); traceMep.Overlays.Add(routes); traceMep.Overlays.Add(markersOverlay); } } else { textBoxLog.Text = "Error! Invalid URL"; } }
public void AddRoute(GMapRoute Route, Color RouteColor) { Route.Stroke = (Pen)route.Stroke.Clone(); Route.Stroke.Color = RouteColor; gMapControl1.Overlays[0].Routes.Add(Route); }
private void myGMAP1_OnRouteClick(GMapRoute item, MouseEventArgs e) { if ((item.Name != null) && (item.Name.StartsWith("route_"))) { LogRouteInfo lri = item.Tag as LogRouteInfo; if (lri != null) { //cerco il punto più vicino MissionPlanner.Utilities.PointLatLngAlt pt2 = new MissionPlanner.Utilities.PointLatLngAlt(myGMAP1.FromLocalToLatLng(e.X, e.Y)); double dBest = double.MaxValue; int nBest = 0; for (int i = 0; i < item.LocalPoints.Count; i++) { PointLatLng pt = item.Points[i]; double d = Math.Sqrt((pt.Lat - pt2.Lat) * (pt.Lat - pt2.Lat) + (pt.Lng - pt2.Lng) * (pt.Lng - pt2.Lng)); if (d < dBest) { dBest = d; nBest = i; } } double perc = (double)nBest / (double) item.LocalPoints.Count; int SampleID = (int)(lri.firstpoint + (lri.lastpoint - lri.firstpoint) * perc); if ((lri.samples.Count > 0) && (nBest < lri.samples.Count)) SampleID = lri.samples[nBest]; GoToSample(SampleID, false, true, true); //debugging route click //GMapMarker pos2 = new GMarkerGoogle(pt2, GMarkerGoogleType.orange_dot); //markeroverlay.Markers.Add(pos2); } } }
void DrawMap() { try { int a = 0; DateTime starttime = DateTime.MinValue; int startdelta = 0; DateTime workingtime = starttime; DateTime lastdrawn = DateTime.MinValue; List <PointLatLng> routelist = new List <PointLatLng>(); //zg1.GraphPane.GraphObjList.Clear(); foreach (DataGridViewRow datarow in dataGridView1.Rows) { if (datarow.Cells[1].Value.ToString() == "GPS") { if (!logformat.ContainsKey("GPS")) { break; } int index = FindInArray(logformat["GPS"].FieldNames, "Lat"); if (index == -1) { a++; continue; } int index2 = FindInArray(logformat["GPS"].FieldNames, "Lng"); if (index2 == -1) { a++; continue; } int index3 = FindInArray(logformat["GPS"].FieldNames, "Status"); if (index3 == -1) { a++; continue; } try { if (double.Parse(datarow.Cells[index3 + 2].Value.ToString(), System.Globalization.CultureInfo.InvariantCulture) != 3) { a++; continue; } string lat = datarow.Cells[index + 2].Value.ToString(); string lng = datarow.Cells[index2 + 2].Value.ToString(); PointLatLng pnt = new PointLatLng() { }; pnt.Lat = double.Parse(lat, System.Globalization.CultureInfo.InvariantCulture); pnt.Lng = double.Parse(lng, System.Globalization.CultureInfo.InvariantCulture); routelist.Add(pnt); } catch { } } a++; } GMapRoute route = new GMapRoute(routelist, "route"); mapoverlay.Routes.Add(route); myGMAP1.ZoomAndCenterRoute(route); myGMAP1.RoutesEnabled = true; } catch { } }
public void DrawRoute() { List<PointLatLng> list = new List<PointLatLng>(); foreach (PointD p in points) { list.Add(new PointLatLng(p.getx(), p.gety())); } GMapRoute r = new GMapRoute(list, "my route"); r.Stroke.Width = 0.5f; r.Stroke.Color = Color.Red; overlayOne.Routes.Add(r); }
private void buttonRouting_Click(object sender, EventArgs e) { if (!textBoxFrom.Text.Equals("") && !textBoxDestination.Text.Equals("")) { String nodeFromName = textBoxFrom.Text; String nodeDestinationName = textBoxDestination.Text; WayNodeModel mFrom = dbConnection.getWayNodeDataAttribute(nodeFromName); WayNodeModel mDestination = dbConnection.getWayNodeDataAttribute(nodeDestinationName); String lat1 = Convert.ToString(mFrom.getLatitude()); String lon1 = Convert.ToString(mFrom.getLongitude()); String lat2 = Convert.ToString(mDestination.getLatitude()); String lon2 = Convert.ToString(mDestination.getLongitude()); // create valid latitude & longitude type from database, ex : -69097867 to -6.9097867 and 1076106278 to 107.6106278 lat1 = lat1.Insert(2, "."); lon1 = lon1.Insert(3, "."); lat2 = lat2.Insert(2, "."); lon2 = lon2.Insert(3, "."); Console.WriteLine("Lat1:" + lat1 + " Lon1:" + lon1); Console.WriteLine("Lat2:" + lat2 + " Lon2:" + lon2); // add marker for source GMapOverlay markersOverlayFrom = new GMapOverlay(mFrom.getWayName()); GMarkerGoogle markerFrom = new GMarkerGoogle(new PointLatLng(Convert.ToDouble(lat1), Convert.ToDouble(lon1)), GMarkerGoogleType.green); markersOverlayFrom.Markers.Add(markerFrom); gMapControl.Overlays.Add(markersOverlayFrom); // add marker for destination GMapOverlay markersOverlayDest = new GMapOverlay(mDestination.getWayName()); GMarkerGoogle markerDest = new GMarkerGoogle(new PointLatLng(Convert.ToDouble(lat2), Convert.ToDouble(lon2)), GMarkerGoogleType.red); markersOverlayDest.Markers.Add(markerDest); gMapControl.Overlays.Add(markersOverlayDest); // getCenterMap from 2 location PointLocation centerMapLocation = new PointLocation(); MapUtils mapUtil = new MapUtils(); centerMapLocation = mapUtil.calculateMidPointLocations(Convert.ToDouble(lat1), Convert.ToDouble(lon1), Convert.ToDouble(lat2), Convert.ToDouble(lon2)); double bearing = mapUtil.calculateBearing(Convert.ToDouble(lat1), Convert.ToDouble(lon1), Convert.ToDouble(lat2), Convert.ToDouble(lon2)); double distance = mapUtil.calculateDistanceKM(Convert.ToDouble(lat1), Convert.ToDouble(lon1), Convert.ToDouble(lat2), Convert.ToDouble(lon2)); Console.WriteLine("Lat3:" + centerMapLocation.getLatitude() + " Lon3:" + centerMapLocation.getLongitude()); Console.WriteLine("Bearing:" + bearing); Console.WriteLine("Distance:" + distance); Console.WriteLine("Pixel Distance:" + CentimeterToPixel(distance * 10)); // get route result string jsonResultPath = getRoutePath(mFrom.getNodeId(), mDestination.getNodeId()); JObject results = JObject.Parse(jsonResultPath); List <NodeModel> listNode = new List <NodeModel>(); foreach (var result in results["path"]) { NodeModel node = new NodeModel(); string nodeId = (string)result["node_id"]; string lat = (string)result["latitude"]; string lon = (string)result["longitude"]; // create valid latitude & longitude type from database, ex : -69097867 to -6.9097867 and 1076106278 to 107.6106278 lat = lat.Insert(2, "."); lon = lon.Insert(3, "."); node.setNodeId(nodeId); node.setLatitude(Convert.ToDouble(lat)); node.setLongitude(Convert.ToDouble(lon)); listNode.Add(node); //Console.WriteLine("NodeId: {0}, Latitude: {1}, Longitude: {2}", nodeId, lat, lon); } // draw path GMapOverlay routeOverlay = new GMapOverlay("path"); List <PointLatLng> points = new List <PointLatLng>(); // path point for (int i = 0; i < listNode.Count; i++) { points.Add(new PointLatLng(listNode[i].getLatitude(), listNode[i].getLongitude())); Console.WriteLine("NodeId: {0}, Latitude: {1}, Longitude: {2}", listNode[i].getNodeId(), listNode[i].getLatitude(), listNode[i].getLongitude()); } // draw line GMapRoute gRoute = new GMapRoute(points, "route"); gRoute.Stroke.Width = 7; //gRoute.Stroke.Color = Color.SeaGreen; //gRoute.Stroke = new Pen(Color.Blue, 7); routeOverlay.Routes.Add(gRoute); gMapControl.Overlays.Add(routeOverlay); // show getCenterMap from 2 location gMapControl.Position = new GMap.NET.PointLatLng(centerMapLocation.getLatitude(), centerMapLocation.getLongitude()); gMapControl.Zoom = 16; int width = gMapControl.Width; int height = gMapControl.Height; Console.WriteLine("[MapControl] Width: " + width + " Height:" + height); /* * // AStar calculation * AStar astar = new AStar(); * astar.calcuateShortestPath(mFrom.getNodeId(), mDestination.getNodeId()); */ /* * // test take 5 screenshots * List<WayNodeModel> listWays = dbConnection.getWayNodeData(); * for(int i = 0; i < 5; i++){ * createMapTileScreenshots(listWays[i].getNodeId(), Convert.ToString(listWays[i].getLatitude()), Convert.ToString(listWays[i].getLongitude())); * }*/ /*String pathScreenshots = System.IO.Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory) + Path.DirectorySeparatorChar + "screenshots" + Path.DirectorySeparatorChar; * Console.WriteLine("Screenshots Path: " + pathScreenshots); * try * { * // setting for proxy * //PhantomJSOptions phOptions = new PhantomJSOptions(); * //phOptions.AddAdditionalCapability(CapabilityType.Proxy, "cache.itb.ac.id"); * * // hide cmd windows of phantomsjs * var driverService = PhantomJSDriverService.CreateDefaultService(); * driverService.HideCommandPromptWindow = true; * * // initiate phantomjs driver * PhantomJSDriver phantom; * phantom = new PhantomJSDriver(driverService); * // setting the default timeout to 30 seconds * phantom.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30)); * string screenshotUrl = "http://localhost/bsts_routing/tilegen/v2/index.php?latitude=-6.9131786&longitude=107.6474137"; * phantom.Navigate().GoToUrl(screenshotUrl); * * // grab the snapshot * Screenshot sh = phantom.GetScreenshot(); * sh.SaveAsFile(pathScreenshots + "test.png", ImageFormat.Png); * phantom.Quit(); * * } catch (Exception error) { * Console.WriteLine(error.Message); * }*/ } else { MessageBox.Show("Please input address first!"); } }
private static void processKML(SharpKml.Dom.Element Element) { try { // log.Info(Element.ToString() + " " + Element.Parent); } catch { } SharpKml.Dom.Document doc = Element as SharpKml.Dom.Document; SharpKml.Dom.Placemark pm = Element as SharpKml.Dom.Placemark; SharpKml.Dom.Folder folder = Element as SharpKml.Dom.Folder; SharpKml.Dom.Polygon polygon = Element as SharpKml.Dom.Polygon; SharpKml.Dom.LineString ls = Element as SharpKml.Dom.LineString; if (doc != null) { foreach (var feat in doc.Features) { //Console.WriteLine("feat " + feat.GetType()); //processKML((Element)feat); } } else if (folder != null) { foreach (SharpKml.Dom.Feature feat in folder.Features) { //Console.WriteLine("feat "+feat.GetType()); //processKML(feat); } } else if (pm != null) { } else if (polygon != null) { GMapPolygon kmlpolygon = new GMapPolygon(new List<PointLatLng>(), "kmlpolygon"); kmlpolygon.Stroke.Color = Color.Purple; kmlpolygon.Fill = new SolidBrush(Color.FromArgb(30, Color.Blue)); foreach (var loc in polygon.OuterBoundary.LinearRing.Coordinates) { kmlpolygon.Points.Add(new PointLatLng(loc.Latitude, loc.Longitude)); } kmlpolygonsoverlay.Polygons.Add(kmlpolygon); } else if (ls != null) { GMapRoute kmlroute = new GMapRoute(new List<PointLatLng>(), "kmlroute"); kmlroute.Stroke.Color = Color.Purple; foreach (var loc in ls.Coordinates) { kmlroute.Points.Add(new PointLatLng(loc.Latitude, loc.Longitude)); } kmlpolygonsoverlay.Routes.Add(kmlroute); } }
private void BUT_doit_Click(object sender, EventArgs e) { string dirPictures = TXT_jpgdir.Text; string logFilePath = TXT_logfile.Text; if (!File.Exists(logFilePath)) { return; } if (!Directory.Exists(dirPictures)) { return; } float seconds = 0; if (selectedProcessingMode == PROCESSING_MODE.TIME_OFFSET) { if ( float.TryParse(TXT_offsetseconds.Text, NumberStyles.Float, CultureInfo.InvariantCulture, out seconds) == false) { AppendText("Offset number not in correct format. Use . as decimal separator\n"); return; } } BUT_doit.Enabled = false; TXT_outputlog.Clear(); try { log.Info("process " + selectedProcessingMode); switch (selectedProcessingMode) { case PROCESSING_MODE.TIME_OFFSET: georef.picturesInfo = georef.doworkGPSOFFSET(logFilePath, dirPictures, seconds, UseGpsorGPS2(), chk_cammsg.Checked, AppendText); if (georef.picturesInfo != null) { georef.CreateReportFiles(georef.picturesInfo, dirPictures, seconds, (double)num_camerarotation.Value, (double)num_hfov.Value, (double)num_vfov.Value, AppendText, httpGeoRefKML); } break; case PROCESSING_MODE.CAM_MSG: georef.picturesInfo = georef.doworkCAM(logFilePath, dirPictures, UseGpsorGPS2(), AppendText); if (georef.picturesInfo != null) { georef.CreateReportFiles(georef.picturesInfo, dirPictures, seconds, (double)num_camerarotation.Value, (double)num_hfov.Value, (double)num_vfov.Value, AppendText, httpGeoRefKML, chk_camusegpsalt.Checked); } break; case PROCESSING_MODE.TRIG: georef.picturesInfo = georef.doworkTRIG(logFilePath, dirPictures, UseGpsorGPS2(), AppendText); if (georef.picturesInfo != null) { georef.CreateReportFiles(georef.picturesInfo, dirPictures, seconds, (double)num_camerarotation.Value, (double)num_hfov.Value, (double)num_vfov.Value, AppendText, httpGeoRefKML, chk_trigusergpsalt.Checked); } break; } } catch (Exception ex) { AppendText("Error " + ex.ToString()); } log.Info("Draw to Map"); GMapRoute route = new GMapRoute("vehicle"); if (georef.vehicleLocations != null) { foreach (var vehicleLocation in georef.vehicleLocations) { route.Points.Add(new PointLatLngAlt(vehicleLocation.Value.Lat, vehicleLocation.Value.Lon, vehicleLocation.Value.AltAMSL)); } } myGMAP1.Overlays[0].Markers.Clear(); if (georef.picturesInfo != null) { foreach (var pictureLocation in georef.picturesInfo) { myGMAP1.Overlays[0].Markers.Add( new GMarkerGoogle(new PointLatLngAlt(pictureLocation.Value.Lat, pictureLocation.Value.Lon, pictureLocation.Value.AltAMSL), GMarkerGoogleType.green) { IsHitTestVisible = true, ToolTipMode = MarkerTooltipMode.OnMouseOver, ToolTipText = Path.GetFileName(pictureLocation.Value.Path) }); } } myGMAP1.Overlays[0].Routes.Clear(); myGMAP1.Overlays[0].Routes.Add(route); myGMAP1.ZoomAndCenterRoutes(myGMAP1.Overlays[0].Id); BUT_doit.Enabled = true; BUT_Geotagimages.Enabled = true; }
/// <summary> /// Populates a <see cref="T:System.Runtime.Serialization.SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> to populate with data.</param> /// <param name="context">The destination (see <see cref="T:System.Runtime.Serialization.StreamingContext"/>) for this serialization.</param> /// <exception cref="T:System.Security.SecurityException"> /// The caller does not have the required permission. /// </exception> public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Id", this.Id); info.AddValue("IsVisible", this.IsVisibile); GMapMarker[] markerArray = new GMapMarker[this.Markers.Count]; this.Markers.CopyTo(markerArray, 0); info.AddValue("Markers", markerArray); GMapRoute[] routeArray = new GMapRoute[this.Routes.Count]; this.Routes.CopyTo(routeArray, 0); info.AddValue("Routes", routeArray); GMapPolygon[] polygonArray = new GMapPolygon[this.Polygons.Count]; this.Polygons.CopyTo(polygonArray, 0); info.AddValue("Polygons", polygonArray); }
internal void add(GMapRoute route) { mapOverlay.Routes.Add(route); }
private void mainloop(object o) { //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); //System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); System.Threading.Thread.CurrentThread.IsBackground = true; threadrun = 1; EndPoint Remote = (EndPoint)(new IPEndPoint(IPAddress.Any, 0)); DateTime lastdata = DateTime.MinValue; DateTime tracklast = DateTime.Now.AddSeconds(0); DateTime tunning = DateTime.Now.AddSeconds(0); DateTime mapupdate = DateTime.Now.AddSeconds(0); DateTime vidrec = DateTime.Now.AddSeconds(0); DateTime waypoints = DateTime.Now.AddSeconds(0); DateTime updatescreen = DateTime.Now; DateTime tsreal = DateTime.Now; double taketime = 0; double timeerror = 0; //comPort.stopall(true); while (threadrun == 1) { if (threadrun == 0) { return; } if (MainV2.comPort.giveComport == true) { System.Threading.Thread.Sleep(50); continue; } try { if (!MainV2.comPort.BaseStream.IsOpen) lastdata = DateTime.Now; } catch { } // re-request servo data if (!(lastdata.AddSeconds(8) > DateTime.Now) && MainV2.comPort.BaseStream.IsOpen) { //Console.WriteLine("REQ streams - flightdata"); try { //System.Threading.Thread.Sleep(1000); //comPort.requestDatastream((byte)MissionPlanner.MAVLink09.MAV_DATA_STREAM.RAW_CONTROLLER, 0); // request servoout MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.EXTENDED_STATUS, MainV2.comPort.MAV.cs.ratestatus); // mode MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.POSITION, MainV2.comPort.MAV.cs.rateposition); // request gps MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.EXTRA1, MainV2.comPort.MAV.cs.rateattitude); // request attitude MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.EXTRA2, MainV2.comPort.MAV.cs.rateattitude); // request vfr MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.EXTRA3, MainV2.comPort.MAV.cs.ratesensors); // request extra stuff - tridge MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.RAW_SENSORS, MainV2.comPort.MAV.cs.ratesensors); // request raw sensor MainV2.comPort.requestDatastream(MAVLink.MAV_DATA_STREAM.RC_CHANNELS, MainV2.comPort.MAV.cs.raterc); // request rc info } catch { log.Error("Failed to request rates"); } lastdata = DateTime.Now.AddSeconds(60); // prevent flooding } if (!MainV2.comPort.logreadmode) System.Threading.Thread.Sleep(50); // max is only ever 10 hz but we go a little faster to empty the serial queue try { if (aviwriter != null && vidrec.AddMilliseconds(100) <= DateTime.Now) { vidrec = DateTime.Now; hud1.streamjpgenable = true; //aviwriter.avi_start("test.avi"); // add a frame aviwriter.avi_add(hud1.streamjpg.ToArray(), (uint)hud1.streamjpg.Length); // write header - so even partial files will play aviwriter.avi_end(hud1.Width, hud1.Height, 10); } } catch { log.Error("Failed to write avi"); } // log playback if (MainV2.comPort.logreadmode && MainV2.comPort.logplaybackfile != null) { if (threadrun == 0) { return; } if (MainV2.comPort.BaseStream.IsOpen) { MainV2.comPort.logreadmode = false; try { MainV2.comPort.logplaybackfile.Close(); } catch { log.Error("Failed to close logfile"); } MainV2.comPort.logplaybackfile = null; } //Console.WriteLine(DateTime.Now.Millisecond); if (updatescreen.AddMilliseconds(300) < DateTime.Now) { try { updatePlayPauseButton(true); updateLogPlayPosition(); } catch { log.Error("Failed to update log playback pos"); } updatescreen = DateTime.Now; } //Console.WriteLine(DateTime.Now.Millisecond + " done "); DateTime logplayback = MainV2.comPort.lastlogread; try { MainV2.comPort.readPacket(); } catch { log.Error("Failed to read log packet"); } double act = (MainV2.comPort.lastlogread - logplayback).TotalMilliseconds; if (act > 9999 || act < 0) act = 0; double ts = 0; if (LogPlayBackSpeed == 0) LogPlayBackSpeed = 0.01; try { ts = Math.Min((act / LogPlayBackSpeed), 1000); } catch { } double timetook = (DateTime.Now - tsreal).TotalMilliseconds; if (timetook != 0) { //Console.WriteLine("took: " + timetook + "=" + taketime + " " + (taketime - timetook) + " " + ts); //Console.WriteLine(MainV2.comPort.lastlogread.Second + " " + DateTime.Now.Second + " " + (MainV2.comPort.lastlogread.Second - DateTime.Now.Second)); //if ((taketime - timetook) < 0) { timeerror += (taketime - timetook); if (ts != 0) { ts += timeerror; timeerror = 0; } } if (ts > 1000) ts = 1000; } taketime = ts; tsreal = DateTime.Now; if (ts > 0 && ts < 1000) System.Threading.Thread.Sleep((int)ts); if (threadrun == 0) { return; } tracklast = tracklast.AddMilliseconds(ts - act); tunning = tunning.AddMilliseconds(ts - act); if (tracklast.Month != DateTime.Now.Month) { tracklast = DateTime.Now; tunning = DateTime.Now; } try { if (MainV2.comPort.logplaybackfile != null && MainV2.comPort.logplaybackfile.BaseStream.Position == MainV2.comPort.logplaybackfile.BaseStream.Length) { MainV2.comPort.logreadmode = false; } } catch { MainV2.comPort.logreadmode = false; } } else { // ensure we know to stop if (MainV2.comPort.logreadmode) MainV2.comPort.logreadmode = false; updatePlayPauseButton(false); if (!playingLog && MainV2.comPort.logplaybackfile != null) { continue; } } try { //Console.WriteLine(DateTime.Now.Millisecond); //int fixme; updateBindingSource(); // Console.WriteLine(DateTime.Now.Millisecond + " done "); // battery warning. float warnvolt = 0; float.TryParse(MainV2.getConfig("speechbatteryvolt"), out warnvolt); float warnpercent = 0; float.TryParse(MainV2.getConfig("speechbatterypercent"), out warnpercent); if (MainV2.comPort.MAV.cs.battery_voltage <= warnvolt) { hud1.lowvoltagealert = true; } else if ((MainV2.comPort.MAV.cs.battery_remaining) < warnpercent) { hud1.lowvoltagealert = true; } else { hud1.lowvoltagealert = false; } // update opengltest if (OpenGLtest.instance != null) { OpenGLtest.instance.rpy = new OpenTK.Vector3(MainV2.comPort.MAV.cs.roll, MainV2.comPort.MAV.cs.pitch, MainV2.comPort.MAV.cs.yaw); OpenGLtest.instance.LocationCenter = new PointLatLngAlt(MainV2.comPort.MAV.cs.lat, MainV2.comPort.MAV.cs.lng, MainV2.comPort.MAV.cs.alt, "here"); } // update vario info MissionPlanner.Utilities.Vario.SetValue(MainV2.comPort.MAV.cs.climbrate); // udpate tunning tab if (tunning.AddMilliseconds(50) < DateTime.Now && CB_tuning.Checked == true) { double time = (Environment.TickCount - tickStart) / 1000.0; if (list1item != null) list1.Add(time, (float)list1item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list2item != null) list2.Add(time, (float)list2item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list3item != null) list3.Add(time, (float)list3item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list4item != null) list4.Add(time, (float)list4item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list5item != null) list5.Add(time, (float)list5item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list6item != null) list6.Add(time, (float)list6item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list7item != null) list7.Add(time, (float)list7item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list8item != null) list8.Add(time, (float)list8item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list9item != null) list9.Add(time, (float)list9item.GetValue((object)MainV2.comPort.MAV.cs, null)); if (list10item != null) list10.Add(time, (float)list10item.GetValue((object)MainV2.comPort.MAV.cs, null)); } // update map if (tracklast.AddSeconds(1.2) < DateTime.Now && gMapControl1.Visible) { if (MainV2.config["CHK_maprotation"] != null && MainV2.config["CHK_maprotation"].ToString() == "True") { // dont holdinvalidation here setMapBearing(); } if (route == null) { route = new GMapRoute(trackPoints, "track"); routes.Routes.Add(route); } PointLatLng currentloc = new PointLatLng(MainV2.comPort.MAV.cs.lat, MainV2.comPort.MAV.cs.lng); gMapControl1.HoldInvalidation = true; int cnt = 0; while (gMapControl1.inOnPaint == true) { System.Threading.Thread.Sleep(1); cnt++; } // maintain route history length if (route.Points.Count > int.Parse(MainV2.config["NUM_tracklength"].ToString())) { // trackPoints.RemoveRange(0, trackPoints.Count - int.Parse(MainV2.config["NUM_tracklength"].ToString())); route.Points.RemoveRange(0, route.Points.Count - int.Parse(MainV2.config["NUM_tracklength"].ToString())); } // add new route point if (MainV2.comPort.MAV.cs.lat != 0) { // trackPoints.Add(currentloc); route.Points.Add(currentloc); } { while (gMapControl1.inOnPaint == true) { System.Threading.Thread.Sleep(1); cnt++; } //route = new GMapRoute(route.Points, "track"); //track.Stroke = Pens.Red; //route.Stroke = new Pen(Color.FromArgb(144, Color.Red)); //route.Stroke.Width = 5; //route.Tag = "track"; //updateClearRoutes(); gMapControl1.UpdateRouteLocalPosition(route); // update programed wp course if (waypoints.AddSeconds(5) < DateTime.Now) { //Console.WriteLine("Doing FD WP's"); updateClearMissionRouteMarkers(); foreach (MAVLink.mavlink_mission_item_t plla in MainV2.comPort.MAV.wps.Values) { if (plla.x == 0 || plla.y == 0) continue; if (plla.command == (byte)MAVLink.MAV_CMD.DO_SET_ROI) { addpolygonmarkerred(plla.seq.ToString(), plla.y, plla.x, (int)plla.z, Color.Red, routes); continue; } string tag = plla.seq.ToString(); if (plla.seq == 0 && plla.current != 2) { tag = "Home"; } if (plla.current == 2) { continue; } addpolygonmarker(tag, plla.y, plla.x, (int)plla.z, Color.White, polygons); } RegeneratePolygon(); // update rally points rallypointoverlay.Markers.Clear(); foreach (var mark in MainV2.comPort.MAV.rallypoints.Values) { rallypointoverlay.Markers.Add(new GMapMarkerRallyPt(mark)); } waypoints = DateTime.Now; } //routes.Polygons.Add(poly); if (route.Points.Count > 0) { // add primary route icon if (routes.Markers.Count != 1) { routes.Markers.Clear(); routes.Markers.Add(new GMarkerGoogle(currentloc, GMarkerGoogleType.none)); } if (MainV2.comPort.MAV.cs.mode.ToLower() == "guided" && MainV2.comPort.MAV.GuidedMode.x != 0) { addpolygonmarker("Guided Mode", MainV2.comPort.MAV.GuidedMode.y, MainV2.comPort.MAV.GuidedMode.x, (int)MainV2.comPort.MAV.GuidedMode.z, Color.Blue, routes); } if (MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.ArduPlane || MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.Ateryx) { routes.Markers[0] = (new GMapMarkerPlane(currentloc, MainV2.comPort.MAV.cs.yaw, MainV2.comPort.MAV.cs.groundcourse, MainV2.comPort.MAV.cs.nav_bearing, MainV2.comPort.MAV.cs.target_bearing) { ToolTipText = MainV2.comPort.MAV.cs.alt.ToString("0"), ToolTipMode = MarkerTooltipMode.Always }); } else if (MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.ArduRover) { routes.Markers[0] = (new GMapMarkerRover(currentloc, MainV2.comPort.MAV.cs.yaw, MainV2.comPort.MAV.cs.groundcourse, MainV2.comPort.MAV.cs.nav_bearing, MainV2.comPort.MAV.cs.target_bearing)); } else { routes.Markers[0] = (new GMapMarkerQuad(currentloc, MainV2.comPort.MAV.cs.yaw, MainV2.comPort.MAV.cs.groundcourse, MainV2.comPort.MAV.cs.nav_bearing)); } // add extra mavs int a = 1; foreach (var port in MainV2.Comports) { if (port == MainV2.comPort) continue; PointLatLng portlocation = new PointLatLng(port.MAV.cs.lat, port.MAV.cs.lng); while (routes.Markers.Count < (a + 1)) routes.Markers.Add(new GMarkerGoogle(portlocation, GMarkerGoogleType.none)); if (port.MAV.cs.firmware == MainV2.Firmwares.ArduPlane || MainV2.comPort.MAV.cs.firmware == MainV2.Firmwares.Ateryx) { routes.Markers[a] = (new GMapMarkerPlane(portlocation, port.MAV.cs.yaw, port.MAV.cs.groundcourse, port.MAV.cs.nav_bearing, port.MAV.cs.target_bearing) { ToolTipText = "MAV: " + a + " " + port.MAV.cs.alt.ToString("0"), ToolTipMode = MarkerTooltipMode.Always }); } else if (port.MAV.cs.firmware == MainV2.Firmwares.ArduRover) { routes.Markers[a] = (new GMapMarkerRover(portlocation, port.MAV.cs.yaw, port.MAV.cs.groundcourse, port.MAV.cs.nav_bearing, port.MAV.cs.target_bearing)); } else { routes.Markers[a] = (new GMapMarkerQuad(portlocation, port.MAV.cs.yaw, port.MAV.cs.groundcourse, port.MAV.cs.nav_bearing)); } a++; } if (route.Points[route.Points.Count - 1].Lat != 0 && (mapupdate.AddSeconds(3) < DateTime.Now) && CHK_autopan.Checked) { updateMapPosition(currentloc); mapupdate = DateTime.Now; } if (route.Points.Count == 1 && gMapControl1.Zoom == 3) // 3 is the default load zoom { updateMapPosition(currentloc); updateMapZoom(17); //gMapControl1.ZoomAndCenterMarkers("routes");// ZoomAndCenterRoutes("routes"); } } // add this after the mav icons are drawn if (MainV2.comPort.MAV.cs.MovingBase != null) { routes.Markers.Add(new GMarkerGoogle(currentloc, GMarkerGoogleType.blue_dot) { Position = MainV2.comPort.MAV.cs.MovingBase, ToolTipText = "Moving Base", ToolTipMode = MarkerTooltipMode.OnMouseOver }); } gMapControl1.HoldInvalidation = false; gMapControl1.Invalidate(); } tracklast = DateTime.Now; } } catch (Exception ex) { Console.WriteLine("FD Main loop exception " + ex.ToString()); } } Console.WriteLine("FD Main loop exit"); }
private void frmMapView_Load(object sender, EventArgs e) { try { RestoreWindowLocation(); //MapView myOSMMap = new MapView(); myOSMMap._myMap = gMapControl2; //Get route data table myOSMMap._oldRideData = Form1.dtOldRide; //Correction table from form1 myOSMMap._cps = Form1.cps; // Test LatLng = New York myOSMMap._initLatLng = new PointLatLng(40.730610, -73.935242); // Get route begin and set it as map center double myLat = (double)myOSMMap._oldRideData.Rows[0][6]; double myLng = (double)myOSMMap._oldRideData.Rows[0][7]; myOSMMap._initLatLng = new PointLatLng(myLat, myLng); myOSMMap._mapZoom = 17; myOSMMap.SetMapDefaults(); //Add route overlay GMapOverlay routes = new GMapOverlay("routes"); //Add markers overlay GMapOverlay markers = new GMapOverlay("markers"); myOSMMap._markers = markers; //Add axis for altitude chart List <double> AltitideXAxis = new List <double>(); myOSMMap._altDataX = AltitideXAxis; List <double> AltitideYAxis = new List <double>(); myOSMMap._altDataY = AltitideYAxis; GMapRoute route = new GMapRoute(myOSMMap.CreateFullRoute(), "GC route"); route.Stroke = new Pen(Color.Red, 3); routes.Routes.Add(route); gMapControl2.Overlays.Add(routes); //Add markers to map gMapControl2.Overlays.Add(markers); //Add selected markers to map myOSMMap._selectedMarkers = selectedMarkers; myOSMMap.AddSelectedMarkersToMap(); //Add selected Markers overlay gMapControl2.Overlays.Add(selectedMarkers); gMapControl2.Refresh(); //Add Altitude chart formsPlot1.plt.PlotScatter(AltitideXAxis.ToArray(), AltitideYAxis.ToArray()); formsPlot1.Render(); } catch (Exception) { throw; } }
private void mainloop() { threadrun = true; EndPoint Remote = new IPEndPoint(IPAddress.Any, 0); DateTime tracklast = DateTime.Now.AddSeconds(0); DateTime tunning = DateTime.Now.AddSeconds(0); DateTime mapupdate = DateTime.Now.AddSeconds(0); DateTime vidrec = DateTime.Now.AddSeconds(0); DateTime waypoints = DateTime.Now.AddSeconds(0); DateTime updatescreen = DateTime.Now; DateTime tsreal = DateTime.Now; double taketime = 0; double timeerror = 0; while (!IsHandleCreated) Thread.Sleep(100); while (threadrun) { if (MainV2.comPort.giveComport) { Thread.Sleep(50); updateBindingSource(); continue; } if (!MainV2.comPort.logreadmode) Thread.Sleep(50); // max is only ever 10 hz but we go a little faster to empty the serial queue try { if (aviwriter != null && vidrec.AddMilliseconds(100) <= DateTime.Now) { vidrec = DateTime.Now; hud1.streamjpgenable = true; //aviwriter.avi_start("test.avi"); // add a frame aviwriter.avi_add(hud1.streamjpg.ToArray(), (uint) hud1.streamjpg.Length); // write header - so even partial files will play aviwriter.avi_end(hud1.Width, hud1.Height, 10); } } catch { log.Error("Failed to write avi"); } // log playback if (MainV2.comPort.logreadmode && MainV2.comPort.logplaybackfile != null) { if (MainV2.comPort.BaseStream.IsOpen) { MainV2.comPort.logreadmode = false; try { MainV2.comPort.logplaybackfile.Close(); } catch { log.Error("Failed to close logfile"); } MainV2.comPort.logplaybackfile = null; } //Console.WriteLine(DateTime.Now.Millisecond); if (updatescreen.AddMilliseconds(300) < DateTime.Now) { try { updatePlayPauseButton(true); updateLogPlayPosition(); } catch { log.Error("Failed to update log playback pos"); } updatescreen = DateTime.Now; } //Console.WriteLine(DateTime.Now.Millisecond + " done "); DateTime logplayback = MainV2.comPort.lastlogread; try { if (!MainV2.comPort.giveComport) MainV2.comPort.readPacket(); } catch { log.Error("Failed to read log packet"); } double act = (MainV2.comPort.lastlogread - logplayback).TotalMilliseconds; if (act > 9999 || act < 0) act = 0; double ts = 0; if (LogPlayBackSpeed == 0) LogPlayBackSpeed = 0.01; try { ts = Math.Min((act/LogPlayBackSpeed), 1000); } catch { } double timetook = (DateTime.Now - tsreal).TotalMilliseconds; if (timetook != 0) { //Console.WriteLine("took: " + timetook + "=" + taketime + " " + (taketime - timetook) + " " + ts); //Console.WriteLine(MainV2.comPort.lastlogread.Second + " " + DateTime.Now.Second + " " + (MainV2.comPort.lastlogread.Second - DateTime.Now.Second)); //if ((taketime - timetook) < 0) { timeerror += (taketime - timetook); if (ts != 0) { ts += timeerror; timeerror = 0; } } if (Math.Abs(ts) > 1000) ts = 1000; } taketime = ts; tsreal = DateTime.Now; if (ts > 0 && ts < 1000) Thread.Sleep((int) ts); tracklast = tracklast.AddMilliseconds(ts - act); tunning = tunning.AddMilliseconds(ts - act); if (tracklast.Month != DateTime.Now.Month) { tracklast = DateTime.Now; tunning = DateTime.Now; } try { if (MainV2.comPort.logplaybackfile != null && MainV2.comPort.logplaybackfile.BaseStream.Position == MainV2.comPort.logplaybackfile.BaseStream.Length) { MainV2.comPort.logreadmode = false; } } catch { MainV2.comPort.logreadmode = false; } } else { // ensure we know to stop if (MainV2.comPort.logreadmode) MainV2.comPort.logreadmode = false; updatePlayPauseButton(false); if (!playingLog && MainV2.comPort.logplaybackfile != null) { continue; } } try { CheckAndBindPreFlightData(); //Console.WriteLine(DateTime.Now.Millisecond); //int fixme; updateBindingSource(); // Console.WriteLine(DateTime.Now.Millisecond + " done "); // battery warning. float warnvolt = Settings.Instance.GetFloat("speechbatteryvolt"); float warnpercent = Settings.Instance.GetFloat("speechbatterypercent"); if (MainV2.comPort.MAV.cs.battery_voltage <= warnvolt) { hud1.lowvoltagealert = true; } else if ((MainV2.comPort.MAV.cs.battery_remaining) < warnpercent) { hud1.lowvoltagealert = true; } else { hud1.lowvoltagealert = false; } // update opengltest if (OpenGLtest.instance != null) { OpenGLtest.instance.rpy = new Vector3(MainV2.comPort.MAV.cs.roll, MainV2.comPort.MAV.cs.pitch, MainV2.comPort.MAV.cs.yaw); OpenGLtest.instance.LocationCenter = new PointLatLngAlt(MainV2.comPort.MAV.cs.lat, MainV2.comPort.MAV.cs.lng, MainV2.comPort.MAV.cs.alt, "here"); } // update opengltest2 if (OpenGLtest2.instance != null) { OpenGLtest2.instance.rpy = new Vector3(MainV2.comPort.MAV.cs.roll, MainV2.comPort.MAV.cs.pitch, MainV2.comPort.MAV.cs.yaw); OpenGLtest2.instance.LocationCenter = new PointLatLngAlt(MainV2.comPort.MAV.cs.lat, MainV2.comPort.MAV.cs.lng, MainV2.comPort.MAV.cs.alt, "here"); } // update vario info Vario.SetValue(MainV2.comPort.MAV.cs.climbrate); // udpate tunning tab if (tunning.AddMilliseconds(50) < DateTime.Now && CB_tuning.Checked) { double time = (Environment.TickCount - tickStart)/1000.0; if (list1item != null) list1.Add(time, ConvertToDouble(list1item.GetValue(MainV2.comPort.MAV.cs, null))); if (list2item != null) list2.Add(time, ConvertToDouble(list2item.GetValue(MainV2.comPort.MAV.cs, null))); if (list3item != null) list3.Add(time, ConvertToDouble(list3item.GetValue(MainV2.comPort.MAV.cs, null))); if (list4item != null) list4.Add(time, ConvertToDouble(list4item.GetValue(MainV2.comPort.MAV.cs, null))); if (list5item != null) list5.Add(time, ConvertToDouble(list5item.GetValue(MainV2.comPort.MAV.cs, null))); if (list6item != null) list6.Add(time, ConvertToDouble(list6item.GetValue(MainV2.comPort.MAV.cs, null))); if (list7item != null) list7.Add(time, ConvertToDouble(list7item.GetValue(MainV2.comPort.MAV.cs, null))); if (list8item != null) list8.Add(time, ConvertToDouble(list8item.GetValue(MainV2.comPort.MAV.cs, null))); if (list9item != null) list9.Add(time, ConvertToDouble(list9item.GetValue(MainV2.comPort.MAV.cs, null))); if (list10item != null) list10.Add(time, ConvertToDouble(list10item.GetValue(MainV2.comPort.MAV.cs, null))); } // update map if (tracklast.AddSeconds(1.2) < DateTime.Now) { // show disable joystick button if (MainV2.joystick != null && MainV2.joystick.enabled) { this.Invoke((MethodInvoker) delegate { but_disablejoystick.Visible = true; }); } if (Settings.Instance.GetBoolean("CHK_maprotation")) { // dont holdinvalidation here setMapBearing(); } if (route == null) { route = new GMapRoute(trackPoints, "track"); routes.Routes.Add(route); } PointLatLng currentloc = new PointLatLng(MainV2.comPort.MAV.cs.lat, MainV2.comPort.MAV.cs.lng); gMapControl1.HoldInvalidation = true; int numTrackLength = Settings.Instance.GetInt32("NUM_tracklength"); // maintain route history length if (route.Points.Count > numTrackLength) { route.Points.RemoveRange(0, route.Points.Count - numTrackLength); } // add new route point if (MainV2.comPort.MAV.cs.lat != 0 && MainV2.comPort.MAV.cs.lng != 0) { route.Points.Add(currentloc); } gMapControl1.UpdateRouteLocalPosition(route); // update programed wp course if (waypoints.AddSeconds(5) < DateTime.Now) { //Console.WriteLine("Doing FD WP's"); updateClearMissionRouteMarkers(); float dist = 0; float travdist = 0; distanceBar1.ClearWPDist(); MAVLink.mavlink_mission_item_t lastplla = new MAVLink.mavlink_mission_item_t(); MAVLink.mavlink_mission_item_t home = new MAVLink.mavlink_mission_item_t(); foreach (MAVLink.mavlink_mission_item_t plla in MainV2.comPort.MAV.wps.Values) { if (plla.x == 0 || plla.y == 0) continue; if (plla.command == (ushort)MAVLink.MAV_CMD.DO_SET_ROI) { addpolygonmarkerred(plla.seq.ToString(), plla.y, plla.x, (int) plla.z, Color.Red, routes); continue; } string tag = plla.seq.ToString(); if (plla.seq == 0 && plla.current != 2) { tag = "Home"; home = plla; } if (plla.current == 2) { continue; } if (lastplla.command == 0) lastplla = plla; try { dist = (float) new PointLatLngAlt(plla.x, plla.y).GetDistance(new PointLatLngAlt( lastplla.x, lastplla.y)); distanceBar1.AddWPDist(dist); if (plla.seq <= MainV2.comPort.MAV.cs.wpno) { travdist += dist; } lastplla = plla; } catch { } addpolygonmarker(tag, plla.y, plla.x, (int) plla.z, Color.White, polygons); } try { //dist = (float)new PointLatLngAlt(home.x, home.y).GetDistance(new PointLatLngAlt(lastplla.x, lastplla.y)); // distanceBar1.AddWPDist(dist); } catch { } travdist -= MainV2.comPort.MAV.cs.wp_dist; if (MainV2.comPort.MAV.cs.mode.ToUpper() == "AUTO") distanceBar1.traveleddist = travdist; RegeneratePolygon(); // update rally points rallypointoverlay.Markers.Clear(); foreach (var mark in MainV2.comPort.MAV.rallypoints.Values) { rallypointoverlay.Markers.Add(new GMapMarkerRallyPt(mark)); } // optional on Flight data if (MainV2.ShowAirports) { // airports foreach (var item in Airports.getAirports(gMapControl1.Position)) { rallypointoverlay.Markers.Add(new GMapMarkerAirport(item) { ToolTipText = item.Tag, ToolTipMode = MarkerTooltipMode.OnMouseOver }); } } waypoints = DateTime.Now; } updateClearRoutesMarkers(); // add this after the mav icons are drawn if (MainV2.comPort.MAV.cs.MovingBase != null) { addMissionRouteMarker(new GMarkerGoogle(currentloc, GMarkerGoogleType.blue_dot) { Position = MainV2.comPort.MAV.cs.MovingBase, ToolTipText = "Moving Base", ToolTipMode = MarkerTooltipMode.OnMouseOver }); } // add gimbal point center try { if (MainV2.comPort.MAV.param.ContainsKey("MNT_STAB_TILT")) { float temp1 = (float)MainV2.comPort.MAV.param["MNT_STAB_TILT"]; float temp2 = (float)MainV2.comPort.MAV.param["MNT_STAB_ROLL"]; float temp3 = (float)MainV2.comPort.MAV.param["MNT_TYPE"]; if (MainV2.comPort.MAV.param.ContainsKey("MNT_STAB_PAN") && // (float)MainV2.comPort.MAV.param["MNT_STAB_PAN"] == 1 && ((float)MainV2.comPort.MAV.param["MNT_STAB_TILT"] == 1 && (float)MainV2.comPort.MAV.param["MNT_STAB_ROLL"] == 0) || (float)MainV2.comPort.MAV.param["MNT_TYPE"] == 4) // storm driver { var marker = GimbalPoint.ProjectPoint(); if (marker != PointLatLngAlt.Zero) { MainV2.comPort.MAV.cs.GimbalPoint = marker; addMissionRouteMarker(new GMarkerGoogle(marker, GMarkerGoogleType.blue_dot) { ToolTipText = "Camera Target\n" + marker, ToolTipMode = MarkerTooltipMode.OnMouseOver }); } } } // cleanup old - no markers where added, so remove all old if (MainV2.comPort.MAV.camerapoints.Count == 0) photosoverlay.Markers.Clear(); var min_interval = 0.0; if (MainV2.comPort.MAV.param.ContainsKey("CAM_MIN_INTERVAL")) min_interval = MainV2.comPort.MAV.param["CAM_MIN_INTERVAL"].Value/1000.0; // set fov's based on last grid calc if (Settings.Instance["camera_fovh"] != null) { GMapMarkerPhoto.hfov = Settings.Instance.GetDouble("camera_fovh"); GMapMarkerPhoto.vfov = Settings.Instance.GetDouble("camera_fovv"); } // add new - populate camera_feedback to map double oldtime = double.MinValue; foreach (var mark in MainV2.comPort.MAV.camerapoints.ToArray()) { var timesincelastshot = (mark.time_usec/1000.0)/1000.0 - oldtime; MainV2.comPort.MAV.cs.timesincelastshot = timesincelastshot; bool contains = photosoverlay.Markers.Any(p => p.Tag.Equals(mark.time_usec)); if (!contains) { if (timesincelastshot < min_interval) addMissionPhotoMarker(new GMapMarkerPhoto(mark, true)); else addMissionPhotoMarker(new GMapMarkerPhoto(mark, false)); } oldtime = (mark.time_usec/1000.0)/1000.0; } // age current int camcount = MainV2.comPort.MAV.camerapoints.Count; int a = 0; foreach (var mark in photosoverlay.Markers) { if (mark is GMapMarkerPhoto) { if (CameraOverlap) { var marker = ((GMapMarkerPhoto) mark); // abandon roll higher than 25 degrees if (Math.Abs(marker.Roll) < 25) { MainV2.comPort.MAV.GMapMarkerOverlapCount.Add( ((GMapMarkerPhoto) mark).footprintpoly); } } if (a < (camcount-4)) ((GMapMarkerPhoto)mark).drawfootprint = false; } a++; } if (CameraOverlap) { if (!kmlpolygons.Markers.Contains(MainV2.comPort.MAV.GMapMarkerOverlapCount) && camcount > 0) { kmlpolygons.Markers.Clear(); kmlpolygons.Markers.Add(MainV2.comPort.MAV.GMapMarkerOverlapCount); } } else if (kmlpolygons.Markers.Contains(MainV2.comPort.MAV.GMapMarkerOverlapCount)) { kmlpolygons.Markers.Clear(); } } catch { } lock (MainV2.instance.adsblock) { // cleanup old for (int a = (routes.Markers.Count - 1); a >= 0; a--) { if (routes.Markers[a].ToolTipText != null && routes.Markers[a].ToolTipText.Contains("ICAO")) { routes.Markers.RemoveAt(a); } } foreach (adsb.PointLatLngAltHdg plla in MainV2.instance.adsbPlanes.Values) { // 30 seconds history if (((DateTime) plla.Time) > DateTime.Now.AddSeconds(-30)) { var adsbplane = new GMapMarkerADSBPlane(plla, plla.Heading) { ToolTipText = "ICAO: " + plla.Tag + " " + plla.Alt.ToString("0"), ToolTipMode = MarkerTooltipMode.OnMouseOver, }; switch (plla.ThreatLevel) { case MAVLink.MAV_COLLISION_THREAT_LEVEL.NONE: adsbplane.AlertLevel = GMapMarkerADSBPlane.AlertLevelOptions.Green; break; case MAVLink.MAV_COLLISION_THREAT_LEVEL.LOW: adsbplane.AlertLevel = GMapMarkerADSBPlane.AlertLevelOptions.Orange; break; case MAVLink.MAV_COLLISION_THREAT_LEVEL.HIGH: adsbplane.AlertLevel = GMapMarkerADSBPlane.AlertLevelOptions.Red; break; } addMissionRouteMarker(adsbplane); } } } if (route.Points.Count > 0) { // add primary route icon // draw guide mode point for only main mav if (MainV2.comPort.MAV.cs.mode.ToLower() == "guided" && MainV2.comPort.MAV.GuidedMode.x != 0) { addpolygonmarker("Guided Mode", MainV2.comPort.MAV.GuidedMode.y, MainV2.comPort.MAV.GuidedMode.x, (int)MainV2.comPort.MAV.GuidedMode.z, Color.Blue, routes); } // draw all icons for all connected mavs foreach (var port in MainV2.Comports) { // draw the mavs seen on this port foreach (var MAV in port.MAVlist) { var marker = Common.getMAVMarker(MAV); addMissionRouteMarker(marker); } } if (route.Points[route.Points.Count - 1].Lat != 0 && (mapupdate.AddSeconds(3) < DateTime.Now) && CHK_autopan.Checked) { updateMapPosition(currentloc); mapupdate = DateTime.Now; } if (route.Points.Count == 1 && gMapControl1.Zoom == 3) // 3 is the default load zoom { updateMapPosition(currentloc); updateMapZoom(17); } } gMapControl1.HoldInvalidation = false; if (gMapControl1.Visible) { gMapControl1.Invalidate(); } tracklast = DateTime.Now; } } catch (Exception ex) { log.Error(ex); Tracking.AddException(ex); Console.WriteLine("FD Main loop exception " + ex); } } Console.WriteLine("FD Main loop exit"); }
/// <summary> /// Метод сортировки адресов по мере удаленности и построения маршрута /// </summary> /// <returns></returns> private async Task Sort_Addresses() { List <Constants> start_list = await oConstantsRepository.Select_Constants_Async("select value from Constants where name=\'Address\'"); Start_address = start_list.First().value.ToString(); needded_addresses.Add(Start_address); needded_adr_copy.Add(Start_address); sorted_addresses.Add(Start_address); List <GMapRoute> routes_list = new List <GMapRoute>(); LOrders = await oOrdersRepository.Select_All_Orders_Async(); #region выборка всех нужных адресов из БД foreach (var c in LOrders) { if (c.status == "Готовится к отправке") { needded_addresses.Add(c.address.ToString()); needded_adr_copy.Add(c.address.ToString()); } } #endregion string Close_position = needded_addresses[0].ToString(); #region Сортировка адресов по мере удаленности от адреса компании for (int i = 0; i < needded_addresses.Count - 1; i++) { double min_Dist = 1000000.0; string Start_position = Close_position; int closest_id = 1; string Closest_Adr = ""; List <double> Start_position_point = m.Geocoding(Start_position); sorted_points.Add(new GMap.NET.PointLatLng(Start_position_point[0], Start_position_point[1])); for (int j = closest_id; j < needded_adr_copy.Count; j++) { if (needded_adr_copy[j] != Start_position) { double Distance = 0.0; List <double> adr_latlng = m.Geocoding(needded_adr_copy[j].ToString()); Distance = gmap_routes.MapProvider.Projection.GetDistance(new GMap.NET.PointLatLng(Start_position_point[0], Start_position_point[1]), new GMap.NET.PointLatLng(adr_latlng[0], adr_latlng[1])); if (Distance < min_Dist) { min_Dist = Distance; Closest_Adr = needded_adr_copy[j].ToString(); } } } sorted_addresses.Add(Closest_Adr.ToString()); List <double> closest_address_points = m.Geocoding(Closest_Adr.ToString()); sorted_points.Add(new GMap.NET.PointLatLng(closest_address_points[0], closest_address_points[1])); needded_adr_copy.Remove(Closest_Adr); Close_position = Closest_Adr; } #endregion GMap.NET.RoutingProvider rp = gmap_routes.MapProvider as GMap.NET.RoutingProvider; if (rp == null) { rp = GMapProviders.OpenStreetMap; } GMap.NET.MapRoute route; #region построение маршрута по отсортированным адресам for (int i = 0; i < sorted_addresses.Count - 1; i++) { List <double> first = m.Geocoding(sorted_addresses[i]); List <double> last = m.Geocoding(sorted_addresses[i + 1]); route = rp.GetRoute(new GMap.NET.PointLatLng(first[0], first[1]), new GMap.NET.PointLatLng(last[0], last[1]), false, false, (int)gmap_routes.Zoom); if (route != null) { GMapRoute mRoute = new GMapRoute(route.Points); { mRoute.ZIndex = -1; } routes_list.Add(mRoute); } } foreach (var l in routes_list) { gmap_routes.Markers.Add(l); l.RegenerateShape(gmap_routes); } #endregion }
private void mainloop() { //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en-US"); //System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); threadrun = 1; EndPoint Remote = (EndPoint)(new IPEndPoint(IPAddress.Any, 0)); DateTime lastdata = DateTime.MinValue; DateTime tracklast = DateTime.Now.AddSeconds(0); DateTime tunning = DateTime.Now.AddSeconds(0); DateTime vidrec = DateTime.Now.AddSeconds(0); DateTime waypoints = DateTime.Now.AddSeconds(0); //comPort.stopall(true); while (threadrun == 1) { if (threadrun == 0) { return; } if (MainV2.giveComport == true) { System.Threading.Thread.Sleep(20); continue; } if (!comPort.BaseStream.IsOpen) lastdata = DateTime.Now; // re-request servo data if (!(lastdata.AddSeconds(8) > DateTime.Now) && comPort.BaseStream.IsOpen) { //Console.WriteLine("REQ streams - flightdata"); try { //System.Threading.Thread.Sleep(1000); //comPort.requestDatastream((byte)ArdupilotMega.MAVLink09.MAV_DATA_STREAM.RAW_CONTROLLER, 0); // request servoout comPort.requestDatastream((byte)ArdupilotMega.MAVLink.MAV_DATA_STREAM.EXTENDED_STATUS, MainV2.cs.ratestatus); // mode comPort.requestDatastream((byte)ArdupilotMega.MAVLink.MAV_DATA_STREAM.POSITION, MainV2.cs.rateposition); // request gps comPort.requestDatastream((byte)ArdupilotMega.MAVLink.MAV_DATA_STREAM.EXTRA1, MainV2.cs.rateattitude); // request attitude comPort.requestDatastream((byte)ArdupilotMega.MAVLink.MAV_DATA_STREAM.EXTRA2, MainV2.cs.rateattitude); // request vfr comPort.requestDatastream((byte)ArdupilotMega.MAVLink.MAV_DATA_STREAM.EXTRA3, MainV2.cs.ratesensors); // request extra stuff - tridge comPort.requestDatastream((byte)ArdupilotMega.MAVLink.MAV_DATA_STREAM.RAW_SENSORS, MainV2.cs.ratesensors); // request raw sensor comPort.requestDatastream((byte)ArdupilotMega.MAVLink.MAV_DATA_STREAM.RC_CHANNELS, MainV2.cs.raterc); // request rc info } catch { } lastdata = DateTime.Now.AddSeconds(120); // prevent flooding } if (!MainV2.comPort.logreadmode) System.Threading.Thread.Sleep(100); // max is only ever 10 hz try { if (aviwriter != null && vidrec.AddMilliseconds(100) <= DateTime.Now) { vidrec = DateTime.Now; hud1.streamjpgenable = true; //aviwriter.avi_start("test.avi"); // add a frame aviwriter.avi_add(hud1.streamjpg.ToArray(), (uint)hud1.streamjpg.Length); // write header - so even partial files will play aviwriter.avi_end(hud1.Width, hud1.Height, 10); } } catch { } if (MainV2.comPort.logreadmode && MainV2.comPort.logplaybackfile != null) { if (threadrun == 0) { return; } updatePlayPauseButton(true); MainV2.comPort.setAPType(); if (comPort.BaseStream.IsOpen) { MainV2.comPort.logreadmode = false; MainV2.comPort.logplaybackfile.Close(); MainV2.comPort.logplaybackfile = null; } DateTime logplayback = MainV2.comPort.lastlogread; try { MainV2.comPort.readPacket(); } catch { } updateLogPlayPosition(); int act = (int)(MainV2.comPort.lastlogread - logplayback).TotalMilliseconds; if (act > 9999 || act < 0) act = 0; int ts = 0; if (LogPlayBackSpeed == 0) LogPlayBackSpeed = 0.01; try { ts = (int) Math.Min((act / LogPlayBackSpeed),1000); } catch { } if (ts > 0) System.Threading.Thread.Sleep(ts); if (threadrun == 0) { return; } tracklast = tracklast.AddMilliseconds(ts - act); tunning = tunning.AddMilliseconds(ts - act); if (tracklast.Month != DateTime.Now.Month) { tracklast = DateTime.Now; tunning = DateTime.Now; } if (MainV2.comPort.logplaybackfile != null && MainV2.comPort.logplaybackfile.BaseStream.Position == MainV2.comPort.logplaybackfile.BaseStream.Length) { MainV2.comPort.logreadmode = false; } } else { // ensure we know to stop if (MainV2.comPort.logreadmode) MainV2.comPort.logreadmode = false; updatePlayPauseButton(false); if (!playingLog && MainV2.comPort.logplaybackfile != null) { continue; } } try { //Console.WriteLine(DateTime.Now.Millisecond); updateBindingSource(); //Console.WriteLine(DateTime.Now.Millisecond + " done "); if (ArdupilotMega.Controls.OpenGLtest.instance != null) { ArdupilotMega.Controls.OpenGLtest.instance.rpy = new OpenTK.Vector3(MainV2.cs.roll,MainV2.cs.pitch,MainV2.cs.yaw); ArdupilotMega.Controls.OpenGLtest.instance.LocationCenter = new PointLatLngAlt(MainV2.cs.lat,MainV2.cs.lng,MainV2.cs.alt,"here"); } if (tunning.AddMilliseconds(50) < DateTime.Now && CB_tuning.Checked == true) { double time = (Environment.TickCount - tickStart) / 1000.0; if (list1item != null) list1.Add(time, (float)list1item.GetValue((object)MainV2.cs, null)); if (list2item != null) list2.Add(time, (float)list2item.GetValue((object)MainV2.cs, null)); if (list3item != null) list3.Add(time, (float)list3item.GetValue((object)MainV2.cs, null)); if (list4item != null) list4.Add(time, (float)list4item.GetValue((object)MainV2.cs, null)); if (list5item != null) list5.Add(time, (float)list5item.GetValue((object)MainV2.cs, null)); if (list6item != null) list6.Add(time, (float)list6item.GetValue((object)MainV2.cs, null)); if (list7item != null) list7.Add(time, (float)list7item.GetValue((object)MainV2.cs, null)); if (list8item != null) list8.Add(time, (float)list8item.GetValue((object)MainV2.cs, null)); if (list9item != null) list9.Add(time, (float)list9item.GetValue((object)MainV2.cs, null)); if (list10item != null) list10.Add(time, (float)list10item.GetValue((object)MainV2.cs, null)); } if (tracklast.AddSeconds(1) < DateTime.Now) { if (MainV2.config["CHK_maprotation"] != null && MainV2.config["CHK_maprotation"].ToString() == "True") { setMapBearing(); } gMapControl1.HoldInvalidation = true; while (gMapControl1.inOnPaint == true) { System.Threading.Thread.Sleep(1); } if (trackPoints.Count > int.Parse(MainV2.config["NUM_tracklength"].ToString())) { trackPoints.RemoveRange(0, trackPoints.Count - int.Parse(MainV2.config["NUM_tracklength"].ToString())); } if (MainV2.cs.lat != 0) trackPoints.Add(new PointLatLng(MainV2.cs.lat, MainV2.cs.lng)); // if (CB_tuning.Checked == false) // draw if in view { if (MainV2.comPort.logreadmode && MainV2.comPort.logplaybackfile != null) { // this is for the pulled wp list from a mavlink logfile FlightPlanner.pointlist.Clear(); FlightPlanner.pointlist.AddRange(MainV2.comPort.wps); } while (gMapControl1.inOnPaint == true) { System.Threading.Thread.Sleep(1); } updateClearRoutes(); route = new GMapRoute(trackPoints, "track"); //track.Stroke = Pens.Red; //route.Stroke = new Pen(Color.FromArgb(144, Color.Red)); //route.Stroke.Width = 5; //route.Tag = "track"; routes.Routes.Add(route); if (waypoints.AddSeconds(10) < DateTime.Now) { //Console.WriteLine("Doing FD WP's"); polygons.Markers.Clear(); foreach (PointLatLngAlt plla in FlightPlanner.pointlist) { if (plla == null || plla.Lng == 0 || plla.Lat == 0) break; addpolygonmarker(plla.Tag, plla.Lng, plla.Lat, (int)plla.Alt,plla.color,polygons); } RegeneratePolygon(); waypoints = DateTime.Now; } if (MainV2.cs.mode.ToLower() == "guided" && GuidedModeWP != null && GuidedModeWP.Lat != 0) { addpolygonmarker("Guided Mode", GuidedModeWP.Lng, GuidedModeWP.Lat, (int)GuidedModeWP.Alt, Color.Blue, routes); } //routes.Polygons.Add(poly); if (trackPoints.Count > 0) { PointLatLng currentloc = new PointLatLng(MainV2.cs.lat, MainV2.cs.lng); if (MainV2.cs.firmware == MainV2.Firmwares.ArduPlane) { routes.Markers.Add(new GMapMarkerPlane(currentloc, MainV2.cs.yaw, MainV2.cs.groundcourse, MainV2.cs.nav_bearing, MainV2.cs.target_bearing, gMapControl1)); } else if (MainV2.cs.firmware == MainV2.Firmwares.ArduRover) { routes.Markers.Add(new GMapMarkerRover(currentloc, MainV2.cs.yaw, MainV2.cs.groundcourse, MainV2.cs.nav_bearing, MainV2.cs.target_bearing, gMapControl1)); } else { routes.Markers.Add(new GMapMarkerQuad(currentloc, MainV2.cs.yaw, MainV2.cs.groundcourse, MainV2.cs.nav_bearing)); } if (trackPoints[trackPoints.Count - 1].Lat != 0 && (DateTime.Now.Second % 4 == 0) && CHK_autopan.Checked) { updateMapPosition(currentloc); } if (trackPoints.Count == 1 && gMapControl1.Zoom == 3) // 3 is the default load zoom { updateMapPosition(currentloc); updateMapZoom(17); //gMapControl1.ZoomAndCenterMarkers("routes");// ZoomAndCenterRoutes("routes"); } } gMapControl1.HoldInvalidation = false; gMapControl1.Invalidate(); } tracklast = DateTime.Now; } } catch (Exception ex) { Console.WriteLine("FD Main loop exception " + ex.ToString()); } } Console.WriteLine("FD Main loop exit"); }
void MainMap_OnRouteLeave(GMapRoute item) { currentRoute = null; item.Stroke.Color = Color.MidnightBlue; //Debug.WriteLine("OnRouteLeave: " + item.Name); }
private void mainloop() { threadrun = true; EndPoint Remote = new IPEndPoint(IPAddress.Any, 0); DateTime tracklast = DateTime.Now.AddSeconds(0); DateTime tunning = DateTime.Now.AddSeconds(0); DateTime mapupdate = DateTime.Now.AddSeconds(0); DateTime vidrec = DateTime.Now.AddSeconds(0); DateTime waypoints = DateTime.Now.AddSeconds(0); DateTime updatescreen = DateTime.Now; DateTime tsreal = DateTime.Now; double taketime = 0; double timeerror = 0; //comPort.stopall(true); while (threadrun) { if (MainV2.comPort.giveComport) { Thread.Sleep(50); continue; } if (!MainV2.comPort.logreadmode) Thread.Sleep(50); // max is only ever 10 hz but we go a little faster to empty the serial queue try { if (aviwriter != null && vidrec.AddMilliseconds(100) <= DateTime.Now) { vidrec = DateTime.Now; hud1.streamjpgenable = true; //aviwriter.avi_start("test.avi"); // add a frame aviwriter.avi_add(hud1.streamjpg.ToArray(), (uint) hud1.streamjpg.Length); // write header - so even partial files will play aviwriter.avi_end(hud1.Width, hud1.Height, 10); } } catch { log.Error("Failed to write avi"); } // log playback if (MainV2.comPort.logreadmode && MainV2.comPort.logplaybackfile != null) { if (MainV2.comPort.BaseStream.IsOpen) { MainV2.comPort.logreadmode = false; try { MainV2.comPort.logplaybackfile.Close(); } catch { log.Error("Failed to close logfile"); } MainV2.comPort.logplaybackfile = null; } //Console.WriteLine(DateTime.Now.Millisecond); if (updatescreen.AddMilliseconds(300) < DateTime.Now) { try { updatePlayPauseButton(true); updateLogPlayPosition(); } catch { log.Error("Failed to update log playback pos"); } updatescreen = DateTime.Now; } //Console.WriteLine(DateTime.Now.Millisecond + " done "); DateTime logplayback = MainV2.comPort.lastlogread; try { MainV2.comPort.readPacket(); } catch { log.Error("Failed to read log packet"); } double act = (MainV2.comPort.lastlogread - logplayback).TotalMilliseconds; if (act > 9999 || act < 0) act = 0; double ts = 0; if (LogPlayBackSpeed == 0) LogPlayBackSpeed = 0.01; try { ts = Math.Min((act/LogPlayBackSpeed), 1000); } catch { } double timetook = (DateTime.Now - tsreal).TotalMilliseconds; if (timetook != 0) { //Console.WriteLine("took: " + timetook + "=" + taketime + " " + (taketime - timetook) + " " + ts); //Console.WriteLine(MainV2.comPort.lastlogread.Second + " " + DateTime.Now.Second + " " + (MainV2.comPort.lastlogread.Second - DateTime.Now.Second)); //if ((taketime - timetook) < 0) { timeerror += (taketime - timetook); if (ts != 0) { ts += timeerror; timeerror = 0; } } if (Math.Abs(ts) > 1000) ts = 1000; } taketime = ts; tsreal = DateTime.Now; if (ts > 0 && ts < 1000) Thread.Sleep((int) ts); tracklast = tracklast.AddMilliseconds(ts - act); tunning = tunning.AddMilliseconds(ts - act); if (tracklast.Month != DateTime.Now.Month) { tracklast = DateTime.Now; tunning = DateTime.Now; } try { if (MainV2.comPort.logplaybackfile != null && MainV2.comPort.logplaybackfile.BaseStream.Position == MainV2.comPort.logplaybackfile.BaseStream.Length) { MainV2.comPort.logreadmode = false; } } catch { MainV2.comPort.logreadmode = false; } } else { // ensure we know to stop if (MainV2.comPort.logreadmode) MainV2.comPort.logreadmode = false; updatePlayPauseButton(false); if (!playingLog && MainV2.comPort.logplaybackfile != null) { continue; } } try { CheckAndBindPreFlightData(); //Console.WriteLine(DateTime.Now.Millisecond); //int fixme; updateBindingSource(); // Console.WriteLine(DateTime.Now.Millisecond + " done "); // battery warning. float warnvolt = 0; float.TryParse(MainV2.getConfig("speechbatteryvolt"), out warnvolt); float warnpercent = 0; float.TryParse(MainV2.getConfig("speechbatterypercent"), out warnpercent); if (MainV2.comPort.MAV.cs.battery_voltage <= warnvolt) { hud1.lowvoltagealert = true; } else if ((MainV2.comPort.MAV.cs.battery_remaining) < warnpercent) { hud1.lowvoltagealert = true; } else { hud1.lowvoltagealert = false; } // update opengltest if (OpenGLtest.instance != null) { OpenGLtest.instance.rpy = new Vector3(MainV2.comPort.MAV.cs.roll, MainV2.comPort.MAV.cs.pitch, MainV2.comPort.MAV.cs.yaw); OpenGLtest.instance.LocationCenter = new PointLatLngAlt(MainV2.comPort.MAV.cs.lat, MainV2.comPort.MAV.cs.lng, MainV2.comPort.MAV.cs.alt, "here"); } // update opengltest2 if (OpenGLtest2.instance != null) { OpenGLtest2.instance.rpy = new Vector3(MainV2.comPort.MAV.cs.roll, MainV2.comPort.MAV.cs.pitch, MainV2.comPort.MAV.cs.yaw); OpenGLtest2.instance.LocationCenter = new PointLatLngAlt(MainV2.comPort.MAV.cs.lat, MainV2.comPort.MAV.cs.lng, MainV2.comPort.MAV.cs.alt, "here"); } // update vario info Vario.SetValue(MainV2.comPort.MAV.cs.climbrate); // udpate tunning tab if (tunning.AddMilliseconds(50) < DateTime.Now && CB_tuning.Checked) { double time = (Environment.TickCount - tickStart)/1000.0; if (list1item != null) list1.Add(time, ConvertToDouble(list1item.GetValue(MainV2.comPort.MAV.cs, null))); if (list2item != null) list2.Add(time, ConvertToDouble(list2item.GetValue(MainV2.comPort.MAV.cs, null))); if (list3item != null) list3.Add(time, ConvertToDouble(list3item.GetValue(MainV2.comPort.MAV.cs, null))); if (list4item != null) list4.Add(time, ConvertToDouble(list4item.GetValue(MainV2.comPort.MAV.cs, null))); if (list5item != null) list5.Add(time, ConvertToDouble(list5item.GetValue(MainV2.comPort.MAV.cs, null))); if (list6item != null) list6.Add(time, ConvertToDouble(list6item.GetValue(MainV2.comPort.MAV.cs, null))); if (list7item != null) list7.Add(time, ConvertToDouble(list7item.GetValue(MainV2.comPort.MAV.cs, null))); if (list8item != null) list8.Add(time, ConvertToDouble(list8item.GetValue(MainV2.comPort.MAV.cs, null))); if (list9item != null) list9.Add(time, ConvertToDouble(list9item.GetValue(MainV2.comPort.MAV.cs, null))); if (list10item != null) list10.Add(time, ConvertToDouble(list10item.GetValue(MainV2.comPort.MAV.cs, null))); } // update map if (tracklast.AddSeconds(1.2) < DateTime.Now) { if (MainV2.config["CHK_maprotation"] != null && MainV2.config["CHK_maprotation"].ToString() == "True") { // dont holdinvalidation here setMapBearing(); } if (route == null) { route = new GMapRoute(trackPoints, "track"); routes.Routes.Add(route); } PointLatLng currentloc = new PointLatLng(MainV2.comPort.MAV.cs.lat, MainV2.comPort.MAV.cs.lng); gMapControl1.HoldInvalidation = true; int cnt = 0; while (gMapControl1.inOnPaint) { Thread.Sleep(1); cnt++; } // maintain route history length if (route.Points.Count > int.Parse(MainV2.config["NUM_tracklength"].ToString())) { // trackPoints.RemoveRange(0, trackPoints.Count - int.Parse(MainV2.config["NUM_tracklength"].ToString())); route.Points.RemoveRange(0, route.Points.Count - int.Parse(MainV2.config["NUM_tracklength"].ToString())); } // add new route point if (MainV2.comPort.MAV.cs.lat != 0) { // trackPoints.Add(currentloc); route.Points.Add(currentloc); } while (gMapControl1.inOnPaint) { Thread.Sleep(1); cnt++; } //route = new GMapRoute(route.Points, "track"); //track.Stroke = Pens.Red; //route.Stroke = new Pen(Color.FromArgb(144, Color.Red)); //route.Stroke.Width = 5; //route.Tag = "track"; //updateClearRoutes(); gMapControl1.UpdateRouteLocalPosition(route); // update programed wp course if (waypoints.AddSeconds(5) < DateTime.Now) { //Console.WriteLine("Doing FD WP's"); updateClearMissionRouteMarkers(); float dist = 0; float travdist = 0; distanceBar1.ClearWPDist(); MAVLink.mavlink_mission_item_t lastplla = new MAVLink.mavlink_mission_item_t(); MAVLink.mavlink_mission_item_t home = new MAVLink.mavlink_mission_item_t(); foreach (MAVLink.mavlink_mission_item_t plla in MainV2.comPort.MAV.wps.Values) { if (plla.x == 0 || plla.y == 0) continue; if (plla.command == (byte) MAVLink.MAV_CMD.DO_SET_ROI) { addpolygonmarkerred(plla.seq.ToString(), plla.y, plla.x, (int) plla.z, Color.Red, routes); continue; } string tag = plla.seq.ToString(); if (plla.seq == 0 && plla.current != 2) { tag = "Home"; home = plla; } if (plla.current == 2) { continue; } if (lastplla.command == 0) lastplla = plla; try { dist = (float) new PointLatLngAlt(plla.x, plla.y).GetDistance(new PointLatLngAlt( lastplla.x, lastplla.y)); distanceBar1.AddWPDist(dist); if (plla.seq <= MainV2.comPort.MAV.cs.wpno) { travdist += dist; } lastplla = plla; } catch { } addpolygonmarker(tag, plla.y, plla.x, (int) plla.z, Color.White, polygons); } try { //dist = (float)new PointLatLngAlt(home.x, home.y).GetDistance(new PointLatLngAlt(lastplla.x, lastplla.y)); // distanceBar1.AddWPDist(dist); } catch { } travdist -= MainV2.comPort.MAV.cs.wp_dist; if (MainV2.comPort.MAV.cs.mode.ToUpper() == "AUTO") distanceBar1.traveleddist = travdist; RegeneratePolygon(); // update rally points rallypointoverlay.Markers.Clear(); foreach (var mark in MainV2.comPort.MAV.rallypoints.Values) { rallypointoverlay.Markers.Add(new GMapMarkerRallyPt(mark)); } // optional on Flight data if (MainV2.ShowAirports) { // airports foreach (var item in Airports.getAirports(gMapControl1.Position)) { rallypointoverlay.Markers.Add(new GMapMarkerAirport(item) { ToolTipText = item.Tag, ToolTipMode = MarkerTooltipMode.OnMouseOver }); } } waypoints = DateTime.Now; } //routes.Polygons.Add(poly); if (route.Points.Count > 0) { // add primary route icon updateClearRouteMarker(currentloc); // draw guide mode point for only main mav if (MainV2.comPort.MAV.cs.mode.ToLower() == "guided" && MainV2.comPort.MAV.GuidedMode.x != 0) { addpolygonmarker("Guided Mode", MainV2.comPort.MAV.GuidedMode.y, MainV2.comPort.MAV.GuidedMode.x, (int) MainV2.comPort.MAV.GuidedMode.z, Color.Blue, routes); } // draw all icons for all connected mavs foreach (var port in MainV2.Comports) { // draw the mavs seen on this port foreach (var MAV in port.MAVlist.GetMAVStates()) { PointLatLng portlocation = new PointLatLng(MAV.cs.lat, MAV.cs.lng); if (MAV.cs.firmware == MainV2.Firmwares.ArduPlane || MAV.cs.firmware == MainV2.Firmwares.Ateryx) { routes.Markers.Add(new GMapMarkerPlane(portlocation, MAV.cs.yaw, MAV.cs.groundcourse, MAV.cs.nav_bearing, MAV.cs.target_bearing) { ToolTipText = MAV.cs.alt.ToString("0"), ToolTipMode = MarkerTooltipMode.Always }); } else if (MAV.cs.firmware == MainV2.Firmwares.ArduRover) { routes.Markers.Add(new GMapMarkerRover(portlocation, MAV.cs.yaw, MAV.cs.groundcourse, MAV.cs.nav_bearing, MAV.cs.target_bearing)); } else if (MAV.aptype == MAVLink.MAV_TYPE.HELICOPTER) { routes.Markers.Add(new GMapMarkerHeli(portlocation, MAV.cs.yaw, MAV.cs.groundcourse, MAV.cs.nav_bearing)); } else if (MAV.cs.firmware == MainV2.Firmwares.ArduTracker) { routes.Markers.Add(new GMapMarkerAntennaTracker(portlocation, MAV.cs.yaw, MAV.cs.target_bearing)); } else if (MAV.cs.firmware == MainV2.Firmwares.ArduCopter2) { routes.Markers.Add(new GMapMarkerQuad(portlocation, MAV.cs.yaw, MAV.cs.groundcourse, MAV.cs.nav_bearing, MAV.sysid)); } else { // unknown type routes.Markers.Add(new GMarkerGoogle(portlocation, GMarkerGoogleType.green_dot)); } } } if (route.Points[route.Points.Count - 1].Lat != 0 && (mapupdate.AddSeconds(3) < DateTime.Now) && CHK_autopan.Checked) { updateMapPosition(currentloc); mapupdate = DateTime.Now; } if (route.Points.Count == 1 && gMapControl1.Zoom == 3) // 3 is the default load zoom { updateMapPosition(currentloc); updateMapZoom(17); //gMapControl1.ZoomAndCenterMarkers("routes");// ZoomAndCenterRoutes("routes"); } } // add this after the mav icons are drawn if (MainV2.comPort.MAV.cs.MovingBase != null) { routes.Markers.Add(new GMarkerGoogle(currentloc, GMarkerGoogleType.blue_dot) { Position = MainV2.comPort.MAV.cs.MovingBase, ToolTipText = "Moving Base", ToolTipMode = MarkerTooltipMode.OnMouseOver }); } // for testing try { if (MainV2.comPort.MAV.param.ContainsKey("MNT_STAB_TILT")) { float temp1 = (float) MainV2.comPort.MAV.param["MNT_STAB_TILT"]; float temp2 = (float) MainV2.comPort.MAV.param["MNT_STAB_ROLL"]; float temp3 = (float) MainV2.comPort.MAV.param["MNT_TYPE"]; if (MainV2.comPort.MAV.param.ContainsKey("MNT_STAB_PAN") && // (float)MainV2.comPort.MAV.param["MNT_STAB_PAN"] == 1 && ((float) MainV2.comPort.MAV.param["MNT_STAB_TILT"] == 1 && (float) MainV2.comPort.MAV.param["MNT_STAB_ROLL"] == 0) || (float) MainV2.comPort.MAV.param["MNT_TYPE"] == 4) // storm driver { var marker = GimbalPoint.ProjectPoint(); if (marker != PointLatLngAlt.Zero) { MainV2.comPort.MAV.cs.GimbalPoint = marker; routes.Markers.Add(new GMarkerGoogle(marker, GMarkerGoogleType.blue_dot) { ToolTipText = "Camera Target\n" + marker, ToolTipMode = MarkerTooltipMode.OnMouseOver }); } } } } catch { } lock (MainV2.instance.adsblock) { for (int a = (routes.Markers.Count - 1); a >= 0; a--) { if (routes.Markers[a].ToolTipText != null && routes.Markers[a].ToolTipText.Contains("ICAO")) { routes.Markers.RemoveAt(a); } } foreach (adsb.PointLatLngAltHdg plla in MainV2.instance.adsbPlanes.Values) { // 30 seconds if (((DateTime) MainV2.instance.adsbPlaneAge[plla.Tag]) > DateTime.Now.AddSeconds(-30)) routes.Markers.Add(new GMapMarkerADSBPlane(plla, plla.Heading) { ToolTipText = "ICAO: " + plla.Tag + " " + plla.Alt.ToString("0"), ToolTipMode = MarkerTooltipMode.OnMouseOver }); } } // routes.Markers.Clear(); gMapControl1.HoldInvalidation = false; if (gMapControl1.Visible) { gMapControl1.Invalidate(); } tracklast = DateTime.Now; } } catch (Exception ex) { log.Error(ex); Console.WriteLine("FD Main loop exception " + ex); } } Console.WriteLine("FD Main loop exit"); }
void MainMap_OnRouteEnter(GMapRoute item) { currentRoute = item; item.Stroke.Color = Color.Red; //Debug.WriteLine("OnRouteEnter: " + item.Name); }
// Do Work private void domainUpDown1_ValueChanged(object sender, EventArgs e) { if (CMB_camera.Text != "" && sender != NUM_Distance) doCalc(); // new grid system test grid = Grid.CreateGrid(list, CurrentState.fromDistDisplayUnit((double)NUM_altitude.Value), (double)NUM_Distance.Value, (double)NUM_spacing.Value, (double)NUM_angle.Value, (double)NUM_overshoot.Value, (double)NUM_overshoot2.Value, (Grid.StartPosition)Enum.Parse(typeof(Grid.StartPosition), CMB_startfrom.Text), false, (float)NUM_Lane_Dist.Value, (float)NUM_leadin.Value); List<PointLatLng> list2 = new List<PointLatLng>(); grid.ForEach(x => { list2.Add(x); }); map.HoldInvalidation = true; routesOverlay.Routes.Clear(); routesOverlay.Polygons.Clear(); routesOverlay.Markers.Clear(); if (grid.Count == 0) { return; } if (CHK_boundary.Checked) AddDrawPolygon(); int strips = 0; int images = 0; int a = 1; PointLatLngAlt prevpoint = grid[0]; float routetotal = 0; List<PointLatLng> segment = new List<PointLatLng>(); foreach (var item in grid) { if (item.Tag == "M") { images++; if (CHK_internals.Checked) { routesOverlay.Markers.Add(new GMarkerGoogle(item, GMarkerGoogleType.green) { ToolTipText = a.ToString(), ToolTipMode = MarkerTooltipMode.OnMouseOver }); a++; segment.Add(prevpoint); segment.Add(item); prevpoint = item; } try { if (TXT_fovH.Text != "") { double fovh = double.Parse(TXT_fovH.Text); double fovv = double.Parse(TXT_fovV.Text); double startangle = 0; if (!CHK_camdirection.Checked) { startangle = 90; } double angle1 = startangle - (Math.Tan((fovv / 2.0) / (fovh / 2.0)) * rad2deg); double dist1 = Math.Sqrt(Math.Pow(fovh / 2.0, 2) + Math.Pow(fovv / 2.0, 2)); double bearing = (double)NUM_angle.Value;// (prevpoint.GetBearing(item) + 360.0) % 360; List<PointLatLng> footprint = new List<PointLatLng>(); footprint.Add(item.newpos(bearing + angle1, dist1)); footprint.Add(item.newpos(bearing + 180 - angle1, dist1)); footprint.Add(item.newpos(bearing + 180 + angle1, dist1)); footprint.Add(item.newpos(bearing - angle1, dist1)); GMapPolygon poly = new GMapPolygon(footprint, a.ToString()); poly.Stroke = new Pen(Color.FromArgb(250 - ((a * 5) % 240), 250 - ((a * 3) % 240), 250 - ((a * 9) % 240)), 1); poly.Fill = new SolidBrush(Color.FromArgb(40, Color.Purple)); if (CHK_footprints.Checked) routesOverlay.Polygons.Add(poly); } } catch { } } else { strips++; if (CHK_markers.Checked) { var marker = new GMapMarkerWP(item, a.ToString()) { ToolTipText = a.ToString(), ToolTipMode = MarkerTooltipMode.OnMouseOver }; routesOverlay.Markers.Add(marker); } segment.Add(prevpoint); segment.Add(item); prevpoint = item; a++; } GMapRoute seg = new GMapRoute(segment, "segment" + a.ToString()); seg.Stroke = new Pen(Color.Yellow, 4); seg.Stroke.DashStyle = System.Drawing.Drawing2D.DashStyle.Custom; seg.IsHitTestVisible = true; if (CHK_grid.Checked) routesOverlay.Routes.Add(seg); routetotal = routetotal + (float)seg.Distance; segment.Clear(); } /* Old way of drawing route, incase something breaks using segments GMapRoute wproute = new GMapRoute(list2, "GridRoute"); wproute.Stroke = new Pen(Color.Yellow, 4); if (chk_grid.Checked) routesOverlay.Routes.Add(wproute); */ // turn radrad = tas^2 / (tan(angle) * G) float v_sq = (float)(((float)NUM_UpDownFlySpeed.Value / CurrentState.multiplierspeed) * ((float)NUM_UpDownFlySpeed.Value / CurrentState.multiplierspeed)); float turnrad = (float)(v_sq / (float)(9.808f * Math.Tan(35 * deg2rad))); // Update Stats if (DistUnits == "Feet") { // Area float area = (float)calcpolygonarea(list) * 10.7639f; // Calculate the area in square feet lbl_area.Text = area.ToString("#") + " ft^2"; if (area < 21780f) { lbl_area.Text = area.ToString("#") + " ft^2"; } else { area = area / 43560f; if (area < 640f) { lbl_area.Text = area.ToString("0.##") + " acres"; } else { area = area / 640f; lbl_area.Text = area.ToString("0.##") + " miles^2"; } } // Distance float distance = routetotal * 3280.84f; // Calculate the distance in feet if (distance < 5280f) { lbl_distance.Text = distance.ToString("#") + " ft"; } else { distance = distance / 5280f; lbl_distance.Text = distance.ToString("0.##") + " miles"; } lbl_spacing.Text = (NUM_spacing.Value * 3.2808399m).ToString("#") + " ft"; lbl_grndres.Text = inchpixel; lbl_distbetweenlines.Text = (NUM_Distance.Value * 3.2808399m).ToString("0.##") + " ft"; lbl_footprint.Text = feet_fovH + " x " + feet_fovV + " ft"; lbl_turnrad.Text = (turnrad * 2 * 3.2808399).ToString("0") + " ft"; } else { // Meters lbl_area.Text = calcpolygonarea(list).ToString("#") + " m^2"; lbl_distance.Text = routetotal.ToString("0.##") + " km"; lbl_spacing.Text = NUM_spacing.Value.ToString("#") + " m"; lbl_grndres.Text = TXT_cmpixel.Text; lbl_distbetweenlines.Text = NUM_Distance.Value.ToString("0.##") + " m"; lbl_footprint.Text = TXT_fovH.Text + " x " + TXT_fovV.Text + " m"; lbl_turnrad.Text = (turnrad * 2).ToString("0") + " m"; } double flyspeedms = CurrentState.fromSpeedDisplayUnit((double)NUM_UpDownFlySpeed.Value); lbl_pictures.Text = images.ToString(); lbl_strips.Text = ((int)(strips / 2)).ToString(); double seconds = ((routetotal * 1000.0) / ((flyspeedms) * 0.8)); // reduce flying speed by 20 % lbl_flighttime.Text = secondsToNice(seconds); seconds = ((routetotal * 1000.0) / (flyspeedms)); lbl_photoevery.Text = secondsToNice(((double)NUM_spacing.Value / flyspeedms)); map.HoldInvalidation = false; if (!isMouseDown) map.ZoomAndCenterMarkers("routes"); CalcHeadingHold(); }
internal double GetDistRouteOSM1(Router router, DateTime selectedDate)//расчет расстояния из OSM файла { List <Order> listOrders = SelectOrders(selectedDate); List <PointLatLng> list = new List <PointLatLng>(); list.Add(new GMap.NET.PointLatLng(StartLat, StartLon)); double dist = 0; try { // double[] currCoord = GetCurrentCoord(master, dateTimePicker1.Value); double fromLat = StartLat; double fromLon = StartLon; for (int i = 0; i < listOrders.Count; i++) { if (router != null) { try { var profile = Vehicle.Car.Fastest(); var route = router.Calculate(profile, (float)fromLat, (float)fromLon, (float)Convert.ToDouble(listOrders[i].Lat), (float)Convert.ToDouble(listOrders[i].Lon)); var routeGeoJson = route.ToGeoJson(); JObject CoordinateSearch = JObject.Parse(routeGeoJson.ToString()); IList <JToken> results = CoordinateSearch["features"].Children().ToList(); IList <SearchResult> searchResults = new List <SearchResult>(); SearchResult searchResult; foreach (JToken result in results) { if (!result.ToString().Contains("\"type\": \"Point\"")) { searchResult = JsonConvert.DeserializeObject <SearchResult>(result.ToString()); searchResults.Add(searchResult); for (int d = 0; d < searchResult.geometry.coordinates.Length / 2; d++) { list.Add(new GMap.NET.PointLatLng(searchResult.geometry.coordinates[d, 1], searchResult.geometry.coordinates[d, 0])); } dist = Math.Round(Convert.ToDouble(searchResult.properties.distance), 3); } } if (dist == 0) { list.Add(new GMap.NET.PointLatLng(Convert.ToDouble(listOrders[i].Lat), Convert.ToDouble(listOrders[i].Lon))); } } catch { list.Add(new GMap.NET.PointLatLng(Convert.ToDouble(listOrders[i].Lat), Convert.ToDouble(listOrders[i].Lon))); } } else { list.Add(new GMap.NET.PointLatLng(Convert.ToDouble(listOrders[i].Lat), Convert.ToDouble(listOrders[i].Lon))); } fromLat = Convert.ToDouble(listOrders[i].Lat); fromLon = Convert.ToDouble(listOrders[i].Lon); } //dist = Math.Round(dist / 1000, 3); //master.SetGMapRoute(list, dist, order.Id); currentRoute = new GMapRoute(list, "Route" + Name); currentRoute.IsVisible = true; currentRoute.Stroke = new Pen(color[Id], 3); } catch { return(0); } return(dist); }
private void map_OnRouteLeave(GMapRoute item) { if (marker != null) { try { if (routesOverlay.Markers.Contains(marker)) routesOverlay.Markers.Remove(marker); } catch { } } }
//ovde sam dodao parametar i graf sam po sebi kako bih mogao da manipulisem s grafovima manuelno/pesaci/vozila/taksi public void drawDijkstraRoute(PointLatLng pt1, PointLatLng pt2, int i) { double ukupno = 0; currentDijkstra = new GMapRoute("Dijkstra"); switch (i) { case 0: //LUKA : za sve grafove koje su prethodno napravljeni brisem tooltiptexts za svaki cvor //mozda moze da se dobije na efikasnosti ako se pamti koji je transport izabran pre ovog izbrisiZnamenitosti(); //LUKA: ovo je sada <List<GMapMarker>,double> var tmp = graph.getDijkstraRoute(pt1, pt2); List <GMapMarker> listaMarkera = tmp.Item1; //LUKA:prolazim kroz svaki marker, uzimam mu ime znamenitosti ako je ima, i ako je ima lepim markeru tooltiptext sa imenom znamenitosti foreach (GMapMarker el in listaMarkera) { currentDijkstra.Points.Add(el.Position); el.ToolTipText = uzimanjeZnamenitostiNaOsnovuIndeksa(int.Parse(el.Tag.ToString())); if (!(el.ToolTipText).Equals("")) { el.ToolTip.Fill = Brushes.Black; el.ToolTip.Foreground = Brushes.White; el.ToolTipMode = MarkerTooltipMode.Always; gmap.Overlays[0].Markers.Add(el); } //LUKA: dodajem marker overlay } ukupno = tmp.Item2; break; case 1: izbrisiZnamenitosti(); var tmpPesaci = graphPesaci.getDijkstraRoute(pt1, pt2); listaMarkera = tmpPesaci.Item1; foreach (GMapMarker el in listaMarkera) { currentDijkstra.Points.Add(el.Position); string znamenitost = uzimanjeZnamenitostiNaOsnovuIndeksa(int.Parse(el.Tag.ToString())); if (znamenitost != "\"\"") { el.ToolTipText = znamenitost; el.ToolTip.Fill = Brushes.Black; el.ToolTip.Foreground = Brushes.White; el.ToolTipMode = MarkerTooltipMode.Always; gmap.Overlays[0].Markers.Add(el); } } ukupno = tmpPesaci.Item2; break; case 2: izbrisiZnamenitosti(); var tmpVozila = graphVozila.getDijkstraRoute(pt1, pt2); listaMarkera = tmpVozila.Item1; foreach (GMapMarker el in listaMarkera) { currentDijkstra.Points.Add(el.Position); string znamenitost = uzimanjeZnamenitostiNaOsnovuIndeksa(int.Parse(el.Tag.ToString())); if (!znamenitost.Equals("\"\"")) { el.ToolTipText = znamenitost; el.ToolTip.Fill = Brushes.Black; el.ToolTip.Foreground = Brushes.White; el.ToolTip.TextPadding = new Size(10, 10); el.ToolTipMode = MarkerTooltipMode.Always; gmap.Overlays[0].Markers.Add(el); } } ukupno = tmpVozila.Item2; break; case 3: izbrisiZnamenitosti(); var tmpTaxi = graphTaxi.getDijkstraRoute(pt1, pt2); listaMarkera = tmpTaxi.Item1; foreach (GMapMarker el in listaMarkera) { currentDijkstra.Points.Add(el.Position); string znamenitost = uzimanjeZnamenitostiNaOsnovuIndeksa(int.Parse(el.Tag.ToString())); if (!znamenitost.Equals("\"\"")) { el.ToolTipText = znamenitost; el.ToolTip.Fill = Brushes.Black; el.ToolTip.Foreground = Brushes.White; el.ToolTipMode = MarkerTooltipMode.Always; gmap.Overlays[0].Markers.Add(el); } } ukupno = tmpTaxi.Item2; break; } currentDijkstra.Stroke = new Pen(Color.Green, 5); gmap.Overlays[0].Routes.Add(currentDijkstra); //VLADAN NOVO: Rute "za spajanje" sa grafom List <PointLatLng> ptsStart = new List <PointLatLng>(); List <PointLatLng> ptsFinish = new List <PointLatLng>(); ptsStart.Add(first.Position); ptsStart.Add(positions[getNearestPoint(first)]); GMapRoute routeStart = new GMapRoute(ptsStart, ""); ptsFinish.Add(second.Position); ptsFinish.Add(positions[getNearestPoint(second)]); GMapRoute routeFinish = new GMapRoute(ptsFinish, ""); routeStart.Stroke = new Pen(Color.Blue, 5); routeFinish.Stroke = new Pen(Color.Blue, 5); gmap.Overlays[0].Routes.Add(routeStart); gmap.Overlays[0].Routes.Add(routeFinish); //VLADAN NOVO: razdaljina od pocetka/kraja do prvog u grafu double distStart = distance(first, graph.getMarkerFromInt(getNearestPoint(first))); double distFinish = distance(second, graph.getMarkerFromInt(getNearestPoint(second))); switch (i) { case 0: //LUKA : zaoukruzivanje na 2/3 decimale //VLADAN NOVO: Ubacio i "random cvorove" tbUkupno.Text = Math.Round(ukupno + distStart + distFinish, 3) + "km"; break; case 1: //brzina coveka kad pesaci je u proseku 4.5 km/h sto je 0.075 km/minut double brzina = 0.075; double vreme = (distStart + distFinish + ukupno) / brzina; tbUkupno.Text = Math.Round(vreme, 2).ToString() + " minuta"; break; case 2: tbUkupno.Text = Math.Round(ukupno + (distFinish + distStart) / 0.075, 2).ToString() + " minuta"; break; case 3: ukupno += 2.8; if (tarifa == 1) { ukupno += 1; } if (tarifa == 2) { ukupno += 0.5; } tbUkupno.Text = Math.Round(ukupno, 2).ToString() + " $"; break; } }