如何将经纬度转换为位置变量?

How to convert lat lng to a Location variable?

我正在android中制作一个地图应用程序,我想在地图上获取2个位置,并查看它们之间的距离。我已经将当前位置作为 "Location" 变量。然而,另一个地方被保存为两个变量:double lat,lng;

我上网查了一下,发现这个方法很有用:

float distance = myLocation.distanceTo(temp);

问题是我的 "temp" 不是 "Location",而是 2 个不同的双打。

有没有办法将它们转换为位置?

PS。我试过但没有用的代码:

Location temp = null;
temp.setLatitude(23.5678);
temp.setLongitude(34.456);
float distance = location.distanceTo(temp);

问题:

Null pointer access: The variable temp can only be null at this location

您必须实例化 Location,然后才能访问其成员。例如

Java

Location temp = new Location(LocationManager.GPS_PROVIDER);
temp.setLatitude(23.5678);
temp.setLongitude(34.456);
float distance = location.distanceTo(temp);


科特林

val distance = location.distanceTo(Location(LocationManager.GPS_PROVIDER).apply {
    latitude = 23.5678
    longitude = 34.456
})

或者,您可以使用静态方法 Location.distanceBetween().

在根本不实例化 Location 对象的情况下获取距离
float[] results = new float[1];
Location.distanceBetween(1, 2, 2 , 2, results);

public static void distanceBetween (double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)

The computed distance is stored in results[0]. If results has length 2 or greater, the initial bearing is stored in results1. If results has length 3 or greater, the final bearing is stored in results[2].

Parameters

startLatitude the starting latitude

startLongitude the starting longitude

endLatitude the ending latitude

endLongitude the ending longitude

results an array of floats to hold the results