Forum Xamarin.Forms

Xamarin.Forms Google Maps and Permissions Plugin

XazinXazin Member ✭✭

Hello there folks, so what I'm trying to accomplish is to

  1. Show a map and some predefined pins (for now).

  2. The map shows with showinguser = false at start, then an async method keeps checking for permission, and if it changes then it creates a new map, removes the old one and inserts the new one where showinguser = true.

  3. Done.

I have had some success, but problem is first time I opened application I got an error and no map, when I had clicked yes to permission and the map that was hardcoded was isshowinguser = true, which means somehow I need runtime change the map settings.

I know it's a bit redundant to create a new map, I understand I could change the current maps settings...

My code is below

using System;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

using Xamarin.Forms.Maps;
using Plugin.Permissions;
using Plugin.Permissions.Abstractions;
using Plugin.Geolocator;

namespace App6.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ItemsPage : ContentPage
    {
        private Double currentLatitude = 0.0;
        private Double currentLongtitude = 0.0;

        private bool hasPermission = false;
        private Map map = new Map();

        public ItemsPage()
        {
            InitializeComponent();

            map = new Map(
                MapSpan.FromCenterAndRadius(
                new Position(55.584974, 11.569806), Distance.FromMiles(145)))
            {
                IsShowingUser = true,
                HeightRequest = 100,
                WidthRequest = 960,
                VerticalOptions = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                MapType = MapType.Street
            };

            var pin1 = new Pin
            {
                Type = PinType.Place,
                Position = new Position(55.057765, 15.131400),
                Label = "Opladningsstation",
                Address = "Sdr Hammer 158, 3730 Nexø"
            };

            var pin2 = new Pin
            {
                Type = PinType.Place,
                Position = new Position(55.102365, 14.699720),
                Label = "Opladningsstation",
                Address = "Sankt Mortensgade 1, 3700 Rønne"
            };

            var pin3 = new Pin
            {
                Type = PinType.Place,
                Position = new Position(55.672586, 12.564548),
                Label = "Opladningsstation",
                Address = "Vesterbro, 1577 København"
            };

            var pin4 = new Pin
            {
                Type = PinType.Place,
                Position = new Position(55.618859, 12.650752),
                Label = "Opladningsstation",
                Address = "Lufthavnsboulevarden 6, 2770 Kastrup"
            };

            map.Pins.Add(pin1);
            map.Pins.Add(pin2);
            map.Pins.Add(pin3);
            map.Pins.Add(pin4);

            mainLayout.Children.Add(map);

            CheckPermission();

        }

        private async void CheckPermission()
        {
            bool done = false;

            while (done.Equals(false))
            {
                try
                {
                    if (hasPermission.Equals(true))
                    {
                        DoPosition();
                        done = true;
                        break;
                    }
                    else
                    {
                        done = false;
                    }
                }
                catch (Exception ex)
                {
                    await DisplayAlert("Exception", ex.Message, "Ok");
                }
            }
        }

        private void DoPosition()
        {

            if (mainLayout.Children.Contains(map))
            {
                map = null;
                mainLayout.Children.Remove(map);
            }

            map = new Map(
                    MapSpan.FromCenterAndRadius(
                    new Position(currentLatitude, currentLongtitude), Distance.FromMiles(30)))
            {
                IsShowingUser = true,
                HeightRequest = 100,
                WidthRequest = 960,
                VerticalOptions = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand,
                MapType = MapType.Street
            };

            var pin1 = new Pin
            {
                Type = PinType.Place,
                Position = new Position(55.057765, 15.131400),
                Label = "Opladningsstation",
                Address = "Sdr Hammer 158, 3730 Nexø"
            };

            var pin2 = new Pin
            {
                Type = PinType.Place,
                Position = new Position(55.102365, 14.699720),
                Label = "Opladningsstation",
                Address = "Sankt Mortensgade 1, 3700 Rønne"
            };

            var pin3 = new Pin
            {
                Type = PinType.Place,
                Position = new Position(55.672586, 12.564548),
                Label = "Opladningsstation",
                Address = "Vesterbro, 1577 København"
            };

            var pin4 = new Pin
            {
                Type = PinType.Place,
                Position = new Position(55.618859, 12.650752),
                Label = "Opladningsstation",
                Address = "Lufthavnsboulevarden 6, 2770 Kastrup"
            };

            map.Pins.Add(pin1);
            map.Pins.Add(pin2);
            map.Pins.Add(pin3);
            map.Pins.Add(pin4);

            mainLayout.Children.Add(map);
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            GetPermission();
        }

        private async void GetPermission()
        {
            try
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
                if (status != PermissionStatus.Granted)
                {
                    if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
                    {
                        await DisplayAlert("Need Location", "Going to need location", "OK");
                    }

                    var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
                    //Best practice to always check that the key exists
                    if (results.ContainsKey(Permission.Location))
                        status = results[Permission.Location];
                }

                if (status == PermissionStatus.Granted)
                {
                    var results = await CrossGeolocator.Current.GetPositionAsync(new TimeSpan(100000));
                    currentLatitude = results.Latitude;
                    currentLongtitude = results.Longitude;
                    hasPermission = true;
                }
                else if (status != PermissionStatus.Unknown)
                {
                    await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            OnPermissionsChange();

        }

        private void OnPermissionsChange()
        {
            try
            {
                var map2 = new Map();

                if (hasPermission.Equals(false))
                {
                    map2 = new Map(
                    MapSpan.FromCenterAndRadius(
                            new Position(55.584974, 11.569806), Distance.FromMiles(145)))
                    {
                        IsShowingUser = false,
                        HeightRequest = 100,
                        WidthRequest = 960,
                        VerticalOptions = LayoutOptions.FillAndExpand,
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        MapType = MapType.Street
                    };
                }
                else
                {
                    map2 = new Map(
                    MapSpan.FromCenterAndRadius(
                            new Position(currentLatitude, currentLongtitude), Distance.FromMiles(20)))
                    {
                        IsShowingUser = true,
                        HeightRequest = 100,
                        WidthRequest = 960,
                        VerticalOptions = LayoutOptions.FillAndExpand,
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        MapType = MapType.Street
                    };
                }
                var pin1 = new Pin
                {
                    Type = PinType.Place,
                    Position = new Position(55.057765, 15.131400),
                    Label = "Opladningsstation",
                    Address = "Sdr Hammer 158, 3730 Nexø"
                };

                var pin2 = new Pin
                {
                    Type = PinType.Place,
                    Position = new Position(55.102365, 14.699720),
                    Label = "Opladningsstation",
                    Address = "Sankt Mortensgade 1, 3700 Rønne"
                };

                var pin3 = new Pin
                {
                    Type = PinType.Place,
                    Position = new Position(55.672586, 12.564548),
                    Label = "Opladningsstation",
                    Address = "Vesterbro, 1577 København"
                };

                var pin4 = new Pin
                {
                    Type = PinType.Place,
                    Position = new Position(55.618859, 12.650752),
                    Label = "Opladningsstation",
                    Address = "Lufthavnsboulevarden 6, 2770 Kastrup"
                };

                map2.Pins.Add(pin1);
                map2.Pins.Add(pin2);
                map2.Pins.Add(pin3);
                map2.Pins.Add(pin4);
                mainLayout.Children.Remove(map);
                map = map2;
                mainLayout.Children.Add(map);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                // EXH 
            } finally
            {
                // MM 
            }
        }
    }
}

