Luckily, there is a NuGet package named SimpleLocation8, which fulfills our needs: Under the hood it uses Google Play Services to exhaust Android’s possibilities. At the same time, it keeps the interface for us very simple and lean. Let’s look into an example with SimpleLocation.
The shared project
Our shared App gets a field locationManager
readonly SimpleLocationManager locationManager = new SimpleLocationManager();
Within the App constructor we simply create an empty, centered label
var label = new Label {
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand,
};
and place it on the MainPage
MainPage = new ContentPage { Content = label };
Furthermore, we make the label display the current location as soon as the location is updated:
locationManager.LocationUpdated +=
() => label.Text = string.Format("Latitude: {0}\nLongitude: {1}",
locationManager.LastLocation.Latitude, locationManager.LastLocation.Longitude);
The LastLocation is formatted into a string and assigned to the label.Text.
Finally, we start the location updates within the OnStart method of the App class. (Starting the location manager from the constructor might not work on iOS.)
locationManager.StartLocationUpdates(LocationAccuracy.Balanced, 1);
The two parameters are the required accuracy (Balanced in this example) and the smallest displacement (here 1 meter). You can further specify two intervals, which are only effective on Android.
The Android projectWithin Android’s MainActivity you need to pass a Context to the SimpleLocationManager. Simply place the following line above Forms.Init in the OnCreate method:
SimpleLocationManager.SetContext(this);
That’s it. SimpleLocation will take care of the rest.
The iOS projectAgain, we also need to add the following two items to the “Info.plist” file:
...
<key>NSLocationAlwaysUsageDescription</key>
<string>Can we use your location</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>We are using your location</string>
</dict>
</plist>That’s all you need to do on iOS. There is no platform-specific code required.