Courses / Mobile Application Development (CDE-315) – BS CS 5th Semester
Week 14 Lab 14 – Display a Location on Google Maps Using Coordinates
Week 14 – Threading and Publishing Android Applications · 150 min read · 9 MCQs to check yourself
Embed Google Maps and add markers using the Maps SDK (Java project – for Part B)
Objective
Enter a latitude, longitude and label, validate them, and show that place on Google Maps using a geo: intent (Part A, required – no API key). As an extension, embed a map with a marker inside the app using the Maps SDK (Part B), or the free osmdroid map.
CLOs: CLO-2 (develop location-based apps), CLO-3 (compare an intent vs an embedded SDK map – key, billing, size), CLO-4 (use Google Maps / OpenStreetMap tools).
What you will build in CampusMate
CampusMapActivity:
| Part | Feature |
|---|---|
| Inputs | Latitude, Longitude, Label (e.g. "Main Library") |
| Quick buttons | Campus (your campus), Faisal Mosque (33.7295, 73.0372) |
| Show on map | Opens the Google Maps app with a pin (browser fallback) |
| Navigate | Starts driving directions |
| Part B | Embedded map with a marker and map-type button |
Workflow
| Step | What you do | File |
|---|---|---|
| 1 | Create the activity | New → Activity |
| 2 | Layout with three inputs and buttons | activity_campus_map.xml |
| 3 | Read and validate coordinates | readCoordinates() |
| 4 | Show on Google Maps (geo: intent + fallback) | showOnMap() |
| 5 | Navigate and quick buttons | navigate() |
| 6 | Part B: embedded Google Map (extension) | MapsActivity.java |
| 7 | Free option: osmdroid | OsmActivity.java |
| 8 | Run and test | Emulator with Google Play |
Why two parts? Opening the Maps app needs no key and no payment, so everyone finishes Part A. The Maps SDK needs a Google Cloud project with billing enabled – do Part B if you can, or use osmdroid.
Step 1 – Create the activity
New → Activity → Empty Views Activity → CampusMapActivity (Java). Use an emulator image with Google Play (it has the Maps app).
Step 2 – Layout (activity_campus_map.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical"
android:padding="24dp">
<EditText
android:id="@+id/etLat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Latitude (-90 to 90)"
android:inputType="numberDecimal|numberSigned" />
<EditText
android:id="@+id/etLng"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Longitude (-180 to 180)"
android:inputType="numberDecimal|numberSigned" />
<EditText
android:id="@+id/etLabel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Label, e.g. Main Library" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button android:id="@+id/btnCampus"
android:layout_width="0dp" android:layout_weight="1"
android:layout_height="wrap_content" android:text="Campus" />
<Button android:id="@+id/btnMosque"
android:layout_width="0dp" android:layout_weight="1"
android:layout_height="wrap_content" android:text="Faisal Mosque" />
</LinearLayout>
<Button android:id="@+id/btnShow"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Show on map" />
<Button android:id="@+id/btnNavigate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Navigate" />
</LinearLayout>
numberDecimal|numberSigned allows a decimal point and a minus sign (e.g. -33.86).
Step 3 – Read and validate the coordinates
package com.example.campusmate;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class CampusMapActivity extends AppCompatActivity {
private EditText etLat, etLng, etLabel;
private double lat, lng; // filled by readCoordinates()
private String label;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_campus_map);
etLat = findViewById(R.id.etLat);
etLng = findViewById(R.id.etLng);
etLabel = findViewById(R.id.etLabel);
findViewById(R.id.btnCampus).setOnClickListener(v -> fill(33.6844, 73.0479, "Our Campus"));
findViewById(R.id.btnMosque).setOnClickListener(v -> fill(33.7295, 73.0372, "Faisal Mosque"));
findViewById(R.id.btnShow).setOnClickListener(v -> { if (readCoordinates()) showOnMap(); });
findViewById(R.id.btnNavigate).setOnClickListener(v -> { if (readCoordinates()) navigate(); });
}
private void fill(double la, double ln, String name) {
etLat.setText(String.valueOf(la));
etLng.setText(String.valueOf(ln));
etLabel.setText(name);
}
// Returns null instead of crashing when the text is not a number
private Double parseCoordinate(String text) {
try {
return Double.parseDouble(text.trim());
} catch (NumberFormatException e) {
return null;
}
}
private boolean readCoordinates() {
Double la = parseCoordinate(etLat.getText().toString());
Double ln = parseCoordinate(etLng.getText().toString());
if (la == null || la < -90 || la > 90) {
etLat.setError("Latitude must be between -90 and 90");
return false;
}
if (ln == null || ln < -180 || ln > 180) {
etLng.setError("Longitude must be between -180 and 180");
return false;
}
lat = la;
lng = ln;
label = etLabel.getText().toString().trim();
if (label.isEmpty()) label = "Location";
return true;
}
// Steps 4 and 5 below
}
| Value | Valid range |
|---|---|
| Latitude | −90 to 90 (south/north) |
| Longitude | −180 to 180 (west/east) – so 190.5 is invalid |
Step 4 – Show on Google Maps (with a browser fallback)
private void showOnMap() {
// geo:lat,lng?q=lat,lng(Label) puts a pin with a label; z=16 is the zoom level
Uri uri = Uri.parse("geo:" + lat + "," + lng + "?z=16&q=" + lat + "," + lng
+ "(" + Uri.encode(label) + ")");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setPackage("com.google.android.apps.maps"); // the Google Maps app specifically
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Maps app not installed → open the map in a browser instead
Uri web = Uri.parse("https://www.google.com/maps/search/?api=1&query=" + lat + "," + lng);
startActivity(new Intent(Intent.ACTION_VIEW, web));
}
}
| Part of the URI | Meaning |
|---|---|
geo:33.7295,73.0372 |
Centre of the map |
?z=16 |
Zoom level (1 = world … 21 = buildings) |
q=33.7295,73.0372(Faisal Mosque) |
Put a pin with this label |
Step 5 – Navigate
private void navigate() {
Uri uri = Uri.parse("google.navigation:q=" + lat + "," + lng + "&mode=d"); // d = driving, w = walking
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setPackage("com.google.android.apps.maps");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(this, "Google Maps is not installed", Toast.LENGTH_SHORT).show();
}
}
Step 6 – Part B (extension): embed a Google Map with a marker
- New → Activity → Gallery → Google Maps Views Activity →
MapsActivity, language Java (addsplay-services-mapsand aSupportMapFragment). - API key: console.cloud.google.com → new project → enable Maps SDK for Android → Credentials → Create API key → restrict it to Android apps with your package name and SHA-1 fingerprint (Gradle panel → signingReport). Billing must be enabled.
- Put the key in
local.propertiesasMAPS_API_KEY=...and read it through the Secrets Gradle Plugin –local.propertiesis not committed to GitHub. - MapsActivity.java:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap map;
private int typeIndex = 0;
private final int[] TYPES = {GoogleMap.MAP_TYPE_NORMAL, GoogleMap.MAP_TYPE_SATELLITE,
GoogleMap.MAP_TYPE_HYBRID, GoogleMap.MAP_TYPE_TERRAIN};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment =
(SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this); // onMapReady() is called when the map is loaded
}
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
map = googleMap;
double lat = getIntent().getDoubleExtra("lat", 33.7295);
double lng = getIntent().getDoubleExtra("lng", 73.0372);
String label = getIntent().getStringExtra("label");
LatLng pos = new LatLng(lat, lng);
map.addMarker(new MarkerOptions().position(pos).title(label).snippet(lat + ", " + lng));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(pos, 15f)); // centre at zoom 15
map.getUiSettings().setZoomControlsEnabled(true);
map.setOnMapClickListener(p -> map.addMarker(new MarkerOptions().position(p).title("Dropped pin")));
}
// Call from a "Map type" button
private void nextMapType() {
typeIndex = (typeIndex + 1) % TYPES.length;
map.setMapType(TYPES[typeIndex]);
}
}
- Open it from CampusMapActivity with an explicit intent (Lab 4):
Intent i = new Intent(this, MapsActivity.class);
i.putExtra("lat", lat);
i.putExtra("lng", lng);
i.putExtra("label", label);
startActivity(i);
Step 7 – Free option: OpenStreetMap with osmdroid (no key, no billing)
Add implementation("org.osmdroid:osmdroid-android:6.1.20"), the INTERNET permission and an org.osmdroid.views.MapView with id osm in the layout:
Configuration.getInstance().setUserAgentValue(getPackageName());
MapView osm = findViewById(R.id.osm);
osm.setMultiTouchControls(true);
GeoPoint point = new GeoPoint(33.7295, 73.0372);
osm.getController().setZoom(16.0);
osm.getController().setCenter(point);
Marker marker = new Marker(osm);
marker.setPosition(point);
marker.setTitle("Faisal Mosque");
osm.getOverlays().add(marker);
Run and test
| Test | Expected result |
|---|---|
| Faisal Mosque → Show on map | Google Maps with a pin "Faisal Mosque" |
| Latitude 95 | Error "Latitude must be between -90 and 90" |
| Longitude 190.5 | Longitude error |
| Latitude "abc" (paste) | Error, no crash |
| Navigate | Google Maps starts driving directions |
| Emulator without Maps app | Map opens in the browser |
| Part B | Embedded map with marker; map type changes |
Common errors and fixes
| Problem | Fix |
|---|---|
Crash NumberFormatException |
Use parseCoordinate() with try/catch |
| Pin label missing | Encode the label: Uri.encode(label) |
| Embedded map is grey | API key missing/restricted wrongly, or Maps SDK not enabled |
| "No Activity found" for navigation | Emulator without Google Play – use a Play image |
Short and long questions
1. (Viva) Explain the geo URI used in your app.
Model answer
geo:lat,lng?z=16&q=lat,lng(Label) – the scheme geo: tells Android it is a map location; lat,lng are the centre coordinates; z=16 sets zoom; q=lat,lng(Label) drops a marker with the given label. It is sent with ACTION_VIEW, optionally restricted to the Google Maps package.
2. (Viva) What steps are needed to show an embedded Google Map with a marker?
Model answer
Enable Maps SDK for Android and create a restricted API key (billing enabled), add play-services-maps and the key meta-data, put a SupportMapFragment in the layout, call getMapAsync, and in onMapReady add a marker with MarkerOptions and move the camera with CameraUpdateFactory.newLatLngZoom.
3. (Viva) What are the valid ranges of latitude and longitude, and how did you validate them?
Model answer
Latitude −90 to +90 and longitude −180 to +180. The app converted the text with parseCoordinate() (Double.parseDouble in try/catch) and showed setError messages when a value was missing or out of range before opening the map.
This lesson ends with a quiz of 9 MCQs. Open the lesson on PrepOasis to take it and save your progress.
Previous: Week 14 Theory – Threading; Publishing Android Applications · Next: Week 15 Theory – Deployment on App Stores; Mobile Programming Languages
All lessons in Mobile Application Development (CDE-315) – BS CS 5th Semester