Currently this shows a white page with no content in it.
Whilst removing the CheckPermission() method from executing the map will show with isshowinguser = false, even though the OnPermissionChange() should be successfully run when permission check is done. I'm not only quite new to C#, I'm also a complete Xamarin newbie ...

If anyone can help me along and help me point out redundant parts it would be great. I'm also looking forward to some guidance as I'm completely new here :3

Thanks a lot for your help and patience.

Answers

  • XazinXazin Member ✭✭

    Current new Code .. Still no solution, been trying lots of things :3

    using System;
    
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    
    using Xamarin.Forms.Maps;
    using Plugin.Permissions;
    using Plugin.Permissions.Abstractions;
    using Plugin.Geolocator;
    
    namespace App6.Views
    {
        [XamlCompilation(XamlCompilationOptions.Compile)]
        public partial class ItemsPage : ContentPage
        {
            private Double currentLatitude = 0.0;
            private Double currentLongtitude = 0.0;
    
            private bool hasPermission = false;
            private Map map = new Map();
    
            public ItemsPage()
            {
                InitializeComponent();
    
                map = new Map(
                    MapSpan.FromCenterAndRadius(
                    new Position(55.584974, 11.569806), Distance.FromMiles(145)))
                {
                    IsShowingUser = false,
                    HeightRequest = 100,
                    WidthRequest = 960,
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    MapType = MapType.Street
                };
    
                var pin1 = new Pin
                {
                    Type = PinType.Place,
                    Position = new Position(55.057765, 15.131400),
                    Label = "Opladningsstation",
                    Address = "Sdr Hammer 158, 3730 Nexø"
                };
    
                var pin2 = new Pin
                {
                    Type = PinType.Place,
                    Position = new Position(55.102365, 14.699720),
                    Label = "Opladningsstation",
                    Address = "Sankt Mortensgade 1, 3700 Rønne"
                };
    
                var pin3 = new Pin
                {
                    Type = PinType.Place,
                    Position = new Position(55.672586, 12.564548),
                    Label = "Opladningsstation",
                    Address = "Vesterbro, 1577 København"
                };
    
                var pin4 = new Pin
                {
                    Type = PinType.Place,
                    Position = new Position(55.618859, 12.650752),
                    Label = "Opladningsstation",
                    Address = "Lufthavnsboulevarden 6, 2770 Kastrup"
                };
    
                map.Pins.Add(pin1);
                map.Pins.Add(pin2);
                map.Pins.Add(pin3);
                map.Pins.Add(pin4);
    
                mainLayout.Children.Add(map);
    
                CheckPermission();
    
            }
    
            private async void CheckPermission()
            {
                bool done = false;
    
                while (done.Equals(false))
                {
                    try
                    {
                        if (hasPermission.Equals(true))
                        {
                            DoPosition();
                            done = true;
                            break;
                        }
                        else
                        {
                            done = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        await DisplayAlert("Exception", ex.Message, "Ok");
                    }
                }
            }
    
            private void DoPosition()
            {
    
                if (mainLayout.Children.Contains(map))
                {
                    mainLayout.Children.Remove(map);
    
                    map.IsShowingUser = true;
                    map.MoveToRegion(MapSpan.FromCenterAndRadius(
                        new Position(currentLatitude, currentLongtitude), Distance.FromMiles(30)));
    
                    mainLayout.Children.Add(map);
                }
    
            }
    
            protected override void OnAppearing()
            {
                base.OnAppearing();
    
                GetPermission();
            }
    
            private async void GetPermission()
            {
                try
                {
                    var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
                    if (status != PermissionStatus.Granted)
                    {
                        if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
                        {
                            await DisplayAlert("Need Location", "Going to need location", "OK");
                        }
    
                        var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);
                        //Best practice to always check that the key exists
                        if (results.ContainsKey(Permission.Location))
                            status = results[Permission.Location];
                    }
    
                    if (status == PermissionStatus.Granted)
                    {
                        var results = await CrossGeolocator.Current.GetPositionAsync(new TimeSpan(100000));
                        currentLatitude = results.Latitude;
                        currentLongtitude = results.Longitude;
                        hasPermission = true;
                    }
                    else if (status != PermissionStatus.Unknown)
                    {
                        await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
    
                // OnPermissionsChange();
    
            }
    
            private void OnPermissionsChange()
            {
                try
                {
                    var map2 = new Map();
    
                    if (hasPermission.Equals(false))
                    {
                        map2 = new Map(
                        MapSpan.FromCenterAndRadius(
                                new Position(55.584974, 11.569806), Distance.FromMiles(145)))
                        {
                            IsShowingUser = false,
                            HeightRequest = 100,
                            WidthRequest = 960,
                            VerticalOptions = LayoutOptions.FillAndExpand,
                            HorizontalOptions = LayoutOptions.FillAndExpand,
                            MapType = MapType.Street
                        };
                    }
                    else
                    {
                        map2 = new Map(
                        MapSpan.FromCenterAndRadius(
                                new Position(currentLatitude, currentLongtitude), Distance.FromMiles(20)))
                        {
                            IsShowingUser = true,
                            HeightRequest = 100,
                            WidthRequest = 960,
                            VerticalOptions = LayoutOptions.FillAndExpand,
                            HorizontalOptions = LayoutOptions.FillAndExpand,
                            MapType = MapType.Street
                        };
                    }
                    var pin1 = new Pin
                    {
                        Type = PinType.Place,
                        Position = new Position(55.057765, 15.131400),
                        Label = "Opladningsstation",
                        Address = "Sdr Hammer 158, 3730 Nexø"
                    };
    
                    var pin2 = new Pin
                    {
                        Type = PinType.Place,
                        Position = new Position(55.102365, 14.699720),
                        Label = "Opladningsstation",
                        Address = "Sankt Mortensgade 1, 3700 Rønne"
                    };
    
                    var pin3 = new Pin
                    {
                        Type = PinType.Place,
                        Position = new Position(55.672586, 12.564548),
                        Label = "Opladningsstation",
                        Address = "Vesterbro, 1577 København"
                    };
    
                    var pin4 = new Pin
                    {
                        Type = PinType.Place,
                        Position = new Position(55.618859, 12.650752),
                        Label = "Opladningsstation",
                        Address = "Lufthavnsboulevarden 6, 2770 Kastrup"
                    };
    
                    map2.Pins.Add(pin1);
                    map2.Pins.Add(pin2);
                    map2.Pins.Add(pin3);
                    map2.Pins.Add(pin4);
                    mainLayout.Children.Remove(map);
                    map = map2;
                    mainLayout.Children.Add(map);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    // EXH 
                } finally
                {
                    // MM 
                }
            }
        }
    }
    
  • LandLuLandLu Member, Xamarin Team Xamurai

    Your project will be stuck in the While loop:

    while (done.Equals(false))
    {
        try
        {
            if (hasPermission.Equals(true))
            {
                DoPosition();
                done = true;
                break;
            }
            else
            {
                done = false;
            }
        }
        catch (Exception ex)
        {
            await DisplayAlert("Exception", ex.Message, "Ok");
        }
    }
    

    As you placed this code in constructor and it will be fired before GetPermission which aligns in the OnAppearing event. hasPermission will not be changed to true.
    You should check the user's permissions first if he denies it, let him go to Settings to change that behavior instead of blocking your app's process.

Sign In or Register to comment.