我一直在使用Google Maps / Google Directions API。有没有人知道我如何能够找到沿着路线的中点,而不是地理中点。
理想情况下,我想找到此中点的纬度和长值。
有什么想法?我有点难过,希望我能找到一个建议而不会发疯,试图找到自己的答案。
答案 0 :(得分:0)
您可以使用Gisgraphy中的GetPointAtDistance原型。原型沿折线返回指定距离的LatLng。以下代码:
var polyline = new google.maps.Polyline({
path: [ new google.maps.LatLng(..., ...),
new google.maps.LatLng(..., ...),
... ];
}), //1.
midDistanceLength = polyline.getPath().getLength() / 2, //2.
midDistanceLatLng = polyline.GetPointAtDistance(midDistanceLength),//3.
midDistanceLat = midDistanceLatLng.lat(), //4.
midDistanceLng = midDistanceLatLng.lng(); //4.
//The prototype from Gisgraphy:
google.maps.Polygon.prototype.GetPointAtDistance = function(metres) {
// some awkward special cases
if (metres == 0) return this.getPath().getAt(0);
if (metres < 0) return null;
if (this.getPath().getLength() < 2) return null;
var dist=0;
var olddist=0;
for (var i=1; (i < this.getPath().getLength() && dist < metres); i++) {
olddist = dist;
dist += google.maps.geometry.spherical.computeDistanceBetween (
this.getPath().getAt(i),
this.getPath().getAt(i-1)
);
}
if (dist < metres) return null;
var p1= this.getPath().getAt(i-2);
var p2= this.getPath().getAt(i-1);
var m = (metres-olddist)/(dist-olddist);
return new google.maps.LatLng( p1.lat() + (p2.lat()-p1.lat())*m, p1.lng() + (p2.lng()-p1.lng())*m);
}
google.maps.Polyline.prototype.GetPointAtDistance = google.maps.Polygon.prototype.GetPointAtDistance;
答案 1 :(得分:0)
最简单的方法是你可以先:
1)使用GMSGeometryDistance计算路径的总距离,方法是通过GMSGeometryDistance函数计算每两个后续点之间的距离,然后对所有距离求和。
2)然后再次计算,并在每一步中求和。当总和大约是总距离的一半时,那么你处于中间点。 示例代码如下:
func findTotalDistanceOfPath(path: GMSPath) -> Double {
let numberOfCoords = path.count()
var totalDistance = 0.0
if numberOfCoords > 1 {
var index = 0 as UInt
while index < numberOfCoords{
//1.1 cal the next distance
var currentCoord = path.coordinateAtIndex(index)
var nextCoord = path.coordinateAtIndex(index + 1)
var newDistance = GMSGeometryDistance(currentCoord, nextCoord)
totalDistance = totalDistance + newDistance
index = index + 1
}
}
return totalDistance
}
func findMiddlePointInPath(path: GMSPath ,totalDistance distance:Double) -> CLLocationCoordinate2D? {
let numberOfCoords = path.count()
let halfDistance = distance/2
let threadhold = 10 //10 meters
var midDistance = 0.0
if numberOfCoords > 1 {
var index = 0 as UInt
while index < numberOfCoords{
//1.1 cal the next distance
var currentCoord = path.coordinateAtIndex(index)
var nextCoord = path.coordinateAtIndex(index + 1)
var newDistance = GMSGeometryDistance(currentCoord, nextCoord)
midDistance = midDistance + newDistance
if fabs(midDistance - halfDistance) < threadhold { //Found the middle point in route
return nextCoord
}
index = index + 1
}
}
return nil //Return nil if we cannot find middle point in path for some reason
}
还有更多优化功能。我在here
中写了一篇关于Swift的详细答案