我在尝试找到阵列的最小距离时遇到了一些问题。我得到了一个从Servlet中检索到的距离列表,然后我遍历它以找到最小值。这是代码:
function getAllTaxiLoc(){
var taxiIcon = [];
var minDist = 0;
var minDistPlate = "";
$.ajax({
url: "/TrackNYP/TrackNYPServlet?action=GetAllTaxiLoc",
type: "GET",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (i, jsondata) {
var taxiPlate = jsondata.taxiPlate;
var taxiLocX = jsondata.taxiLocX;
var taxiLocY = jsondata.taxiLocY;
// Calculating to determine if the taxi location is within buffer radius
var xs = 0;
var ys = 0;
xs = taxiLocX - 29770.742075;
xs = xs * xs;
ys = taxiLocY - 40062.99945;
ys = ys * ys;
var distance = Math.sqrt( xs + ys );
if(distance < 800){
//Plot marker onto map
if(minDist > distance){
minDist = distance;
minDistPlate = taxiPlate;
}
}
console.log(minDist + "DIST");
console.log(minDistPlate + "PLATE");
});
},
error: function (request, state, errors) {
}
});
}
从这些代码中,我打印出的minDist和minDistPlate为0并为空。有任何想法吗?提前谢谢。
答案 0 :(得分:1)
您已在代码的开头设置minDist = 0
。如果将其与实际距离进行比较,则0将始终为最小距离。换句话说,if(minDist > distance)
将永远不会返回true。您需要设置minDist = 999999
或大于预期最小距离的数字。