首页 > 解决方案 > Android OpenStreetMap 坐标

问题描述

我有一个从 OpenStreetMap 获取坐标的类。当我从一个普通的 Java 类执行它时,它工作得很好:我在 android studio 中编写了一个测试类,然后执行它的 main 方法。

这是我的测试类,它可以工作并打印正确的结果:

public class openstreetmaptest {
    static String address2 = "Platz der Republik 1, 11011 Berlin";
    static String address1 = "Willy-Brandt-Straße 1, 10557 Berlin";
    public static void main(String[] args) {
        Location testL = new Location(address1);
        Location test2 = new Location(address2);
        System.out.println("distance: " + testL.distanceBetween(test2));
        System.out.println("lat 1: " + testL.getLat());
        System.out.println("lng 1: " + testL.getLng());
        System.out.println("lat 2: " + test2.getLat());
        System.out.println("lng 2: " + test2.getLng());
    }
}

Location 类的重要部分:

public double distanceBetween(Location x)   {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(x.getLat()-getLat());
    double dLng = Math.toRadians(x.getLng()-getLng());
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.cos(Math.toRadians(getLat())) * Math.cos(Math.toRadians(x.getLat())) *
                    Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    double dist = earthRadius * c;
    return dist;
}


private void calculateDegrees()  {
    Map<String, Double> coords;
    coords = OpenStreetMapUtils.getInstance().getCoordinates(address);
    lat = coords.get("lat");
    lng = coords.get("lon");
}

在我的 Android 项目中,我有一个扩展 AppCompatActivity 的类。用户按下按钮后,我从 UI 字段(地址信息)中获取他的输入字符串。有了这些,我正在创建一个 Location 对象。这里的坐标计算不再起作用。

它似乎在这里崩溃:

 private String getRequest(String url) throws Exception {

    final URL obj = new URL(url);
    final HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    con.setRequestMethod("GET");

    if (con.getResponseCode() != 200) {
        return null;
    }

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    return response.toString();
}

查看参考以查看对 OpenStreetMap 的请求的完整代码。

android.permission.INTERNET&android.permission.ACCESS_NETWORK_STATE包含在我的清单中。

这是我获取坐标的参考:链接

标签: javaandroidurlhttps

解决方案


推荐阅读