如何通过IP地址在Android设备中确定位置

15

我正在开发一个安卓应用程序。我想使用设备的IP地址确定设备的位置。我该从哪里开始?Google APIs上的链接不够明确。谢谢。

6个回答

6
我们可以通过简单的API调用获取位置,但是它的精度很低。
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(位置API服务)
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;
    }
}

你说“但它的准确率会很低”是什么意思? - Dyno Cris
位置不会很精确。它可能会返回离您几英里远的位置数据。 - Levon Petrosyan
在我的情况下,我需要找出国家,这是基于IP地址的,所以我认为在这种情况下国家将被确定得相当准确,对吧? - Dyno Cris
我认为是的,是这样。 - Levon Petrosyan

4

请查看Google Maps Geolocation API

示例POST:

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

响应示例:

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

限制:

标准API用户:

每天免费查询2500次

每用户每秒10个查询 启用按需计费以解锁更高配额:

$0.50美元/每1000次附加查询,每天最高可达100,000次。

了解更多


2

有几个网络服务可以根据IP地址提供您的纬度和经度值。

其中之一是api.ipinfodb.com

例如,您可以通过发送请求来获取纬度和经度

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

此功能以JSON格式返回数据,您可以通过设置format=xml来获得XML响应。(您需要注册以获取API密钥)。

或者您可以从链接下载数据库。

您可以下载数据集,但必须不断更新它。


我已经尝试获取此网站的API密钥,但未成功。即使我已经提供了位置信息,它仍然要求我的位置。你愿意分享你的密钥吗? - mungaih pk

1
使用 IP 地址获取位置详细信息。
https://geolocation-db.com/json/your_ip_address

限制:每个IP地址每分钟最多发出45个请求

文档https://ip-api.com/docs/api:json


1
你可以使用freegeoip.net。这是一个免费、开源的服务。你可以直接使用该服务或在个人服务器上运行它。它也可以很容易地部署到Heroku上。要获取IP地址位置,只需使用OkHttp发送http/https请求即可。
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());
            }
        });
    }
});

响应看起来会像这样:

{
    "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
}

1

请回答,这个URL有限制吗?谢谢。 - Dyno Cris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接