Download Code

Xamarin GPS Location Map Android

In xamarin gps location map android tutorial you will learn how to map a marker on a current location of any user using location services(GPS).Before starting Xamarin GPS Location Map Android tutorial you must have some knowledge of how to use map in android application.How to use location services GPS in android.You can read basic from this Google_Map_V2 tutorial.

When you go through the Google_Map_V2 tutorial.You will know how to create Android Map API key.How to import Google_Play_Services_Lib.How to load map in fragment.

Create new xamarin gps location map android application project.Go to Main.axml and add fragment.

xamarin gps, xamarin gps location, xamarin gps location map, xamarin gps location map android, how to get current location and set on map android xamarin, xamarin get current location and display on google map android,

Create a new class GPSHelper.cs.It’s a Service class used to get location using NETWORK or GPS.

GPSHelper.cs

namespace MyMap
{
	[Activity(Label = "GPSHelper")]
	public class GPSHelper : Service, ILocationListener
	{
		private Context con;     // pointer this class means context(this)
		bool GPS_Status = false;     // GPS status variable activated or not
		bool Network_Status = false; // Network service status checker
		bool able_To_Get_Location = false;   // status to check whether whether GPS or Network gives the location
		Location location;

		long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // The minimum distance to change Updates in meters
		long MIN_TIME_BW_UPDATES = 0; // The minimum time between updates in milliseconds
		protected LocationManager locationManager; // Location Manager variable
		double latitude; // latitude
		double longitude; // longitude
						  // constructor for GPS class to set the context and get user location
		public GPSHelper(Context con)
		{
			this.con = con;
			getUserLocation();
		}



		public void OnLocationChanged(Location location)
		{
			this.location = location;
			getLatitude();
			getLongitude();
		}

		public Location getUserLocation()
		{
			try
			{
				locationManager = (LocationManager)con.GetSystemService(LocationService);

				// getting GPS status
				GPS_Status = locationManager.IsProviderEnabled(LocationManager.GpsProvider);

				// getting network status
				Network_Status = locationManager
					.IsProviderEnabled(LocationManager.NetworkProvider);

				if (!GPS_Status && !Network_Status)
				{
					// no network provider is enabled
				}
				else {
					this.able_To_Get_Location = true;
					// First get location from Network Provider
					if (Network_Status)
					{
						locationManager.RequestLocationUpdates(
							LocationManager.NetworkProvider,
								MIN_TIME_BW_UPDATES,
								MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

						if (locationManager != null)
						{
							location = locationManager
								.GetLastKnownLocation(LocationManager.NetworkProvider);
							if (location != null)
							{
								latitude = location.Latitude;
								longitude = location.Longitude;
							}
						}
					}
					// if GPS Enabled get lat/long using GPS Services
					if (GPS_Status)
					{
						if (location == null)
						{
							locationManager.RequestLocationUpdates(
								LocationManager.GpsProvider,
									MIN_TIME_BW_UPDATES,
									MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

							if (locationManager != null)
							{
								location = locationManager
									.GetLastKnownLocation(LocationManager.GpsProvider);
								if (location != null)
								{
									latitude = location.Latitude;
									longitude = location.Longitude;
								}
							}
						}
					}
				}

			}
			catch (Exception e)
			{
				e.StackTrace.ToString();
			}

			return location;
		}




		/**
	 * Function to get latitude
	 * */
		public double getLatitude()
		{
			if (location != null)
			{
				latitude = location.Latitude;
			}

			// return latitude
			return latitude;
		}

		/**
		 * Function to get longitude
		 * */
		public double getLongitude()
		{
			if (location != null)
			{
				longitude = location.Longitude;
			}

			// return longitude
			return longitude;
		}


		// check wifi and GPS status working or not
		public bool able_To_Get_Lo()
		{
			return this.able_To_Get_Location;
		}
		// alert to enable your GPS or Network setting
		// alert to enable your GPS or Network setting
		public void showSettingsAlert()
		{
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(con);

			// Setting Dialog Title
			alertDialog.SetTitle("GPS is settings");

			// Setting Dialog Message
			alertDialog.SetMessage("GPS is not enabled. Do you want to go to settings menu?");

			alertDialog.SetPositiveButton("Settings", (senderAlert, args) =>
			{
				Intent intent = new Intent(Settings.ActionLocationSourceSettings);
				con.StartActivity(intent);
			});

			alertDialog.SetNegativeButton("Cancel", (senderAlert, args) =>
			{
				alertDialog.SetCancelable(true);
			});


			// Showing Alert Message
			alertDialog.Show();

		}

		public void OnProviderDisabled(string provider)
		{
			throw new NotImplementedException();
		}

		public void OnProviderEnabled(string provider)
		{
			throw new NotImplementedException();
		}

		public void OnStatusChanged(string provider, [GeneratedEnum] Availability status, Bundle extras)
		{
			throw new NotImplementedException();
		}
		public override IBinder OnBind(Intent intent)
		{
			throw new NotImplementedException();
		}
	}
}

Go to MainActivity.cs class.

