Home > Software design >  How to fill xamarin.forms.maps with a lot of pins - Xamarin
How to fill xamarin.forms.maps with a lot of pins - Xamarin

Time:03-22

I have 1919 coordinates with latitude and longitude on txt file with this format:

    44.05215, 27.03266,
    44.05056, 27.13236,
    44.04887, 27.23206,
    44.04709, 27.33175,
    44.04522, 27.43143,
    44.04326, 27.5311,
    44.0412, 27.63077,
    44.03906, 27.73043,
    44.0345, 27.92973,
    44.10396, 22.64161,
    44.10638, 22.74137,
    44.10871, 22.84114,
    44.11095, 22.94092,
    44.1131, 23.0407,

Is there a way to fill xamarin.forms.maps with this coordinates and if it's possible how to set the coordinates on the position property and each (index 1) in label property ?

For now I set one pin on the map like that (just for test):

map.MoveToRegion(MapSpan.FromCenterAndRadius(
                        new Position(42.1499994, 24.749997),
                        Distance.FromMiles(100)));

        Pin pin = new Pin
        {
            Label = "Santa Cruz",
            Address = "The city with a boardwalk",
            Type = PinType.Place,
            Position = new Position(42.1499994, 24.749997)
        };

        map.Pins.Add(pin);

       

Since I don't want the data to be read via a text file on a mobile device, how would it be best to write static data and then to be submitted as coordinates of the pins ?

Can I get an example of how to set the coordinates in List or Array or something else and after how to set like a coordinates to the pins and set each (index 1) on the label property ?

CodePudding user response:

As one of the comments pointed out though, there are almost always better options than hardcoding. The preferable alternative would be an API call to get the positions so the app would not need to be recompiled when the positions need updated. The next best alternative would be an file or resource that a non-technical member of the team could update if needed.

However, If you're absolutely set on hardcoding the positions, I would do it in a static class with a static list:

public static class HardcodedLocations
{
    public static List<Position> Positions = new List<Position>
    {
        new Position(44.05215, 27.03266),
        new Position(44.05056, 27.13236),
        new Position(44.04887, 27.23206)
    };
}

Then where you need to add the pins, you can use a For loop to keep the index while adding the pins:

for (int i = 0; i < HardcodedLocations.Positions.Count; i  )
{
    var pin = new Pin
    {
        Label = $"Santa Cruz - {i 1}",
        Address = "The city with a boardwalk",
        Type = PinType.Place,
        Position = HardcodedLocations.Positions[i]
     };

     map.Pins.Add(pin);
}

enter image description here

Note that I have no idea on what the performance of adding almost 2000 pins in a loop would look like.

  • Related