How to get current location or move to current location in Xamarin.Forms.Map

筅森魡賤 提交于 2019-11-28 23:28:27
Giorgi

You will need to call MoveToRegion method with the position you are interested in.

You can use Geolocator Plugin for Xamarin to get the location in PCL project:

var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync(10000);
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position. Longitude), 
                                             Distance.FromMiles(1))

Center the map on your location:

var position = await locator.GetPositionAsync(5000);
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude), Distance.FromMiles(1))

Zoom the map on its current position:

var zoomLevel = 9; // between 1 and 18
var latlongdegrees = 360 / (Math.Pow(2, zoomLevel));
map.MoveToRegion(new MapSpan (map.VisibleRegion.Center, latlongdegrees, latlongdegrees));

Ref: https://developer.xamarin.com/guides/xamarin-forms/working-with/maps/

Is this not a common usecase to zoom to users position?

Yes, it is. For iOS just use the MKMapView ShowUserLocation property.

From Apple documentary:

Setting this property to YES causes the map view to use the Core Location framework to find the current location and try to display it on the map.

Source: https://developer.apple.com/library/ios/documentation/MapKit/Reference/MKMapView_Class/#//apple_ref/occ/instp/MKMapView/showsUserLocation

So how can you do it in Xamarin? You will need a custom renderer which extends Xamarin Forms MapRenderer. Get the native map and set the ShowUserLocation property to true.

Here is an example:

private void MoveToCurrentPosition()
{
  var nativeMap = Control as MKMapView;
  if (nativeMap == null)
    return;

  nativeMap.ShowsUserLocation = true;
}

Also set nativeMap.SetUserTrackingMode(MKUserTrackingMode.Follow, true); to automatically follow the user.

This may not work when the map is initialised, since iOS couldn't get the user location yet. So if you need to display the current user location when the map appears, just use an EventHandler for MKUserLocationEventArgs and use the DidUpdateUserLocation event. You can do it like this:

private EventHandler<MKUserLocationEventArgs> _didUpdateUserLocationEventHandler;

// In OnElementChanged:
_didUpdateUserLocationEventHandler = (_, __) =>
{
    MoveToCurrentPosition();
    nativeMap.DidUpdateUserLocation -= _didUpdateUserLocationEventHandler;
};
nativeMap.DidUpdateUserLocation += _didUpdateUserLocationEventHandler;

Do not forget to deregister this event. Use it just for a usual initialise behaviour. The user should be free to scroll on the map as he likes.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!