我如何为附近的地方创建Java桌面应用程序

时间:2019-05-06 03:48:25

标签: java geolocation google-geolocation

我想创建一个Java桌面应用程序,该应用程序可以借助我的地理位置告诉我附近的地方。有两个问题:

  1. 我无法使用我的IP地址获得我的确切位置,并且我尝试了无法提供我确切位置的API。

  2. 我需要一个算法的帮助,该算法可以告诉我两个地理位置之间的距离。 有人可以帮忙吗?我认为我无法为附近的地方构建桌面应用程序。

我认为可以通过以下方式实现这一目标: 1.使用基于HTTP请求为我提供地理位置信息的API。 2.将javascript嵌入我的桌面应用程序中,因为很容易在我的应用程序中找到准确的地理位置。

尽管我要附加一个代码,借助API来确定地理位置。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.Charset;

import org.json.JSONException;
import org.json.JSONObject;

public class findLoc {


  private static String readAll(Reader rd) throws IOException {                       
    StringBuilder sb = new StringBuilder();                                          //Making a function READ ALL that reads all the string in file
    int cp;
    while ((cp = rd.read()) != -1) {
      sb.append((char) cp);
    }
    return sb.toString();
  }

  public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
    InputStream is = new URL(url).openStream();
    try {
      BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
      String jsonText = readAll(rd);                                                                            //Reading Json from url and doing it by function
      JSONObject json = new JSONObject(jsonText);
      return json;
    } finally {
      is.close();
    }
  }

  public static void main(String[] args) throws IOException, JSONException {                       //Main function
    JSONObject jsonIp = readJsonFromUrl("https://api.ipify.org?format=json");
    String ipAddress = (String) jsonIp.get("ip");
    System.out.println("Your public IP address : ");
    System.out.println(ipAddress);
    JSONObject json = readJsonFromUrl("http://ip-api.com/json/"+ipAddress);

//    System.out.println(json.toString());
    System.out.println();
    System.out.println("Your details :");
    System.out.println("map location:"+json.get("lat")+","+json.get("lon"));
    System.out.println("current location:"+json.get("city")+","+json.get("regionName"));
  }
}

如果有人可以帮助我解决这个问题,或者有关其他替代方法的建议,请

0 个答案:

没有答案
相关问题