java根据地址获取高德地图的经纬度
时间: 2023-08-30 11:09:57 浏览: 53
要根据地址获取高德地图的经纬度,可以使用高德地图提供的Web API接口,可以通过Java代码发送HTTP请求,获取到返回的JSON格式数据,从而解析出经纬度信息。
以下是一个使用Java发送HTTP请求,获取高德地图经纬度的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class GetLocation {
public static void main(String[] args) {
try {
// 地址信息
String address = "北京市海淀区中关村大街27号";
// 转换地址编码
String addressEncode = URLEncoder.encode(address, "UTF-8");
// 发送HTTP请求
URL url = new URL("http://restapi.amap.com/v3/geocode/geo?key=your_key&address=" + addressEncode);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
// 读取HTTP响应
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 解析经纬度信息
String[] location = response.toString().split(",\"");
if (location.length >= 2) {
String[] lnglat = location[1].split("\":\"");
if (lnglat.length >= 2) {
System.out.println("经度:" + lnglat[1].split(",")[0]);
System.out.println("纬度:" + location[0].split(":")[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
其中,`your_key`需要替换为自己的高德地图开发者Key。