java 通过经纬度获取海拔高度 百度地图api
时间: 2023-11-18 13:41:33 浏览: 525
可以使用百度地图的Elevation API来获取经纬度对应的海拔高度。以下是Java代码示例:
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class ElevationAPI {
public static void main(String[] args) throws Exception {
String ak = "你的百度地图AK";
double lat = 39.915;
double lng = 116.404;
int coordType = 3; // 坐标类型,3代表WGS84坐标系
String url = "http://api.map.baidu.com/geoconv/v1/?coords=" + lng + "," + lat +
"&from=" + coordType + "&to=6&ak=" + ak;
String json = httpRequest(url);
// 解析返回的json数据
String status = getValueByKey(json, "status");
if ("0".equals(status)) {
String x = getValueByKey(json, "x");
String y = getValueByKey(json, "y");
// 获取海拔高度
url = "http://api.map.baidu.com/elevation/v1/?locations=" + y + "," + x + "&coordtype=wgs84&ak=" + ak;
json = httpRequest(url);
status = getValueByKey(json, "status");
if ("0".equals(status)) {
String elevation = getValueByKey(json, "elevation");
System.out.println("海拔高度:" + elevation);
} else {
System.out.println("获取海拔高度失败,错误码:" + status);
}
} else {
System.out.println("坐标转换失败,错误码:" + status);
}
}
public static String httpRequest(String requestUrl) throws IOException {
StringBuilder sb = new StringBuilder();
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
InputStream inputStream = connection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str;
while ((str = bufferedReader.readLine()) != null) {
sb.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
connection.disconnect();
return sb.toString();
}
public static String getValueByKey(String json, String key) {
String value = "";
int index = json.indexOf(key);
if (index > 0) {
index += key.length() + 2;
boolean flag = true;
while (flag) {
String tmp = json.substring(index, index + 1);
if (!",".equals(tmp) && !"}".equals(tmp)) {
value += tmp;
index++;
} else {
flag = false;
}
}
}
return value;
}
}
```
其中,ak是你的百度地图API Key,lat和lng分别是经纬度,coordType是坐标类型,这里使用的是WGS84坐标系。在代码中,先使用Geoconv API将经纬度转换为百度坐标系的x、y坐标,然后再使用Elevation API获取海拔高度。最后输出海拔高度即可。
阅读全文