【问题标题】:How to get geolocation by ip in android?如何在android中通过ip获取地理位置?
【发布时间】:2017-05-19 02:32:02
【问题描述】:

谁知道是否存在任何 API 来获取使用公共 IP 的 android 设备的估计地理位置(纬度、经度)?

现在我可以通过以下方法获取 IP 地址:

private void getIPAddress(){
    URL url;
    BufferedReader bufferedReader=null;
    InputStreamReader in=null;
    HttpURLConnection urlConnection = null;
    try {
        url = new URL("http://ip2country.sourceforge.net/ip2c.php?format=JSON");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();
        in = new InputStreamReader(urlConnection.getInputStream());
        bufferedReader = new BufferedReader(in);
        String line;
        StringBuffer buffer = new StringBuffer(); 
        while((line = bufferedReader.readLine()) != null) {
              buffer.append(line);
              buffer.append('\r');
        }
        bufferedReader.close();
        in.close();
        JSONObject json_data = new JSONObject(buffer.toString());
        ip = json_data.getString("ip");
    } catch (Exception e) {
        e.printStackTrace();
    } 
    finally{
         try {
            bufferedReader.close();
            in.close();
        } catch (IOException e) {}

        if(urlConnection != null) {
            urlConnection.disconnect(); 
          }
    }
}

谢谢

【问题讨论】:

    标签: android geolocation ip


    【解决方案1】:

    您可以使用网络服务来请求您的 IP 位置。 This API 以 XML 格式返回 IP 地址的位置(国家、地区、城市、邮政编码、纬度、经度)和关联的时区。

    【讨论】:

      【解决方案2】:

      您可以使用此链接 (http://freegeoip.net/json/) 获取以下所有信息。提供的 ip 是您连接到的外部 ip 地址。

      JSON 格式:(但你可以选择你的格式)

      {
        "ip": "xx.xxx.xxx.xx",
        "country_code": "US",
        "country_name": "United States",
        "region_code": "XX",
        "region_name": "XXX XXXX",
        "city": "XXX XXXX",
        "zip_code": "10XXX",
        "time_zone": "America/New_York",
        "latitude": 4X.XXXX,
        "longitude": -7X.XXXX,
        "metro_code": 501
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-06-22
        • 1970-01-01
        • 2016-08-21
        • 1970-01-01
        • 2014-02-13
        • 2013-11-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多