pom.xml:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
package com.demo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
public class demo {
public static void main(String[] args) {
//因测试需要代理
System.setProperty("https.proxyHost", "Your_Host");
System.setProperty("https.proxyPort", "Your_Port");
double latitude = lat; // 纬度
double longitude = long; // 经度
String apiKey = " Google Map appKey";
try {
String address = reverseGeocode(latitude, longitude, apiKey);
System.out.println("逆地址解析的地址输出: " + address);
// 检查是否在中国
boolean isChina = isLocationInMalaysia(address);
System.out.println("Location: " + (isChina ? true : false));
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
private static String reverseGeocode(double latitude, double longitude, String apiKey) throws IOException {
String apiUrl = "https://maps.googleapis.com/maps/api/geocode/json"; //终端地址
String urlString = apiUrl + "?latlng=" + latitude + "," + longitude + "&key=" + apiKey;
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
try {
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 获取响应代码
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应内容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 解析JSON响应
JSONObject jsonResponse = new JSONObject(response.toString());
JSONArray results = jsonResponse.getJSONArray("results");
if (results.length() > 0) {
JSONObject firstResult = results.getJSONObject(0);
return firstResult.getString("formatted_address");
} else {
return "No results found";
}
} else {
throw new IOException("HTTP error code: " + responseCode);
}
} finally {
// 关闭连接
connection.disconnect();
}
}
private static boolean isLocationInMalaysia(String address) {
// 通过地址信息,判断国家是否为中国
return address.toLowerCase().contains("china");
}
}