java 根据地址返回经纬度
时间: 2023-11-08 15:04:42 浏览: 169
要根据地址返回经纬度,可以使用一些地图API,例如高德地图API、百度地图API、谷歌地图API等。这里以高德地图API为例,介绍如何实现。
1. 首先需要在高德开放平台上注册账号,并创建一个应用,获得一个API Key。
2. 使用Java发送HTTP请求,调用高德地图API的地理编码接口,将地址作为参数传入,获取经纬度信息。示例代码如下:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class AddressToLocation {
public static void main(String[] args) {
String address = "广东省深圳市南山区科技园"; // 要查询的地址
String key = "your_api_key"; // 高德地图API Key
try {
address = URLEncoder.encode(address, "UTF-8");
String url = "https://restapi.amap.com/v3/geocode/geo?key=" + key + "&address=" + address;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String result = response.toString();
System.out.println(result); // 输出API返回的结果
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
3. 解析API返回的结果,获取经纬度信息。示例代码如下:
```
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class AddressToLocation {
public static void main(String[] args) {
String address = "广东省深圳市南山区科技园"; // 要查询的地址
String key = "your_api_key"; // 高德地图API Key
try {
address = URLEncoder.encode(address, "UTF-8");
String url = "https://restapi.amap.com/v3/geocode/geo?key=" + key + "&address=" + address;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
String result = response.toString();
JSONObject jsonObject = JSONObject.parseObject(result);
JSONArray geocodes = jsonObject.getJSONArray("geocodes");
if (geocodes != null && !geocodes.isEmpty()) {
JSONObject location = geocodes.getJSONObject(0).getJSONObject("location");
String lng = location.getString("lng"); // 经度
String lat = location.getString("lat"); // 纬度
System.out.println("经度:" + lng + ",纬度:" + lat);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
注意:这里使用了FastJSON库来解析JSON数据,需要先下载并导入到项目中。
阅读全文
相关推荐










