Java可以使用地理编码服务将地址转换为经纬度坐标(GPS坐标)。地理编码服务是一种将地址转换为经纬度坐标的服务,通常由地图服务提供商提供。
有许多可用于Java的地理编码服务,例如Google Maps API和Bing Maps API。要使用这些服务,您需要注册并获取API密钥。然后,您可以使用Java代码调用API并传递地址信息,API将返回地址的经纬度坐标。
例如,使用Google Maps API进行地址转GPS的示例代码如下所示:
``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject;
public class AddressToGPS { // Replace YOUR_API_KEY with your Google Maps API key private static final String API_KEY = "YOUR_API_KEY";
public static void main(String[] args) { String address = "1600 Amphitheatre Parkway, Mountain View, CA"; String latLong = getLatLong(address); System.out.println(latLong); }
public static String getLatLong(String address) { try { URL url = new URL( "https://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&key=" + API_KEY); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output = "", full = ""; while ((output = br.readLine()) != null) { full += output; } JSONObject jsonObject = new JSONObject(full); JSONObject jsonObjectLocation = (JSONObject) jsonObject.get("results")[0].get("geometry").get("location");