Home > Mobile >  Dynamically load Polygon with Positions
Dynamically load Polygon with Positions

Time:11-29

I'm trying to create a geofence with an uncertain amount of coordinates, but C# and Xamarin Forms Maps won't accept dynamically loaded-in content. I have made sure that there always will be three or more positions to create the geofence. I have tried this, with coordinates being a string array:

Polygon geofence = new Polygon
{
    StrokeColor = Color.Green,
    FillColor = Color.Green,
    Geopath = 
    {
        foreach (string coordinate in coordinates)
        {
            string[] LongAndLat = coordinate.Split(',');
            new Position(Convert.ToDouble(LongAndLat[0]), Convert.ToDouble(LongAndLat[1]));
        }
    }
};

Which basically tells me that C# doesn't expect a function within the Geopath parameters, but I don't know how to get to where I want without doing it.

Is there a way to do this correctly?

CodePudding user response:

The C# syntax isn't valid. Since the Geopath property is readonly, you have to assign the property later. This solution works:

string[] coordinates = geodata.Split(';');
                
Polygon geofence = new Polygon
{
    StrokeColor = Color.Green,
    FillColor = Color.FromRgba(0, 255, 0, 0.4)
};

foreach(string coordinate in coordinates)
{
    string[] LongAndLat = coordinate.Split(',');
    geofence.Geopath.Add(new Position(Convert.ToDouble(LongAndLat[0]), Convert.ToDouble(LongAndLat[1])));
}
  • Related