In this post we will see how-to use the Elevation API in android to retrieve the Elevation data of a specific location.

Before starting, we have to get an Api Key to use this service. We have to go to the following link https://developers.google.com/maps/documentation/elevation/start and click on the button “Get a Key”, that is in the section “Activate the APiIand get an API key”. Follow the instruction and get the API Key.

Note: Without the API Key we can’t use this service.

Note: To get the Elevation data of a specific location, we need it’s specific GPS coordinated in the Lat/Lon format.

How to retrieve Elevation data

To retrieve the Elevation data we have to make an HTTPS request with a specific formatted url:

https://maps.googleapis.com/maps/api/elevation/json?locations=LAT,LON&key=API_KEY

where, we have to substitute LAT,LON with the Gps coordinates of the location and API_KEY with the APi Key that you get from the previous url.

Once we make the HTTPS request, we will get a response in a JSON format. What we jave to do is to parsing the JSON response and extract the Elevation data.  An example of a JSON response could be the following:

{
   "results" : [
      {
         "elevation" : 1608.637939453125,
         "location" : {
            "lat" : 39.73915360,
            "lng" : -104.98470340
         },
         "resolution" : 4.771975994110107
      }
   ],
   "status" : "OK"
}

Android Implementation

As there is no a real Android API for the Elevation, we have to work as a web application.

HTTP request

The first thing we have to do is to generate an HTTP request with the format we have seen before. You can use whatever library you want to make it, or you can use the following one:

 public class GetHttp {

    public static int GetHttpToServer(String urlLink, StringBuffer response) {
        try {
            URL obj = new URL(urlLink);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
            conn.setRequestMethod("GET");
            int responseCode = conn.getResponseCode();

            BufferedReader in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        } catch (MalformedURLException ex) {
            Log.e("GetHttp", Log.getStackTraceString(ex));
            return 2;
        } catch (NoRouteToHostException ex) {
            Log.e("GetHttp", Log.getStackTraceString(ex));
            return 3;
        } catch (SocketTimeoutException ex){
            Log.e("GetHttp", Log.getStackTraceString(ex));
            return 4;
        } catch (SSLException ex){
            Log.e("GetHttp", Log.getStackTraceString(ex));
            return 5;

        } catch (IOException ex) {
            Log.e("GetHttp", Log.getStackTraceString(ex));
            return 6;
        } catch (Exception e){
            Log.e("GetHttp", Log.getStackTraceString(e));
            return 7;

        }
        return 0;
    }
}

As you can see the class to make the HTTP request (GetHTTP) is very simple. It has only one function GetHTTPToServer that requires in input the url and a StringBuffer to store the HTTP response (formatted in JSON in our case).

The try{…} catch{…} section is needed to check possible error while we make the HTTP request. In absence of error we will get the value 0. We will get a value ranginf from 1-6 (depends on the exception that occurs) and we will get 7 if the error was not listed in the previous exceptions.

Note: This class can be defined directly in one Activity or, better method, it can be defined in a separed file and then called inside the Activity.

Parsing the JSON response

Once we get the respone we have to parse the Elevation data:

int ret;
double Lat,Lon;
double elevation;
String ApiKey = "XXXXXXXXXXXXXXXX";   //Your Api Key
String url = "https://maps.googleapis.com/maps/api/elevation/json?locations=" + Lat + "," + Lon + "&key="+ApiKey;
StringBuffer response = new StringBuffer();

ret = com.domain.package.GetHttp.GetHttpToServer(url, response);

if (ret == 0) 
{
    try {
        JSONObject jsonObj = new JSONObject(response.toString());
        JSONArray resultEl = jsonObj.getJSONArray("results");
        JSONObject current = resultEl.getJSONObject(0);
        elevation = Double.parseDouble(current.getString("elevation"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

To get the return value of the GetHTTPToSever we use an int variable. To specify the Lat/Lon coordinates we use two double variables (possible upgrade: instead of giving directly the Lat/Lon coordinates, you can let the user insert them or retrieve them from the GPS sensor). We use a double for the Elevation data, a String for the url and the ApiKey and then we use a StringBuffer ti store the response.

Once the function is executed, we get the return value. If the return value is 0, we parse the JSON respone and we get the Elevation data. The try{…} catch{…} section is needed to check that the JSON parsing will be fine.

Note: If in the same time that you get the Elevation data you have to perform any other operation, it’s better to make the HTTP request inside the AsyncTask classes in order to make the request in background without block the execution of other tasks.