  • Refer fragment from xml and use MapFragment with GoogleMap class to load map.
  • Create variable for GPSHelper.cs class to get current location.
  • Add Marker on Google Map.
  • Animate Camera to that Marker.

MainActivity.cs

namespace MyMap
{
	[Activity(Label = "MyMap", MainLauncher = true, Icon = "@mipmap/icon")]
	public class MainActivity : Activity, IOnMapReadyCallback
	{
		private GoogleMap google;
		// latitude and longitude
		double codecLatitude;
		double codecLongitude;
		MapFragment mapFrag;
		GPSHelper myGPS;

		protected override void OnCreate(Bundle savedInstanceState)
		{
			base.OnCreate(savedInstanceState);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Main);
			myGPS = new GPSHelper(this);
			if (myGPS.able_To_Get_Lo())
			{
				codecLatitude = myGPS.getLatitude();
				codecLongitude = myGPS.getLongitude();
				Toast.MakeText(this, "Location Successfully set", ToastLength.Short).Show();
				initializeMap(codecLatitude,codecLongitude);
			}
			else {
				myGPS.showSettingsAlert();
			}



		}


		/**
 		* 	function to load map.
 		* */

		public void initializeMap(double latitude,double longitude)
		{
			
			
			LatLng location = new LatLng(latitude, longitude);  // setting latitude and longitude
																// getting MapFragment
			mapFrag = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.map);
			// setting MapFragment to googleMap variable
			google = mapFrag.Map;


			if (google != null)
			{
				google.MapType = GoogleMap.MapTypeNormal;  // setting map type

				// creating marker

				MarkerOptions marker = new MarkerOptions()
					.SetPosition(new LatLng(latitude, longitude))
					.SetTitle("Android Codec");
				//positioning camera according to marker
				CameraPosition.Builder builder = CameraPosition.InvokeBuilder();
				builder.Target(location);
				builder.Zoom(15);
				builder.Bearing(155);

				CameraPosition cameraPosition = builder.Build();
				CameraUpdate cameraUpdate = CameraUpdateFactory.NewCameraPosition(cameraPosition);
				google.MoveCamera(cameraUpdate);  // move camera to marker
				google.AddMarker(marker);    // add marker to google Map
			}
		}
		public void OnMapReady(GoogleMap googleMap)
		{
			google = googleMap;
		}

	}
}

At last go to Android Manifest.xml File and add some permissions with Google Map API KEY.

xamarin gps, xamarin gps location, xamarin gps location map, xamarin gps location map android, how to get current location and set on map android xamarin, xamarin get current location and display on google map android,

Note: Don’t forget to import “google_play_services_lib” in your project.

Run your xamarin gps location map android application project.

xamarin gps, xamarin gps location, xamarin gps location map, xamarin gps location map android, how to get current location and set on map android xamarin, xamarin get current location and display on google map android,

That’s it for this tutorial.

Thanks.