Search code examples
javageolocation

How to fetch user location in java web application from backend?


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?


Solution

  • May I know whose coordinates you want to access? If you want to access end user / visitor IP address, the Google Geolocation API won't be working.

    HTML5 geolocation is a client-side feature and required approval from client to receive their coordinates.

    The best option you can try is to use the visitor IP address and estimate it using geolocation database. You can start with free IP2Location LITE DB5 with coordinates.