帮我写一个百度定位的工具类
时间: 2024-06-09 07:05:02 浏览: 16
好的,以下是一个简单的基于百度地图API的定位工具类,供参考:
```java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* 百度地图定位工具类
*/
public class BaiduLocationUtils {
/**
* 根据经纬度获取地址信息
*
* @param longitude 经度
* @param latitude 纬度
* @return 地址信息
*/
public static String getAddress(double longitude, double latitude) throws IOException {
String url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak={你的百度地图AK}&output=json&coordtype=wgs84ll&location=" + latitude + "," + longitude;
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
String result = stringBuilder.toString();
JSONObject jsonObject = JSON.parseObject(result);
String address = jsonObject.getJSONObject("result").getString("formatted_address");
return address;
}
}
```
使用时,需要将代码中的 `{你的百度地图AK}` 替换为自己的百度地图开发者密钥。另外,由于该工具类使用了网络请求,建议在非 UI 线程中调用。