【问题标题】:How to convert lat lng to a Location variable?如何将 lat lng 转换为 Location 变量?
【发布时间】:2015-06-28 11:12:31
【问题描述】:

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

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

float distance = myLocation.distanceTo(temp);

问题是我拥有的“临时”不是“位置”,它是 2 个不同的双打。

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

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

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

问题:

空指针访问:变量temp在这个位置只能为空

【问题讨论】:

    标签: android google-maps-android-api-2


    【解决方案1】:

    您必须先实例化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
    })
    

    【讨论】:

    • 大声笑,这是一个 Kotlin > Java 插图。
    【解决方案2】:

    或者,您可以使用静态方法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[0] 中。如果结果的长度为 2 或更大,初始方位存储在 results1 中。如果结果 长度为 3 或更大,最终方位存储在 results[2] 中。

    参数

    startLatitude起始纬度

    startLongitude起始经度

    endLatitude结束纬度

    endLongitude结束经度

    results一个浮点数组来保存结果

    【讨论】:

    • 这个方法很有趣,也很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2019-10-10
    • 2023-04-07
    相关资源
    最近更新 更多