我正在Xamarin.Forms.Maps.Polyline
运行时创建一个。鉴于该属性是只读的,如何动态附加位置?Polyline.Geopath
在运行时创建折线
按照文档创建折线:Xamarin.Forms Map Polygons and Polylines。此链接是代码中固定位置的教程。如何在运行时动态分配位置。
using Xamarin.Forms.Maps;
// ...
Map map = new Map
{
// ...
};
创建一个对象来存储路由数据(从json中提取的数据)
public class MapRoute
{
//[JsonPropertyName("timestamp")]
public long timestamp { get; set; }
//[JsonPropertyName("lat")]
public double lat { get; set; }
//[JsonPropertyName("lng")]
public double lng { get; set; }
public MapRoute(long v1, double v2, double v3)
{
timestamp = v1;
lat = v2;
lng = v3;
}
}
将路由对象序列化为 JsonString。
public void RouteAppend(MapRoute route)
{
JsonString.Append(JsonSerializer.Serialize(route));
JsonString.Append(",");
}
在现实生活中,jsonString中有2个以上的元素(jsonString中存储了1000多个元素)
readonly string jsonString = " [ {\"timestamp\": 1514172600000, \"Lat\": 37.33417925, \"Lng\": -122.04153133}, " + "{\"timestamp\": 1514172610000, \"Lat\": 37.33419725, \"Lng\": -122.04151333} ]";
JsonDocument doc;
JsonElement root;
private IList<Position> pos;
doc = Parse(testString);
root = doc.RootElement;
var routes = root.EnumerateArray();
while (routes.MoveNext())
{
var user = routes.Current;
pos.Add(new Position(Convert.ToDouble(user.GetProperty("lat")), Convert.ToDouble(user.GetProperty("lng"))));
}
最后,有一个pos
包含很多 的列表Position
,我将分配pos
给Geopath
。不幸的是,这是不允许的。它是一个只读属性:
// instantiate a polyline
Polyline polyline = new Polyline
{
StrokeColor = Color.Blue,
StrokeWidth = 12,
Geopath = pos // It is a readonly property, cannot assign pos to Geopath
}
// add the polyline to the map's MapElements collection
map.MapElements.Add(polyline);
如何解决这个问题?