距离比较器

根据传进来的初始点和其他经过点的集合,计算出初始点经过那些途经点的最佳路径。返回的就是初始点然后是途经点排好序的结果。

package com.nbomb.route.util;

import com.nbomb.route.domain.Village;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Component
public class Plan {


public class DistanceComparator implements Comparator<Village> {
    private Village origin;

    public DistanceComparator(Village origin) {
        this.origin = origin;
    }

    @Override
    public int compare(Village village1, Village village2) {
        double distance1 = calculateDistance(origin, village1);
        double distance2 = calculateDistance(origin, village2);
        return Double.compare(distance1, distance2);
    }

    private double calculateDistance(Village village1, Village village2) {
        double lat1 = Double.parseDouble(village1.getLatitude());
        double lon1 = Double.parseDouble(village1.getLongitude());
        double lat2 = Double.parseDouble(village2.getLatitude());
        double lon2 = Double.parseDouble(village2.getLongitude());

        double earthRadius = 6371; // Earth's radius in kilometers
        double dLat = Math.toRadians(lat2-lat1);
        double dLon = Math.toRadians(lon2-lon1);
        double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                        Math.sin(dLon/2) * Math.sin(dLon/2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
        double distance = earthRadius * c;

        return distance;
    }
}



    public List<Village> getPlan(List<Village> villages, Village startingPoint) {
        // 使用距离比较器对乡村列表进行排序
        Collections.sort(villages, new DistanceComparator(startingPoint));

        return villages;
    }
}

你可能感兴趣的:(java,开发语言,maven,spring,boot)