Search code examples
c#xamarinxamarin.formsmapspins

When I load data from my database I want to create multiple pins on my map, now I only get 1 pin


I am working with a map in xamarin forms and came across a problem that I cannot seem to solve. I want to add multiple pins (to multiple locations) and in my database in parse I have data for 3 different places but when I test it on the app only 1 pin appear on the map.

This is my code:

var getItems = await parseAPI.getInfo (Application.Current.Properties ["sessionToken"].ToString ()); //I load my data.

foreach (var currentItem in getItems["results"]) {
    mLong = currentItem ["long"].ToString (); //my long from my data
    mLat = currentItem ["lat"].ToString (); //my lat from my data

}

var storeLong = Double.Parse (mLong, CultureInfo.InvariantCulture); //converting the long from string to int.
var storeLat = Double.Parse (mLat, CultureInfo.InvariantCulture); //converting the lat from string to int.

if (mLong != null) {

    var pin = new Pin ();
    pin.Position = new Position (storeLat,storeLng); //here i add the data i have.
    pin.Label = "test";
    pin.Address = "test";

    theMap.Pins.Add (pin); //adding my pins to my map. 
}

Maybe I need to create a list <String> somehow?


Solution

  • You are not creating a pin for each of the getItems, only the last one, try extending for foreach to wrap the entire code snippet:

    var getItems = await parseAPI.getInfo (Application.Current.Properties ["sessionToken"].ToString ()); //I load my data.
    
    foreach (var currentItem in getItems["results"]) 
    {
        mLong = currentItem ["long"].ToString (); //my long from my data
        mLat = currentItem ["lat"].ToString (); //my lat from my data
    
        var storeLong = Double.Parse (mLong, CultureInfo.InvariantCulture); //converting the long from string to int.
        var storeLat = Double.Parse (mLat, CultureInfo.InvariantCulture); //converting the lat from string to int.
    
        if (mLong != null) 
        {
            var ourPosition = new Position (13, -15);
            theMap.MapType = MapType.Hybrid;
            theMap.MoveToRegion (
                MapSpan.FromCenterAndRadius (
                    ourPosition, Distance.FromMeters (300)));
    
            var pin = new Pin ();
            pin.Position = new Position (storeLat,storeLng); //here i add the data i have.
            pin.Label = "test";
            pin.Address = "test";
            pin.Clicked += onButtonClicked1;
    
            theMap.Pins.Add (pin); //adding my pins to my map. 
        }
    }