Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (151).NET Core  (25)Angular  (49)ASP.NET  (48)ASP.NET Core  (64)ASP.NET MVC  (86)Azure  (28)Blazor  (97)DocIO  (20)Essential JS 2  (71)Essential Studio  (163)File Formats  (20)Flutter  (112)JavaScript  (148)Microsoft  (101)PDF  (59)React  (33)Succinctly series  (122)Syncfusion  (480)TypeScript  (30)Uno Platform  (3)UWP  (4)Vue  (26)Webinar  (25)Windows Forms  (55)WinUI  (21)WPF  (122)Xamarin  (130)XlsIO  (24)Other CategoriesBarcode  (4)BI  (29)Bold BI  (3)Build conference  (6)Business intelligence  (53)Button  (4)C#  (107)Chart  (51)Cloud  (9)Company  (445)Dashboard  (6)Data Science  (3)Data Validation  (5)DataGrid  (47)Development  (257)Doc  (7)DockingManager  (1)eBook  (93)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (20)Extensions  (13)File Manager  (4)Gantt  (9)Gauge  (7)Git  (4)Grid  (27)HTML  (9)Installer  (2)Knockout  (2)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (228)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (24)Performance  (6)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (6)Road Map  (9)Scheduler  (26)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (19)Solution Services  (2)Spreadsheet  (9)SQL  (7)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (60)UI  (131)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (1)Visual Studio  (19)Visual Studio Code  (11)Web  (215)What's new  (141)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
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:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top