问题
如何从后端获取 Java Web 应用程序中的用户位置?
解决方案
我尝试使用地理定位 api 从其余 api 获取纬度和纬度,但当我将其部署到服务器上时,测试用例失败,因为它正在获取服务器位置的纬度和经度。
我很困惑如何向 url 添加其他参数以使其完美工作。
下面是我的代码 -
public static JSONObject getLatLon() {
JSONObject Jobject = null;
String json = createJson();
LOG.info("Json is " + json);
okhttp3.RequestBody body = okhttp3.RequestBody.create(JSON, json);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://www.googleapis.com/geolocation/v1/geolocate?key=XXX")
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
LOG.info("response is " + response);
String resStr = response.body().string();
LOG.info("response String is " + resStr);
Jobject = new JSONObject(resStr);
LOG.info("Json Object is " + Jobject);
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return Jobject;
}
public static String createJson() {
ObjectMapper mapper = new ObjectMapper();
String json = null;
try {
return mapper.writeValueAsString(json);
} catch (JsonProcessingException e) {
}
return null;
}
Can anyone guide me how can I fetch latitute and longitute so that endUser location can be fetched?
最佳答案
我可以知道您想访问谁的坐标吗?如果您想访问最终用户/访问者 IP 地址,Google Geolocation API 将无法工作。
HTML5 地理定位是一项客户端功能,需要得到客户端的批准才能接收其坐标。
您可以尝试的最佳选择是使用访问者 IP 地址并使用地理位置数据库对其进行估计。您可以从免费IP2Location LITE DB5开始与坐标。
关于java - 如何从后端获取java Web应用程序中的用户位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47509783/