使用java免费将地理位置转换为经纬度
时间: 2023-12-31 22:07:13 浏览: 67
您可以使用Java中提供的Google Maps API或OpenStreetMap API来免费将地理位置转换为经纬度。这些API允许您通过HTTP请求向服务发送地址或地点名称,并返回与该地点相关的经度和纬度坐标。以下是一个使用Google Maps API的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class Geocoding {
public static String getLatLng(String address) throws Exception {
String url = "https://maps.googleapis.com/maps/api/geocode/json?address=" + address.replace(" ", "+");
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();
JSONObject json = new JSONObject(response.toString());
JSONObject location = json.getJSONArray("results").getJSONObject(0).getJSONObject("geometry").getJSONObject("location");
double lat = location.getDouble("lat");
double lng = location.getDouble("lng");
return lat + "," + lng;
}
public static void main(String[] args) throws Exception {
String address = "1600 Amphitheatre Parkway, Mountain View, CA";
String latLng = getLatLng(address);
System.out.println(latLng);
}
}
```
在上述代码中,我们首先构造了Google Maps API的URL,然后使用Java的HttpURLConnection类发送GET请求并获取响应。接下来,我们将响应字符串解析为JSON格式,并提取出经度和纬度坐标。最后,我们将这些坐标合并为一个字符串并返回。在此示例中,我们将地址设置为1600 Amphitheatre Parkway,Mountain View,CA,并获取其经度和纬度坐标。