Skip to content
VirtualLP Virtual Learning Platform

Practical 4: Consuming the Google Maps REST API

14 min read Topic 28 of 34 1 hands-on lab

Aim

Write a Java program that sends an address or place name to Google Maps. Show the full address, latitude, longitude and a map link. Read the JSON (JavaScript Object Notation) reply and handle missing results, access errors and request limits.

Theory

A Google Maps web service accepts an HTTPS (Hypertext Transfer Protocol Secure) request and returns data in JSON. Your program reads that data and chooses the fields it needs.

Latitude tells how far north or south a place is. Longitude tells how far east or west it is. An API (Application Programming Interface) key identifies the project making the request.

asking for directions

You ask a shopkeeper "Where is Gateway of India?" (the request). He replies "Colaba, near the Taj hotel" (the response). Geocoding is asking Google the same question – but the answer comes as exact map coordinates in JSON. Your API key is like a membership card that proves you are allowed to ask.

sequenceDiagram
    participant A as Java client (PlaceFinder)
    participant G as maps.googleapis.com
    A->>A: read API key from config.properties
    A->>G: GET /maps/api/geocode/json?address=Gateway+of+India&key=AIza…
    G-->>A: {"results":[{"formatted_address":…,"geometry":{"location":{"lat":18.92,"lng":72.83}}}],"status":"OK"}
    A->>G: GET /maps/api/place/textsearch/json?query=cafes+in+Mumbai&key=AIza…
    G-->>A: {"results":[{"name":"Kyani & Co.",…}],"status":"OK"}
API Endpoint Main parameters Main fields in the answer
Geocoding – address → coordinates /maps/api/geocode/json address, key formatted_address, geometry.location.lat/lng, place_id
Places Text Search – find businesses /maps/api/place/textsearch/json query, key name, formatted_address, rating, types

The status values you must handle

Status Meaning What your program should do
OK Results found Read the results
ZERO_RESULTS The request was fine, but nothing was found Tell the user politely – don't crash
REQUEST_DENIED The API key is missing, wrong or restricted Check the key and that the API is enabled; show error_message
OVER_QUERY_LIMIT Too many requests / quota used up Wait and try again later
INVALID_REQUEST A required parameter is missing Fix the request
Key point

Google APIs reply with HTTP (Hypertext Transfer Protocol) 200 even when there is a logical error – so always check the JSON status field. Keep the API key outside the code (a properties file or an environment variable) and restrict it in the Google Cloud console.

Main Java classes used

Class Use
java.net.http.HttpClient / HttpRequest / HttpResponse Send the GET request (Java 11+)
URLEncoder.encode(text, UTF_8) Make spaces and special characters safe for a URL (Uniform Resource Locator) (Gateway of India → Gateway+of+India)
org.json.JSONObject / JSONArray Read the JSON reply
ResourceBundle Read maps.api.key from config.properties

Requirements

JDK (Java Development Kit) 21, Eclipse, the org.json library, and a Google Cloud project with the Geocoding API and Places API enabled and an API key.

The Places request below uses Places API (Legacy). New Google Cloud projects cannot enable it. Use an existing enabled project for this example, or follow the Places API (New) guide. Geocoding is a separate API.

Program – PlaceFinder.java

This is the request-handling part of main(String[] args) throws Exception. Import java.net.URI, java.net.URLEncoder, java.net.http.*, java.nio.charset.StandardCharsets, java.util.ResourceBundle and org.json.*.

final String GEOCODE_URL = "https://maps.googleapis.com/maps/api/geocode/json";
final String PLACES_URL = "https://maps.googleapis.com/maps/api/place/textsearch/json";
String apiKey = ResourceBundle.getBundle("config").getString("maps.api.key");
HttpClient http = HttpClient.newHttpClient();

String address = "Gateway of India, Mumbai";
String url = GEOCODE_URL + "?address=" + URLEncoder.encode(address, StandardCharsets.UTF_8) + "&key=" + apiKey;
HttpResponse<String> response = http.send(HttpRequest.newBuilder(URI.create(url)).GET().build(),
        HttpResponse.BodyHandlers.ofString());

