简体   繁体   中英

How to auto-add item to a list from an incoming serial data?

I'm trying to trace the real time position of an object using c# and GMap.net. Inside GMap.net, in order to trace a route, I have to use a List<PointLatLng> and then unify them using a Pen .

The problem is that I don't know where the object will be at the beginning, so I have no points to add, a part the first one.

Is it possible to add only one point to a list and update it in real time?

Or, it is possible to save the first point into a variable and then add the other points using the pervious variable's name incrementing a number by 1 each time the data is received from the serial port and then refreshing the list with the new points?

`

List<PointLatLng> points = new List<PointLatLng>();
var coordinates = new List<PointLatLng> { new PointLatLng(GPS_Latitude, GPS_Longitude) };
coordinates.Add(new PointLatLng(GPS_Latitude, GPS_Longitude));
GMapOverlay trace = new GMapOverlay("Real Time Position");
GMapRoute carroute = new GMapRoute(coordinates, "Traiectory");
gMapControl1.Overlays.Add(trace);
trace.Routes.Add(carroute);
//Pen redPen = new Pen(Color.Red, 3);
carroute.Stroke = new Pen(Color.Red, 3);

`

By this way I have only the first point but not the others. Data are received with 1hz frequence with serial port. I mean: the list count only one item and not more even if I received more than 1 datum.

Yes either of those solutions is possible.


You can have a list of points and then call .Add() whenever you want to add a point to the list (it wouldn't make sense to use a List if you're only saving a single point - if that's the case see next example). This way you have a history of all the points. You can always get the newest point by accessing the item at the last index in the list:

// Create list and (optionally) add the first point to it
var points = new List<Point> { new Point(x, y) };

// Add a new point to the list whenever you want
points.Add(new Point(newX, newY));

// Get the most recent point by getting the item at the last index
var newestPoint = points[points.Count - 1];  // Note: this will fail if the list is empty

You can also have a single point variable and then update it's coordinates either by changing the values independently: or by assigning it a new Point:

var myPoint = new Point(x, y);

// Update coordinates independently whenever you want
myPoint.X = newX; 
myPoint.Y = newY;

// Or just assign a new Point
myPoint = new Point(newX, newY);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM