目录

Elevation API

Function

Queries the altitude corresponding to a longitude-latitude point by specifying the longitude-latitude coordinates or the path and sampling point.

Scenario

You can use this API to develop walking and cycling apps, mobile positioning apps, or low-resolution measurement apps.

Restrictions

Prototype

Protocol

HTTPS POST

Direction

Your server -> Map Kit server

URL

https://mapapi.cloud.huawei.com/mapApi/v1/elevation/getElevation

Data Format

Request: Content-Type: application/json

Response: Content-Type: application/json

Request Parameters

At least one of Authorization in Request Header and key in Query String need to be set.

Request Header

Parameter

Mandatory

Type

Description

Content-Type

Yes

application/json

Request data format.

Authorization

No

String

Authentication mode. Access token (recommended) authentication and API key authentication are supported.

NOTE:

For access token authentication:

For API key authentication:

  • For details about how to obtain an API key, please refer to Obtaining the API Key.
  • You need to call the URLEncoder.encode("Your apiKey", "UTF-8") method to encode the API key using encodeURI. For example, if the original API key is ABC/DFG+, the conversion result is ABC%2FDFG%2B.
  • You are advised to take measures for protecting the API key security. For details, please refer to How can I protect the API key?.

Query String

Parameter

Mandatory

Type

Description

key

No

String

Authentication key. For details about how to obtain one, please refer to Obtaining the API Key.

NOTE:
  1. For details about how to obtain an API key, please refer to Obtaining the API Key.
  2. You need to call the URLEncoder.encode("Your apiKey", "UTF-8") method to encode the API key using encodeURI. For example, if the original API key is ABC/DFG+, the conversion result is ABC%2FDFG%2B.

Request Body

The parameter priorities are as follows: locations > encodedLocation > path + samples > encodedPath + samples. The parameters are described as follows:

  1. If locations is passed, only the longitude and latitude specified in locations are used.
  2. If locations is not passed, but encodedLocation is passed, only the decoded longitude and latitude are used.
  3. If both locations and encodedLocation are not passed, but path and samples are passed, only the longitude and latitude of the generated sampling point are used.
  4. If locations, encodedLocation, and path are not passed, but encodedPath and samples are passed, the sampling path is decoded and then only the longitude and latitude of the generated sampling point are used.

Parameter

Mandatory

Type

Description

locations

No

Coordinate[]

Collection of 1 to 512 longitude-latitude coordinates, which are used to calculate the altitude.

encodedLocation

No

String

Longitude-latitude coordinates encoded using the GeoHash algorithm.

The value can be an array of strings separated by semicolons (;).

path

No

Coordinate[]

Specified path for calculating the altitude. The value is a collection of longitude-latitude coordinates along the path.

encodedPath

No

String

Longitude-latitude coordinates in the path, which are encoded using the GeoHash algorithm.

The value can be an array of strings separated by semicolons (;).

samples

No

Integer

Number of sampling points in the path.

This parameter is used to generate the specified number of equidistant sampling points in the path specified by path or encodedPath. The path start and end points are also counted in the number of sampling points.

This parameter is mandatory if path or encodedPath is passed.

Request Example

POST https://mapapi.cloud.huawei.com/mapApi/v1/elevation/getElevation?key=API key HTTP/1.1
Content-Type: application/json
Accept: application/json
{
    "locations": [
        {
          "lat": 21.0,
          "lng": 21.0
        },
        {
          "lat": 21.5,
          "lng": 21.5
        }
    ]
}

Response Parameters

When the status code is 200:

Response Header

Parameter

Mandatory

Type

Description

Content-Type

Yes

application/json

Data format of a response.

Response Body

Parameter

Type

Description

returnCode

String

Result code. For details, please refer to Result Codes.

returnDesc

String

Result description.

results

ElevationResult[]

Altitude information returned upon successful query.

Response Example

When the status code is 200:

HTTP/1.1 200 OK
Content-type: application/json
{
    "returnCode": "0",
    "results": [
        {
            "elevation": 572.0,
            "location": {
                "lng": 21.0,
                "lat": 21.0
            },
            "resolution": 28.868248865094273
        },
        {
            "elevation": 513.0,
            "location": {
                "lng": 21.5,
                "lat": 21.5
            },
            "resolution": 28.77044670027833
        }
    ],
    "returnDesc": "OK"
}

Call Example

Access token authentication 
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@Slf4j
class TestElevation {
    private static final Logger log = LoggerFactory.getLogger(TestElevation.class);

    public static final String ROOT_URL = "https://mapapi.cloud.huawei.com/mapApi/v1/elevation/getElevation";
 
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
 
    public static void getElevation(String accessToken) throws UnsupportedEncodingException {
        JSONObject json = new JSONObject();
 
        try {
            JSONArray locations = new JSONArray();
            JSONObject startingPoint_1 = new JSONObject();
            JSONObject startingPoint_2 = new JSONObject();
 
            startingPoint_1.put("lng", 21.0);
            startingPoint_1.put("lat", 21.0);
 
            startingPoint_2.put("lng", 21.5);
            startingPoint_2.put("lat", 21.5);
 
            locations.add(0, startingPoint_1);
            locations.add(1, startingPoint_2);
 
            json.put("locations", locations);
        } catch (JSONException e) {
            log.error("getElevation failed : {}", e.getMessage());
        }
        RequestBody body = RequestBody.create(JSON, json.toJSONString());
        OkHttpClient client = new OkHttpClient();
        Request request =
                new Request.Builder().url(ROOT_URL).addHeader("Authorization", "Bearer " + accessToken) 
                        .post(body)
                        .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.error("getElevation onFailure : {}", e.toString());
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                log.debug("getElevation onResponse : {}", response.body().string());
            }
        });
    }
}
API key authentication
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
@Slf4j
class TestElevation {
    private static final Logger log = LoggerFactory.getLogger(TestElevation.class);

    public static final String ROOT_URL = "https://mapapi.cloud.huawei.com/mapApi/v1/elevation/getElevation";
 
    public static final String connection = "?key=";
 
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
 
    public static void getElevation(String apiKey) throws UnsupportedEncodingException {
        JSONObject json = new JSONObject();
 
        try {
            JSONArray locations = new JSONArray();
            JSONObject startingPoint_1 = new JSONObject();
            JSONObject startingPoint_2 = new JSONObject();
 
            startingPoint_1.put("lng", 21.0);
            startingPoint_1.put("lat", 21.0);
 
            startingPoint_2.put("lng", 21.5);
            startingPoint_2.put("lat", 21.5);
 
            locations.add(0, startingPoint_1);
            locations.add(1, startingPoint_2);
 
            json.put("locations", locations);
        } catch (JSONException e) {
            log.error("getElevation failed : {}", e.getMessage());
        }
        RequestBody body = RequestBody.create(JSON, json.toJSONString());
        OkHttpClient client = new OkHttpClient();
        Request request =
                new Request.Builder().url(ROOT_URL + connection + URLEncoder.encode(apiKey, "UTF-8"))
                        .post(body)
                        .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                log.error("getElevation onFailure : {}", e.toString());
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                log.debug("getElevation onResponse : {}", response.body().string());
            }
        });
    }
}

GeoHash Algorithm Encoding Example

/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2021. All rights reserved.
 */

package elevation;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * GeoHash encoding.
 */
public class GeoHashUtil {
    private static final int NUM_BITS = 3 * 5;

    private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'b', 'c', 'd', 'e', 'f',
        'g', 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

    // Define the code mapping.
    private static final HashMap<Character, Integer> lookup = new HashMap<>();

    static {
        // Initialize the code mapping content.
        int index = 0;
        for (char c : DIGITS) {
            lookup.put(c, index++);
        }
    }

    /**
     * Encoding.
     * 
     * @param lat double
     * @param lng double
     * @return String
     */
    public static String encode(double lat, double lng) {
        BitSet latbits = getBits(lat, -90, 90);
        BitSet lonbits = getBits(lng, -180, 180);
        StringBuilder buffer = new StringBuilder();
        for (int i = 0; i < NUM_BITS; i++) {
            buffer.append((lonbits.get(i)) ? '1' : '0');
            buffer.append((latbits.get(i)) ? '1' : '0');
        }
        return base32(Long.parseLong(buffer.toString(), 2));
    }

    private static BitSet getBits(double lat, double floor, double ceiling) {
        BitSet buffer = new BitSet(NUM_BITS);
        for (int i = 0; i < NUM_BITS; i++) {
            double mid = (floor + ceiling) / 2;
            if (lat >= mid) {
                buffer.set(i);
                floor = mid;
            } else {
                ceiling = mid;
            }
        }
        return buffer;
    }

    private static String base32(long i) {
        char[] buf = new char[65];
        int charPos = 64;
        boolean negative = (i < 0);
        if (!negative) {
            i = -i;
        }
        while (i <= -32) {
            buf[charPos--] = DIGITS[(int) (-(i % 32))];
            i /= 32;
        }
        buf[charPos] = DIGITS[(int) (-i)];
        if (negative) {
            buf[--charPos] = '-';
        }
        return new String(buf, charPos, (65 - charPos));
    }

    private static double decode(BitSet bs, double floor, double ceiling) {
        double mid = 0;
        for (int i = 0; i < bs.length(); i++) {
            mid = (floor + ceiling) / 2;
            if (bs.get(i)) {
                floor = mid;
            } else {
                ceiling = mid;
            }
        }
        return mid;
    }

    /**
     * Decode the encoded character string.
     *
     * @param geohash String
     * @return double[]
     */
    public static List<CoordinateDTO> decode(String geohash) {
        return Arrays.stream(geohash.split(";")).map(GeoHashUtil::decodeSingle).collect(Collectors.toList());
    }

    private static CoordinateDTO decodeSingle(String geohash) {
        StringBuilder buffer = new StringBuilder();
        for (char c : geohash.toCharArray()) {
            int i = lookup.get(c) + 32;
            buffer.append(Integer.toString(i, 2).substring(1));
        }

        BitSet lngset = new BitSet();
        BitSet latset = new BitSet();

        int j = 0;
        for (int i = 0; i < NUM_BITS * 2; i += 2) {
            boolean isSet = false;
            if (i < buffer.length()) {
                isSet = buffer.charAt(i) == '1';
            }
            lngset.set(j++, isSet);
        }

        j = 0;
        for (int i = 1; i < NUM_BITS * 2; i += 2) {
            boolean isSet = false;
            if (i < buffer.length()) {
                isSet = buffer.charAt(i) == '1';
            }
            latset.set(j++, isSet);
        }

        double lng = decode(lngset, -180, 180);
        double lat = decode(latset, -90, 90);

        CoordinateDTO coordinateDTO = new CoordinateDTO();
        coordinateDTO.setLat(lat);
        coordinateDTO.setLng(lng);
        return coordinateDTO;
    }

    /**
     * Longitude and latitude.
     */
    @Getter
    @Setter
    @NoArgsConstructor
    @AllArgsConstructor
    @ToString
    public static class CoordinateDTO {
        private Double lat;

        private Double lng;
    }
}