简体   繁体   中英

Xamarin iOS - Getting User's current latitude and longitude (Simple Example)

In the Xamarin Forms files, I have an interface with a method: GetCurrentLocation, and two properties (both strings): latitude and longitude.

In the Xamarin iOS files, I have a class interfacing from previously mentioned interface. The method (now expounded upon) states that, upon activation, it creates a MKMapView, get's the User's lat. and long., and sets them to equal to the lat. and long. properties of the class (As shown below).

    public string latitude { get; set; }
    public string longitude { get; set; }
    public void GetCurrentLocation () {
        var vm = new MKMapView();
        latitude = mv.UserLocation.Coordinate.Latitude.ToString();
        longitude = mv.UserLocation.Coordinate.Longitude.ToString();
    }

For this example, this method will only be called upon once, and the purpose is simply to get the lat. and long. of the device and display it in text.

(After some dependency-service shenanigans...) Back inside the Xamarin Forms files, I have a page in which I call the method to get the location, then use the newly acquired coordinates to display the device's current location in text. (I did set a custom location in the simulator, btw.)

Now, my prob is that when I actually run the program, the displayed string says that the lat. and long. are both 0. ("Latitude = 0, Longitude = 0") WHYYYYYYYYYYY?!?!? 😩 ultimate sad face


UPDATE: This is my code AFTER adding in the NuGet Package ---

First - IMapView (interface) - includes the following:

    public interface IMapView {
            double latitude { get; set; }
            double longitude { get; set; }
            void GetLatandLong ();
            IGeolocator locator { get; set; }
            Position position { get; set; }
    };

Second - MapView_iOS (native class) - includes the following:

    //Obvious instantiations of the Interfaced Properties...

    public async void GetLatandLong () {

            locator = CrossGeolocator.Current;
            locator.DesiredAccuracy = 100;

            position = await locator.GetPositionAsync (timeoutMilliseconds: 10000);

            latitude = Convert.ToDouble (position.Latitude);
            longitude = Convert.ToDouble (position.Longitude);
    }

Third - App.cs (x.forms class) - includes the following:

    //Among other basic startup stuff...

    protected override void OnStart()
    {
        DependencyService.Get<IMapView> ().GetLatandLong();
    }

Fourth and Finally - ContentPage (x.forms class) - contains:

    //Outside of the constructor:
    protected override void OnAppearing () {
        DisplayAlert ("It Works!", DependencyService.Get<IMapView> ().latitude + " + " + DependencyService.Get<IMapView> ().longitude, "Okay");
    }

    //Inside of the constructor:
    var LabelGest = new TapGestureRecognizer();
    LabelGest.Tapped += (s, e) => {
            DisplayAlert ("It Works!", DependencyService.Get<IMapView> ().latitude + " + " + DependencyService.Get<IMapView> ().longitude, "Okay");
    };

    var MyLabel = new Label {
            Text = "My Label",
            GestureRecognizers = {LabelGest}
    };

So you can see that I've got the DisplayAlert that displays my coordinates set up in two different places: Once when I open up the page and once when I tap a certain item on that page. When I tap on the item, the DisplayAlert activates properly giving the correct coordinates. The first DisplayAlert, however, (the one that activates when the page appears,) goes off incorrectly. It pops up at the right time, but it always gives the message of "0 + 0". :( This is the simplest example of my problem. I also have a Map on a separate page that goes like this:

    Content = new Map (MapSpan.FromCenterAndRadius (new Xamarin.Forms.Maps.Position
                    (DependencyService.Get<IMapView> ().latitude, DependencyService.Get<IMapView> ().longitude),
                        Distance.FromMiles (0.3))) {
            IsShowingUser = true,
            HeightRequest = 100,
            WidthRequest = 960,
            VerticalOptions = LayoutOptions.FillAndExpand
    }

This renders similar results, with the opening position being "0, 0" on the map. Any help is appreciated!

You can use https://github.com/jamesmontemagno/Xamarin.Plugins/tree/master/Geolocator

This is a plugin for Xamarin Forms

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