根据其地理位置位置对数组进行排序

时间:2015-09-14 01:34:46

标签: java android eclipse sorting android-studio

我在自定义模型中有一个带lat和lng的数组。我想对数组进行排序,以便距离我的位置的最小距离位于顶部位置,依此类推。

这是我试过的

               myLocation = new Location("");

                myLocation.setLatitude(Double.valueOf(MyApplication.getInstance().getLatitude()));
                myLocation.setLongitude(Double.valueOf(MyApplication.getInstance().getLongitude()));
                Collections.sort(pings, new DistanceComparator());


private class DistanceComparator implements java.util.Comparator<PingModel>
    {
        @Override
        public int compare(PingModel lhs, PingModel rhs)
        {
            Location lhsLocation = new Location("");

            lhsLocation.setLatitude(Double.valueOf(lhs.latloc));
            lhsLocation.setLongitude(Double.valueOf(lhs.lngloc));

            Location rhsLocation = new Location("");

            rhsLocation.setLatitude(Double.valueOf(lhs.latloc));
            rhsLocation.setLongitude(Double.valueOf(lhs.lngloc));

            return (int)rhsLocation.distanceTo(myLocation) - (int)lhsLocation.distanceTo(myLocation);
        }
    }

结果不确定它正在做什么样的排序,但不是根据距离。

3 个答案:

答案 0 :(得分:0)

不确定这是否有帮助,但我正在开展类似的项目,并发现此链接非常有用:http://www.geodatasource.com/developers/java

基本上,如果你有位置;使用距离函数计算新位置 - 您的位置,然后根据此进行排序。循环遍历位置数组,并根据结果进行排序。

希望它有所帮助。

答案 1 :(得分:0)

你可以试试

吗?
class CustomView: UIView {

    var customLayers = [HogeProtocol]()

    func callTheFunctionAndAddSublayer() {

        for customLayer in customLayers {
            customLayer.aFunction() // can call
            layer.addSublayer(customLayer) // cannot call.. 
        }

    }
}

答案 2 :(得分:0)

在减法之前转换为int可能并不总是有效。例如,如果您的distanceTo()函数返回km并且距您的点和数据点的距离在1 km以内,则减法的结果可能为0.

而不是

return (int)rhsLocation.distanceTo(myLocation) - (int)lhsLocation.distanceTo(myLocation);

尝试

return (rhsLocation.distanceTo(myLocation) - lhsLocation.distanceTo(myLocation)) > 0 ? 1 : -1;
相关问题