How to Display Current GPS Location in OSM Maps Using Xamarin.Essentials | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (215)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (915)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (147)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (628)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (592)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Display Current GPS Location in OSM Maps Using Xamarin.Essentials

How to Display Current GPS Location in OSM Maps Using Xamarin.Essentials

The Syncfusion Maps control for Xamarin has built-in support for external imagery services like OpenStreetMap (OSM) and Bing Maps to visualize satellite, aerial, street, and other map imagery tiles without using shape files. Apart from Bing Maps and OSM, you can also render maps from other map providers such as Google Maps and TomTom.

Before getting into the details of this blog, you need to understand the following two useful features in Xamarin.Essentials:

  • Geolocation: Acquires a device’s current geolocation coordinates (latitude and longitude).
  • Geocoding: Converts an address (user-readable) to positional coordinates and vice versa.

In this article, you will learn how to mark (pin) the current device’s GPS (Global Positioning System) location in the Maps control with OSM (you can use any map service provider, such as Bing, Google, and others) using the geolocation support, and how to display the detected location from the address using the geocoding support.

Note: To access the geolocation functionality in Xamarin.Essentials, please refer to this link to find platform-specific steps.

Let’s get started!

Show device’s current GPS location in OSM

Follow these steps to display a device’s current GPS location in OSM using the Syncfusion Xamarin Maps control:

Step 1: Initialize the Maps control

First, you need to create an instance of the Xamarin Maps control with an OSM imagery layer. OSM is a world map built by a community of mappers that is free to use under an open license.

The Maps control uses the imagery layer to display tile images from the OSM service. To use OSM, you need to add an imagery layer in the Maps’s Layers collection and set the LayerType as OSM as shown in the following code.

<maps:SfMaps>
            <maps:SfMaps.Layers>
                <maps:ImageryLayer x:Name="imageryLayer" LayerType="OSM" ></maps:ImageryLayer>
            </maps:SfMaps.Layers>
 </maps:SfMaps>

Note: Refer to this documentation link to get started with the Xamarin Maps control.

Step 2: Get current geolocation

The current location of a geographic coordinate point can be obtained from the geolocation APIs, which will ask the user for permission when necessary.

The GetLastKnownLocationAsync method is used to get the last known location of the device. It works faster than fetching an entire set of location data, but it lacks accuracy and may return null if there is no cached location.

Refer to the following code.

var location = await Geolocation.GetLastKnownLocationAsync();

If the last known location is null, then call the GetLocationAsync method to query the device’s current geographic coordinates. It is recommended to pass in a full GeolocationRequest with location accuracy to avoid a time delay in fetching the location.

Refer to the following code.

private async void GetCurrentGeolocation()
{
    try
    {
        var location = await Geolocation.GetLastKnownLocationAsync();
        if (location == null)
        {
            var request = new GeolocationRequest(GeolocationAccuracy.Medium, TimeSpan.FromSeconds(10));
            location = await Geolocation.GetLocationAsync(request);
            if (location != null)
            {
                geoLocation = location;
            }
        }
        else
        {
            geoLocation = location;
        }
    }
    catch (Exception ex)
    {
        // Unable to get location
    }        
}

Step 3: Set the marker pin in location

After fetching the current device GPS location, you need to add marker in the map at the acquired location. The ImageryLayer provides an option to place the marker inside the map using the Markers collection property.

To pin the current location, create the MapMarker object by assigning the fetched location point to the Latitude and Longitude properties. Then, add the object to the Markers collection in the ImageryLayer instance as shown in the following code.

if (location != null)
{
    MapMarker marker = new MapMarker();
    marker.Latitude = location.Latitude.ToString();
    marker.Longitude = location.Longitude.ToString();
    this.imageryLayer.Markers = new ObservableCollection<MapMarker> { marker };
}

You can customize the type of marker (pin) icon using the MarkerIcon property or add a customized marker by using the MarkerTemplate property.

To show the current location at the center of the map, set that point to the GeoCoordinates property as shown in the following code.

private void SetMarkerInLocation(Location location)
{
    if (location != null)
    {
        MapMarker marker = new MapMarker();
        marker.Latitude = location.Latitude.ToString();
        marker.Longitude = location.Longitude.ToString();
        this.imageryLayer.Markers = new ObservableCollection<MapMarker> { marker };

        this.imageryLayer.GeoCoordinates = new Point(location.Latitude, location.Longitude);
        this.imageryLayer.Radius = 50;
        this.imageryLayer.DistanceType = DistanceType.Mile;
    }
}

Refer to the following .gif image.
Show device’s current GPS location in OSM

Display the detected location from the address

Any address can be geocoded into latitude and longitude coordinates by using the geocoding APIs in Xamarin.Essentials. To do this, you need to pass the address (e.g., a Microsoft building address) to the geocoding GetLocationsAsync method as a string argument. Then, the method will asynchronously return a collection of geographic position objects that represent the address.

Refer to the following code.

private async void GetLocationFromAddress()
{
    try
    {
        var address = "Microsoft Building 25 Redmond WA USA";
        var locations = await Geocoding.GetLocationsAsync(address);

        var location = locations?.FirstOrDefault();
        if (location != null)
        {
            geoLocation = location;
        }
    }
    catch (FeatureNotSupportedException fnsEx)
    {
        // Feature not supported on device
    }
}

After getting the location, set the map marker (pin) for that location in the map as explained in the Set the marker pin in location section.

Refer to the following .gif image.
Display the detected location from the address

Resource

You can download the complete sample code of this blog from this GitHub location.

Conclusion

Thanks for reading! In this blog, we have learned how easy it is to display the current and detected GPS location in the Syncfusion Xamarin Maps control using Xamarin.Essentials. So, try out the instructions provided in this blog and tell us about your experience in the comments section below. The Syncfusion Maps control is also available for the Blazor, ASP.NET (Core, MVC, Web Forms), JavaScript, Angular, React, Vue, Flutter, UWP, WinForms, and WPF platforms.

Check out the complete user guide of our Maps control and see our map samples in this GitHub location. Additionally, you can check out our demo apps in Google PlayMicrosoft Store, and TestFlight.

If you have any questions about these controls, please let us know in the comments below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed