简体   繁体   中英

Xamarin Google Map

I am doing a looping in Xamarin, which add pin into the google map. Was wondering why it does not render to the Map immediately?

I want to show the pin to be added into the Map one at a time, so I added Sleep for 1 second to delay the plotting.

I think the reason is because its running on code behind for the plotting, hence the method of using the code below will be invalid.

for(int i = 0;i < templist.Count ; i++)
        {
            if (i != 0)
            {
                if (MyMap.Pins.Count > 9) { 
                    MyMap.Pins.RemoveAt(0);
                }
            }

            var Item = templist.ElementAt(i);
            string resultDatetimer = Item.DateTimer;
            string resultLocation = Item.Location;
            string resultLatitude = Item.Latitude;
            string resultLongitude = Item.Longitude;


            var position = new Position(Convert.ToDouble(resultLatitude), Convert.ToDouble(resultLongitude));

            var pin1 = new Pin
            {
                Type = PinType.Place,
                Position = position,
                Label = "Date:" + resultDatetimer + ", Location:" + resultLocation
            };

            MyMap.Pins.Add(pin1);

            MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(Convert.ToDouble(resultLatitude), Convert.ToDouble(resultLongitude))
                 , Distance.FromMeters(500)));
System.Threading.Thread.Sleep(1000);
        }

1) Do not use System.Threading.Thread.Sleep as that is a blocking call and if you are on the UI thread, your UI/keyboard/touch inputs, etc.. all just froze for that time period, use an awaited Task.Delay instead so the message pump for that thread can continue.

await Task.Delay(1000);

2) If your code is running on a background thread, make sure that you perform your pin add and movetoregion on the ui thread.

Device.BeginInvokeOnMainThread(() =>
{
    MyMap.Pins.Add(pin1);
    MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(Convert.ToDouble(resultLatitude), Convert.ToDouble(resultLongitude))
     , Distance.FromMeters(500)));
}); 

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