【问题标题】:Google Maps: Attaching events on polyline icons谷歌地图:在折线图标上附加事件
【发布时间】:2013-02-12 01:15:53
【问题描述】:
我有一个页面,我试图在地图上模拟船舶位置。其中一些船位于折线上的某个位置,而另一些则位于单点标记处。
对于沿折线的百分比的船只,我能够正确显示图标。我想做的是将事件完全附加在该图标上,而不是整个多段线上。
我的代码在
http://www.cleancruising.com.au/map_allShipLoc2.asp
我也尝试过使用 google.maps.geometry.spherical.computeDistanceBetween 来计算船舶位置的 LatLng,但由于它使用球面几何,因此这些点无法在平面地图上正确转换。
【问题讨论】:
标签:
javascript
google-maps-api-3
google-maps-markers
【解决方案1】:
要计算船舶位置的 LatLng,请参阅 this thread from the Google Maps API v3 group 和 example in it
下面是从Mike Williams' (v2) epoly library修改的GetPointAtDistance函数
// === A method which returns a GLatLng of a point a given distance along the path ===
// === Returns null if the path is shorter than the specified distance ===
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 += this.getPath().getAt(i).distanceFrom(this.getPath().getAt(i-1));
}
if (dist < metres) {return null;}
var projection = this.getMap().getProjection();
if (!projection) {
alert("no projection");
return;
}
// Project
var p1= projection.fromLatLngToPoint(this.getPath().getAt(i-2));
var p2= projection.fromLatLngToPoint(this.getPath().getAt(i-1));
var m = (metres-olddist)/(dist-olddist);
// alert("p1="+p1+" p2="+p2+" m="+m);
// Unproject
return projection.fromPointToLatLng(new google.maps.Point( p1.x + (p2.x-p1.x)*m, p1.y + (p2.y-p1.y)*m));
}