Problem
How to fetch user location in java web application from backend?
Solution
I tried Geolocation api to fetch latitute and latitute from the rest api but the test case failed when I deployed it on Server as it was fetching lat and long of Server Location.
And I am confused how to add other parameters to the url to make it work perfectly.
Below is my code -
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?