BCA / B.Tech 17 min read

Location and Maps Services

Location and Maps Services

1: Displaying Maps

The Google Maps Platform is used to integrate maps into Android applications. The `Google Maps Android API` allows you to embed interactive maps within your app.

Key Steps to Integrate Maps:

  1. Get an API Key: Go to the Google Cloud Console, create a project, enable the "Maps SDK for Android," and generate an API key.
  2. Add Dependencies: Add the dependency for Google Play services for maps in your `build.gradle` file.
  3. Add the API Key: Add your API key to the `AndroidManifest.xml` file.
  4. Add Permissions: Add the necessary location permissions in `AndroidManifest.xml`.
  5. Add a MapFragment: Add a `SupportMapFragment` to your XML layout to display the map.
  6. Initialize the Map: Get the map object in your activity using the `getMapAsync()` method.
[Image of Google Maps integrated into an Android app]

Example in Java:

Step 1: API Key and Permissions in AndroidManifest.xml


<manifest ...>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application ...>
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="YOUR_API_KEY_HERE" />
        ...
    </application>
</manifest>

Step 2: MapFragment in XML Layout


<fragment
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Step 3: Controlling the Map in the Activity


public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    // This callback is triggered when the map is ready to be used.
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Create a LatLng object for Bhilwara, Rajasthan and add a marker.
        LatLng bhilwara = new LatLng(25.3485, 74.6373);
        mMap.addMarker(new MarkerOptions().position(bhilwara).title("Marker in Bhilwara"));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(bhilwara, 12)); // Zoom level 12
    }
}

2: Getting and Monitoring Location Data

Getting the user's current location is a critical feature for many apps. The `FusedLocationProviderClient` is used to get location data in Android.

Steps to Get Location:

  1. Check Permissions: Check for the `ACCESS_FINE_LOCATION` permission and request it from the user if necessary (runtime permission).
  2. Get an Instance of FusedLocationProviderClient: Create an object of this class to interact with location services.
  3. Get the Last Known Location: Quickly obtain the device's last cached location.

Example of Getting Last Known Location in Java:


public class LocationActivity extends AppCompatActivity {

    private FusedLocationProviderClient fusedLocationClient;
    private TextView locationTextView;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);

        locationTextView = findViewById(R.id.location_tv);
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

        checkLocationPermission();
    }

    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            // Permission is not granted, request it
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            // Permission has already been granted, get the location
            getLastLocation();
        }
    }

    private void getLastLocation() {
        // A permission check is mandatory here
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            fusedLocationClient.getLastLocation()
                .addOnSuccessListener(this, new OnSuccessListener() {
                    @Override
                    public void onSuccess(Location location) {
                        // Got last known location. In some rare situations this can be null.
                        if (location != null) {
                            String locationText = "Latitude: " + location.getLatitude() + 
                                                  "
Longitude: " + location.getLongitude();
                            locationTextView.setText(locationText);
                        } else {
                            locationTextView.setText("Location not available.");
                        }
                    }
                });
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission was granted
                getLastLocation();
            } else {
                Toast.makeText(this, "Location permission is required!", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

Monitoring Location: For continuous location updates, you can use the `requestLocationUpdates()` method, which delivers location data at a specific interval.