GPS Location Tracker using Xamarin

Mobile devices are smart enough to provide the geo-location coordinates by consuming the GPS API embedded inside.
Let’s get the geo-coordinates and a street address which is close to the location using Xamarin. In the below example I have demonstrated the same in Android environment.

Following are few steps

Step #1
After creating a new Xamarin Android app add some common permission in AssemblyInfo.cs

[assembly: UsesPermission(Manifest.Permission.Internet)]
[assembly: UsesPermission(Manifest.Permission.AccessFineLocation)]
[assembly: UsesPermission(Manifest.Permission.AccessCoarseLocation)]

Step #2
Add a relativelayout in the design screen and add four textviews

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/location_text"
        android:width="200dp"
        android:layout_marginRight="0dp"
        android:layout_gravity="right"
        android:gravity="left"
        android:layout_alignParentRight="true" />
    <TextView
        android:text="Location :"
        android:layout_width="60.2dp"
        android:layout_height="wrap_content"
        android:id="@+id/textView1"
        android:layout_toLeftOf="@id/location_text"
        android:layout_alignTop="@id/location_text"
        android:width="100dp"
        android:layout_marginTop="0dp"
        android:layout_alignParentLeft="true" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/location_text"
        android:id="@+id/address_text"
        android:width="200dp"
        android:layout_alignParentRight="true" />
     <TextView
        android:text="Address :"
        android:layout_width="60.2dp"
        android:layout_height="wrap_content"
        android:id="@+id/textView2"
        android:layout_toLeftOf="@id/address_text"
        android:layout_below="@id/location_text"
        android:width="100dp"
        android:layout_marginTop="0dp"
        android:layout_alignParentLeft="true" />
</RelativeLayout>

Step #3
Implement the ILocationListener in Activity1.cs to include the required methods. Below is the code of Activity1.cs

    public class Activity1 : Activity, ILocationListener
    {
        
        Location currentLocation;
	LocationManager locationManager;

        TextView locationText;
	TextView addressText;
        string locationProvider;

	/// <param name="location">The new location, as a Location object.</param>
	/// <summary>
	/// Called when the location has changed.
	/// </summary>
        public void OnLocationChanged(Location location)
        {
			try
			{
				currentLocation = location;

				if (currentLocation == null)
					locationText.Text = "Unable to determine your location.";
				else
				{
					locationText.Text = String.Format("{0},{1}", currentLocation.Latitude, currentLocation.Longitude);

					Geocoder geocoder = new Geocoder(this);

					//The Geocoder class retrieves a list of address from Google over the internet
					IList<Address> addressList =  geocoder.GetFromLocation(currentLocation.Latitude, currentLocation.Longitude, 10);

					Address address = addressList.FirstOrDefault();

					if (address != null)
					{
						StringBuilder deviceAddress = new StringBuilder();

						for (int i = 0; i < address.MaxAddressLineIndex; i++)
							deviceAddress.Append(address.GetAddressLine(i))
								.AppendLine(",");

						addressText.Text = deviceAddress.ToString();
					}
					else
						addressText.Text = "Unable to determine the address.";
				}
			}
			catch
			{
				addressText.Text = "Unable to determine the address.";
			}
        }

	/// <summary>
	/// Raises the create event.
	/// </summary>
	/// <param name="bundle">Bundle.</param>
        protected override void OnCreate(Bundle bundle)
        {
			base.OnCreate(bundle);
			SetContentView(Resource.Layout.Main);

			addressText = FindViewById<TextView>(Resource.Id.address_text);

			locationText = FindViewById<TextView>(Resource.Id.location_text);

			//Initialising the LocationManager to provide access to the system location services.
			//The LocationManager class will listen for GPS updates from the device and notify the application by way of events. 
			locationManager = (LocationManager)GetSystemService(LocationService);

			//Define a Criteria for the best location provider
			Criteria criteriaForLocationService = new Criteria{
				//A constant indicating an approximate accuracy
				Accuracy = Accuracy.Coarse,
				PowerRequirement = Power.Medium
			};

			IList<string> acceptableLocationProviders = locationManager.GetProviders(criteriaForLocationService, true);

			if (acceptableLocationProviders.Any())
				locationProvider = acceptableLocationProviders.First();
			else
				locationProvider = String.Empty;
        }

	/// <summary>
	/// Override OnResume so that Activity1 will begin listening to the LocationManager 
	/// when the activity comes into the foreground:
	/// </summary>
        protected override void OnResume()
        {
            base.OnResume();
            locationManager.RequestLocationUpdates(locationProvider, 0, 0, this);
        }

	/// <summary>
	/// Override OnPause and unsubscribe Activity1 from the LocationManager when the activity goes into the background:
	/// </summary>
        protected override void OnPause()
        {
            base.OnPause();
            locationManager.RemoveUpdates(this);
        }
    }

Make sure while running the app into device be the GPS and WiFi(Internert) is on. Now let’s run the app and we can find the longitude and latitude of our location and the address as we move with the device. During movement we can find the address and the location are changing.

Written By: Anup Samantaray, Software Developer, Mindfire Solutions

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s