Convert GPS Coordinates to Address using Google Geocoding API using Java

Google Logo

Google Maps makes it easy to convert addresses to their corresponding GPS coordinates using the Geocoding API. But what if you want to do the reverse, i.e. convert GPS coordinates to the corresponding address? Simple, just use Google’s ReverseGeocoding functionality.

Below you find a simple Java example of how to use the API to convert GPS coordinates to addresses:

package at.kerstner.geocoding;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

/**
 *
 * @param lng
 * @param lat
 * @return
 */
    private String getAddressByGpsCoordinates(String lng, String lat)
            throws MalformedURLException, IOException, org.json.simple.parser.ParseException {
        
        URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?latlng="
                + lat + "," + lng + "&sensor=true");
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        String formattedAddress = "";

        try {
            InputStream in = url.openStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String result, line = reader.readLine();
            result = line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }

            JSONParser parser = new JSONParser();
            JSONObject rsp = (JSONObject) parser.parse(result);

            if (rsp.containsKey("results")) {
                JSONArray matches = (JSONArray) rsp.get("results");
                JSONObject data = (JSONObject) matches.get(0); //TODO: check if idx=0 exists
                formattedAddress = (String) data.get("formatted_address");
            }

            return "";
        } finally {
            urlConnection.disconnect();
            return formattedAddress;
        }
    }

The example above retrieves the formatted address of the first result found. Additional checks have been omitted for better readability.

The API response has the following format:

{"results":[
{"address_components":[
{"long_name":"1","types":["street_number"],"short_name":"1"},
{"long_name":"Entenplatz","types":["route"],"short_name":"Entenpl."},
{"long_name":"Gries","types":["sublocality","political"],"short_name":"Gries"},
{"long_name":"Graz","types":["locality","political"],"short_name":"Graz"},
{"long_name":"Graz","types":["administrative_area_level_2","political"],"short_name":"Graz"},
{"long_name":"Styria","types":["administrative_area_level_1","political"],"short_name":"Stmk."},
{"long_name":"Austria","types":["country","political"],"short_name":"AT"},
{"long_name":"8020","types":["postal_code"],"short_name":"8020"}],
"formatted_address":"Entenplatz 1, 8020 Graz, Austria",
"types":["street_address"],"geometry":{"viewport":{"southwest":{"lng":15.4327164197085,"lat":47.0663661197085},"northeast":{"lng":15.4354143802915,"lat":47.0690640802915}},"location_type":"ROOFTOP","location":{"lng":15.4340654,"lat":47.0677151}}},

{"address_components":[{...}]}

]}

You also might want to checkout http://www.mobilefish.com/services/coordinate_converter/coordinate_converter.php for an easy way to handle and convert coordinates and preview them on a map.

Comments

9 responses to “Convert GPS Coordinates to Address using Google Geocoding API using Java”

  1. Moe Avatar
    Moe

    THANKS VERY VERY MUCH!!!!

  2. Kasun Avatar
    Kasun

    Thanks a lot friend!!!

    1. afsar Avatar
      afsar

      Can u plz tell which jars i have to use for this code

  3. Danish Avatar
    Danish

    will u plz send me the whole code?

  4. Sreekanth V S Avatar
    Sreekanth V S

    Thanks a lot….perfect.

    1. ali Avatar
      ali

      hi srikant could u please send me the code

  5. Nadeem Avatar
    Nadeem

    How i can process multiple latitude/longitude to get their respective address in a single request.
    Please suggest

  6. vara Avatar
    vara

    java.io.IOException: Server returned HTTP response code: 400 for URL: http://maps.googleapis.com/maps/api/geocode/json?latlng=‎17.387140,78.491684&sensor=true
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.URL.openStream(Unknown Source)
    at vara.app.in.Location.getlocation(Location.java:26)
    at vara.app.in.Location.main(Location.java:18)

    1. vara Avatar
      vara

      i am getting this error. while using this code, can u help me ?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.