if (response.statusCode() != 200) {
    System.out.println("HTTP error: " + response.statusCode());
    return;
}
JSONObject json = new JSONObject(response.body());
String status = json.getString("status");
if (!status.equals("OK")) {
    System.out.println("Geocoding failed: " + status + " - " + json.optString("error_message", "no results"));
    return;
}
JSONObject first = json.getJSONArray("results").getJSONObject(0);
JSONObject loc = first.getJSONObject("geometry").getJSONObject("location");
System.out.println("Address  : " + first.getString("formatted_address"));
System.out.printf("Latitude : %.6f%n", loc.getDouble("lat"));
System.out.printf("Longitude: %.6f%n", loc.getDouble("lng"));
System.out.println("Map      : https://www.google.com/maps?q=" + loc.getDouble("lat") + "," + loc.getDouble("lng"));

// Places Text Search
String placesUrl = PLACES_URL + "?query=" + URLEncoder.encode("cafes in Mumbai", StandardCharsets.UTF_8) + "&key=" + apiKey;
HttpResponse<String> placesResponse = http.send(HttpRequest.newBuilder(URI.create(placesUrl)).GET().build(),
        HttpResponse.BodyHandlers.ofString());
if (placesResponse.statusCode() != 200) {
    System.out.println("Places HTTP error: " + placesResponse.statusCode());
    return;
}
JSONObject placesJson = new JSONObject(placesResponse.body());
if (!"OK".equals(placesJson.optString("status"))) {
    System.out.println("Places result: " + placesJson.optString("status"));
    return;
}
JSONArray places = placesJson.getJSONArray("results");
for (int i = 0; i < places.length(); i++) {
    JSONObject p = places.getJSONObject(i);
    System.out.println((i + 1) + ". " + p.getString("name") + " - " + p.getString("formatted_address"));
}

What the code does, step by step:

  1. Reads the API key from config.properties (not written in the code).
  2. Builds the URL – the address is URL-encoded and the key is added.
  3. Sends the GET request and gets the reply as text.
  4. Parses the JSON and checks status – if it is not OK, it prints the status and the error message and stops (no crash).
  5. Takes the first result, digs into geometry → location and prints the address, latitude, longitude and a map link.
  6. Then does a Places search for "cafes in Mumbai" and prints each café's name and address in a numbered list.

config.properties

maps.api.key=AIza…your-key…

Procedure

  1. Run the program with a placeholder (fake) key – observe REQUEST_DENIED and the error_message.
  2. Put your real API key in config.properties and run again – the address and coordinates are printed.
  3. Add the Places Text Search part and print the list of cafés.
  4. Try an address that does not exist – the program prints ZERO_RESULTS instead of crashing.
  5. Look at the requests and JSON replies in the HTTP monitor.

Virtual lab · Web Services · 35 min

Practical 4: Place search and geolocation with the Google Maps REST APIs

Write a Java client that calls the Google Maps Geocoding and Places Text Search APIs: configure the API key, build the HTTP request, parse the JSON, and handle REQUEST_DENIED and ZERO_RESULTS responses.

Open lab

Output / Observations

Example output for the settings in this lesson:

Address  : Apollo Bandar, Colaba, Mumbai, Maharashtra 400001, India
Latitude : 18.921984
Longitude: 72.834654
Map      : https://www.google.com/maps?q=18.9219841,72.8346543
Cafes in Mumbai:
1. Café Mondegar - Metro House, Colaba Causeway, Mumbai 400001, India
2. Kyani & Co. - JSS Rd, Marine Lines East, Mumbai 400002, India
3. Starbucks Horniman Circle - Elphinstone Building, Fort, Mumbai 400001, India

Conclusion

Check that a valid place returns an address and location. Keep the API key in the settings file. Test a place with no result and a request with an invalid key. The program should explain the error without stopping unexpectedly.

Viva questions

  1. Why must query values be URL-encoded? Spaces, commas and special characters would otherwise break the URL.
  2. Why check the status field when HTTP is 200? Google returns logical errors inside a 200 response.
  3. How should an API key be protected? Keep it out of source control, use environment/config files, and restrict it by API and by application in the console.
  4. What is the difference between the Geocoding and Places APIs? Geocoding converts an address ⇄ coordinates; Places searches for businesses and points of interest.
  5. What would you do on OVER_QUERY_LIMIT? Wait and retry with increasing delays (exponential back-off), cache results, ask for a higher quota.
  6. Which Java class sends HTTP requests since Java 11? java.net.http.HttpClient.

Practise this topic

Hands-on virtual lab

Apply what you just read in a realistic, guided simulation. Free with a verified account.

Create a free account to track your progress and unlock virtual labs.