繁体   English   中英

如何使用IP地址确定Android设备的位置

[英]How to determine location of device in Android using IP address

我正在开发一款Android应用。 我想使用其IP地址确定设备的位置。 我从哪里开始? Google API上的链接不够完善。 谢谢。

您应该使用fallowing API来获取使用ip的位置。

Ip2Location API

结帐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的用户:

每天2,500次免费查询每位用户每秒10次查询启用“按需付费”结算以解锁更高的配额:

$ 0.50美元/ 1000个额外查询,每天最多100,000个。

更多

有几种Web服务,可以从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密钥)。

或者你可以从数据库中下载这个这个链接。

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

我用来获取ip,国家和城市的设备

测试你可以使用RESTCLIENT ,firefox插件来发出HTTP请求。

只需复制https://addons.mozilla.org/en-us/firefox/addon/restclient/此URL并在RESTCLIENT中测试或刚刚在浏览器地址栏中测试

希望这可以帮助!

你可以使用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
}

我们可以通过简单的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

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;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM