查找最近的位置改进

时间:2016-10-25 18:17:39

标签: javascript algorithm geolocation distance

我找到了以下算法来找到给定位置的最近点:

function closestLocation(targetLocation, locationData) {
    function vectorDistance(dx, dy) {
        return Math.sqrt(dx * dx + dy * dy);
    }

    function locationDistance(location1, location2) {
        var dx = location1.lat - location2.lat,
            dy = location1.lng - location2.lng;

        return vectorDistance(dx, dy);
    }

    return locationData.reduce(function(prev, curr) {
        var prevDistance = locationDistance(targetLocation , prev),
            currDistance = locationDistance(targetLocation , curr);


          return (prevDistance < currDistance) ? prev : curr;  

    });
}

该算法效果很好,但现在我需要添加一个功能:epsilon

function closestLocation(targetLocation, locationData, epsilon) {
    function vectorDistance(dx, dy) {
        return Math.sqrt(dx * dx + dy * dy);
    }

    function locationDistance(location1, location2) {
        var dx = location1.lat - location2.lat,
            dy = location1.lng - location2.lng;

        return vectorDistance(dx, dy);
    }

    return locationData.reduce(function(prev, curr) {
        var prevDistance = locationDistance(targetLocation , prev),
            currDistance = locationDistance(targetLocation , curr);


          return (prevDistance < currDistance && Math.abs(prevDistance - currDistance) < epsilon) ? prev : curr;  

    });
}

我认为它会起作用,但事实并非如此。

我想仅在对象epsilon时才返回该对象。

编辑:

输入:

locationData = [{"lat":number, "lng":number, "title": "title"}, {"lat":number, "lng":number, "title": "title"}]

targetLocation = {"lat": number, "lng": number}

输出:

closest = {"lat":number, "lng":number, "title": "title"}

0 个答案:

没有答案