我的解决方案是从各种来源进行几个级别的调整。我喜欢上面的链接,它指向我填充点,但最后,它并没有达到我希望的准确性。记得很久以前的数学课,我知道有可能找到这个。最后,这个脚本循环遍历路径中的点,然后计算它们之间最接近用户点击的点。
效率低下是每次都必须遍历整个点集。不幸的是,我只是不知道更好的方法,因为多点的路径可以向任何方向移动,直到集合结束才知道你是否找到了最近的点路径。这样做的美妙之处在于它将获得路径中绝对最近的点,而不会捕捉到任何东西。
这里的第一个参数是标记点。这是一个 lat/lng 对。第二个是路径中的 lat/lng 点数组。它返回的是最接近您的个人点的路径上的纬度/经度。如果您愿意,可以对其进行大量修改以报告更多信息,但出于我的目的,这正是我想要的。
function find_closest_point_on_path(marker_pt,path_pts){
var lowest = 9999999999999999;
var theLat = 0;
var theLng = 0;
$.each(path_pts,function(key, path_pt){
if(typeof path_pts[key+1] != "undefined"){
var test = point_to_line_segment_distance(path_pt.lat(),path_pt.lng(), path_pts[key+1].lat(),path_pts[key+1].lng(), marker_pt.lat(),marker_pt.lng());
if(test[0] < lowest){
lowest = test[0];
theLat = test[1];
theLng = test[2];
}
}
});
return new google.maps.LatLng(theLat, theLng);
}
function point_to_line_segment_distance(startX,startY, endX,endY, pointX,pointY) {
// Adapted from Philip Nicoletti's function, found here: http://www.codeguru.com/forum/printthread.php?t=194400
r_numerator = (pointX - startX) * (endX - startX) + (pointY - startY) * (endY - startY);
r_denominator = (endX - startX) * (endX - startX) + (endY - startY) * (endY - startY);
r = r_numerator / r_denominator;
px = startX + r * (endX - startX);
py = startY + r * (endY - startY);
s = ((startY-pointY) * (endX - startX) - (startX - pointX) * (endY - startY) ) / r_denominator;
distanceLine = Math.abs(s) * Math.sqrt(r_denominator);
closest_point_on_segment_X = px;
closest_point_on_segment_Y = py;
if ( (r >= 0) && (r <= 1) ) {
distanceSegment = distanceLine;
}
else {
dist1 = (pointX - startX) * (pointX - startX) + (pointY - startY) * (pointY - startY);
dist2 = (pointX - endX) * (pointX - endX) + (pointY - endY) * (pointY - endY);
if (dist1 < dist2) {
closest_point_on_segment_X = startX;
closest_point_on_segment_Y = startY;
distanceSegment = Math.sqrt(dist1);
}
else {
closest_point_on_segment_X = endX;
closest_point_on_segment_Y = endY;
distanceSegment = Math.sqrt(dist2);
}
}
return [distanceSegment, closest_point_on_segment_X, closest_point_on_segment_Y];
}