我一直在玩谷歌地图/ Google路线API。有没有人对我如何能够沿着路线而不是地理中点找到中点提出了一些看法。Google Maps API - 沿路线的中点
理想情况下,我想找到这个中点的纬度和长度值。
有什么想法?我有点难过,希望我能够找到一个建议,而不会疯狂地尝试自己找到答案。
我一直在玩谷歌地图/ Google路线API。有没有人对我如何能够沿着路线而不是地理中点找到中点提出了一些看法。Google Maps API - 沿路线的中点
理想情况下,我想找到这个中点的纬度和长度值。
有什么想法?我有点难过,希望我能够找到一个建议,而不会疯狂地尝试自己找到答案。
您可以使用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)使用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
}
还有更多的优化功能。我在Swift写了一个详细的答案here