java - 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
包含在我的清单中。
这是我获取坐标的参考:链接
解决方案
推荐阅读
- html - 在 Shiny 中垂直对齐图像
- python - AttributeError:“StreamingBody”对象没有属性“startswith”
- amazon-web-services - 将约 200.000 个 s3 文件复制到新前缀
- javascript - fetch() 未捕获自定义错误消息
- python - 如何制作时间间隔不均匀的折线图?在 FacetGrid 函数中
- javascript - 如何制作图像滑块的想法
- types - 为什么 Unsigned 特征不会自动给出 Rust 中的 One 特征?
- java - Spring Boot 2.5/Spring Data Rest 3.5 在创建/修补资源时导致 NPE
- visual-studio-code - 带引号的 Stange bux
- android - 使用 FirebaseStored 下载 SVG 数据图像