How to determine location of device in Android using IP address

前端 未结 5 1785
忘掉有多难
忘掉有多难 2021-02-04 05:21

I am developing an Android app. I want to determine the location of the device using its IP address. Where do I start? The links on Google APIs are not conclusive enough. Thanks

相关标签:
5条回答
  • 2021-02-04 05:49

    You can use freegeoip.net.

    It's a free, open source service. You can use the service directly or run it on your personal server. It can also get deployed to Heroku pretty easily.

    To get the IP location simply use OkHttp to send a http/https request:

    String url = "https://freegeoip.net/json/"
    Request mRequest = new Request.Builder()
            .url(url)
            .build();
    Context mContext // A UI context
    new OkHttpClient().newCall(mRequest).enqueue(new Callback() {
        Handler mainHandler = new Handler(mContext.getApplicationContext().getMainLooper());
    
        @Override
        public void onResponse(Call call, Response response) {
            String responseBody = null;
            try {
                responseBody = response.body().string();
            } catch (final IOException e) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        // handle error
                    }
                });
            }
    
            final String finalResponseBody = responseBody;
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    // handle response body
                    try {
                        JSONObject locationObject = new JSONObject(finalResponseBody);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
        @Override
        public void onFailure(Call call, final IOException e) {
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    mNetworkListener.onNetworkError(e.getMessage());
                }
            });
        }
    });
    

    And the response will look like something like this:

    {
        "ip": "192.30.253.113",
        "country_code": "US",
        "country_name": "United States",
        "region_code": "CA",
        "region_name": "California",
        "city": "San Francisco",
        "zip_code": "94107",
        "time_zone": "America/Los_Angeles",
        "latitude": 37.7697,
        "longitude": -122.3933,
        "metro_code": 807
    }
    
    0 讨论(0)
  • 2021-02-04 05:56

    I use this to get ip, country and city of device

    to test you can use RESTCLIENT , the firefox addon for making HTTP requests.

    simply copy https://addons.mozilla.org/en-us/firefox/addon/restclient/ this URL and test in RESTCLIENT or just past in browser address bar

    Hope This helps!

    0 讨论(0)
  • 2021-02-04 05:57

    Checkout Google Maps Geolocation API

    Sample POST:

    https://www.googleapis.com/geolocation/v1/geolocate?key=YOUR_API_KEY
    

    Sample response:

    {
      "location": {
        "lat": 51.0,
        "lng": -0.1
      },
      "accuracy": 1200.4
    }
    

    Limits:

    Users of the standard API:

    2,500 free queries per day 10 query per second, per user Enable pay-as-you-go billing to unlock higher quotas:

    $0.50 USD / 1000 additional queries, up to 100,000 daily.

    MORE

    0 讨论(0)
  • 2021-02-04 05:57

    We can get the location by simple API call, but it will have low accuracy.

    LocationApiService apiService = getGeoApiService();
        apiService.getLocation().enqueue(new Callback<GeoResponse>() {
            @Override
            public void onResponse(Call<GeoResponse> call, Response<GeoResponse> response) {
                response.body().getLatitude();
                response.body().getLongitude();
            }
    
            @Override
            public void onFailure(Call<GeoResponse> call, Throwable t) {
                t.getMessage();
            }
        });
    

    LocationApiService

    public interface LocationApiService {
        @GET("json")
        Call<GeoResponse> getLocation();
    }
    

    getGeoApiService()

    public static final String BASE_URL = "http://ip-api.com/";
    
    public static LocationApiService getGeoApiService() {
            return new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build()
                    .create(LocationApiService.class);
        }
    

    GeoResponse

    public class GeoResponse {
    
        private String as;
        private String city;
        private String country;
        private String countryCode;
        private String isp;
        @SerializedName("lat")
        private double latitude;
        @SerializedName("lon")
        private double longitude;
        private String org;
        private String query;
        private String region;
        private String regionName;
        private String timezone;
    
        @Override
        public String toString() {
            return "countryCode: " + countryCode + ", isp: " + isp + ", city: " + city;
        }
    
        public String getAs() {
            return as;
        }
    
        public void setAs(String as) {
            this.as = as;
        }
    
        public String getCity() {
            return city;
        }
    
        public void setCity(String city) {
            this.city = city;
        }
    
        public String getCountry() {
            return country;
        }
    
        public void setCountry(String country) {
            this.country = country;
        }
    
        public String getCountryCode() {
            return countryCode;
        }
    
        public void setCountryCode(String countryCode) {
            this.countryCode = countryCode;
        }
    
        public String getIsp() {
            return isp;
        }
    
        public void setIsp(String isp) {
            this.isp = isp;
        }
    
        public double getLatitude() {
            return latitude;
        }
    
        public void setLatitude(double latitude) {
            this.latitude = latitude;
        }
    
        public double getLongitude() {
            return longitude;
        }
    
        public void setLongitude(double longitude) {
            this.longitude = longitude;
        }
    
        public String getOrg() {
            return org;
        }
    
        public void setOrg(String org) {
            this.org = org;
        }
    
        public String getQuery() {
            return query;
        }
    
        public void setQuery(String query) {
            this.query = query;
        }
    
        public String getRegion() {
            return region;
        }
    
        public void setRegion(String region) {
            this.region = region;
        }
    
        public String getRegionName() {
            return regionName;
        }
    
        public void setRegionName(String regionName) {
            this.regionName = regionName;
        }
    
    
        public String getTimezone() {
            return timezone;
        }
    
        public void setTimezone(String timezone) {
            this.timezone = timezone;
        }
    }
    
    0 讨论(0)
  • 2021-02-04 05:59

    There are several web-services, which provides you latitude and longitude value from IP address.

    one such is api.ipinfodb.com

    for ex, you can latitude and longitude by sending request like

     http://api.ipinfodb.com/v3/ip-city/?key=<your_api_key>
                   &ip=74.125.45.100&format=json
    

    this returns the data in json format and you can get response in XML by setting format=xml.(you need to register to get your API key).

    or you can download database from this and this link.

    you can download datasets but u have to constantly update it.

    0 讨论(0)
提交回复
热议问题