views:

353

answers:

1

I have several markers on my map and want to center dynamily each time I click on a selected point which show a bunch of markers group.

Does anyone know how to do that in As3?

A: 

You could try to use the a formula to get the centroid of the polygon drawn by your markers, assuming it's a polygon. If not, and they're a bunch of scattered points, you need to get the ones on that form the outer bounding segments first.Also, the code assumes the polygon is closed(loops), so the last point is your first point again.

function centreOfMass(polyPoints:Array):Point{
 var cx:Number = 0;
 var cy:Number = 0;
 var area:Number = area(polyPoints);
 var result:Point = new Point();
 var i:Number,j:Number,n:Number = polyPoints.length;
 var factor:Number = 0;
 for(i = 0; i < n ; i++){
  j = (i+1) % n;
  factor = polyPoints[i].x * polyPoints[j].y - polyPoints[j].x * polyPoints[i].y;
  cx += polyPoints[i].x + polyPoints[j].x * factor;
  cy += polyPoints[i].y + polyPoints[j].y * factor;
 }
 area *= 6.0;
 factor = 1 / area;
 cx *= factor;
 cy *= factor;
 result.offset(cx,cy);//sets x and y to cx and cy
 return result;
}

function area(polyPoints:Array):Number{
 var i:int,j:int,n:int = polyPoints.length;
 var area:Number = 0;
 for(i = 0; i < n; i++){
  j = (i+1) % n;
  area += polyPoints[i].x * polyPoints[j].y;
  area -= polyPoints[j].x * polyPoints[i].y;
 }
 area *= 0.5;
 return area;
}

You create an array of points and you use the lat/lon coords as x,y coords. If you're using flash player 10, feel free to change the array into a Vector. and don't forget to do the import.flash.geom.Point.

I didn't come up with the code, I just ported what was on the amazing Paul Bourke website. Tons of handy stuff there.

George Profenza