Google Map API: How to center dynamicly markers in AS3? - actionscript-3

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?

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.

Related

Java 2D Polygon outside another

I'd like to know if there is a java way to, given a polygon, draw another one at a given distance and with the same center.
I tried AffineTransform but don't really know how it Works.
Thank you.
You need to translate your polygon by half its centroid width and height. I have included the code that comes from http://paulbourke.net/geometry/polygonmesh/PolygonUtilities.java to calculate the centroid of a polygon.
public void drawPolygon(){
Graphics2D g2 = bufferedImage.createGraphics();
Polygon poly=new Polygon();
poly.addPoint(100, 100);
poly.addPoint(200, 100);
poly.addPoint(200, 200);
poly.addPoint(150, 250);
poly.addPoint(100, 200);
poly.addPoint(100, 100);
g2.setColor(Color.blue);
g2.fillPolygon(poly);
g2.setColor(Color.red);
Point2D.Double []pts=new Point2D.Double[poly.npoints];
for (int i=0;i<poly.npoints;i++){
pts[i]=new Point2D.Double(poly.xpoints[i],poly.ypoints[i]);
}
Point2D centroid=centerOfMass(pts);
g2.translate(-centroid.getX(), -centroid.getY());
g2.scale(2, 2);
g2.drawPolygon(poly);
}
public static double area(Point2D[] polyPoints) {
int i, j, n = polyPoints.length;
double area = 0;
for (i = 0; i < n; i++) {
j = (i + 1) % n;
area += polyPoints[i].getX() * polyPoints[j].getY();
area -= polyPoints[j].getX() * polyPoints[i].getY();
}
area /= 2.0;
return (area);
}
/**
* Function to calculate the center of mass for a given polygon, according
* to the algorithm defined at
* http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/
*
* #param polyPoints
* array of points in the polygon
* #return point that is the center of mass
*/
public static Point2D centerOfMass(Point2D[] polyPoints) {
double cx = 0, cy = 0;
double area = area(polyPoints);
// could change this to Point2D.Float if you want to use less memory
Point2D res = new Point2D.Double();
int i, j, n = polyPoints.length;
double factor = 0;
for (i = 0; i < n; i++) {
j = (i + 1) % n;
factor = (polyPoints[i].getX() * polyPoints[j].getY()
- polyPoints[j].getX() * polyPoints[i].getY());
cx += (polyPoints[i].getX() + polyPoints[j].getX()) * factor;
cy += (polyPoints[i].getY() + polyPoints[j].getY()) * factor;
}
area *= 6.0f;
factor = 1 / area;
cx *= factor;
cy *= factor;
res.setLocation(cx, cy);
return res;
}
Another way of doing this, common in the GIS world, is to buffer a polygon. There is a library called Java Topology Suite that will provide this functionality, although it might be harder to figure out what the scale factor is.
There are some very interesting discussions about polygon growing in this post: An algorithm for inflating/deflating (offsetting, buffering) polygons

What is an elegant way to position 8 circles around a point

var circles:Array = new Array();
for(var i:int = 0; i < 8; i++)
{
var ball:Ball = new Ball();
ball.x = ???
ball.y = ???
circles.push(ball);
}
What is the best way to position balls around some point lets say in 5-10 distance of each other, is there some formula?
for(var i:int = 0; i < 8; i++)
{
var ball:Ball = new Ball();
// Point has a useful static function for this, it takes two parameters
// First, length, in other words how far from the center we want to be
// Second, it wants the angle in radians, a complete circle is 2 * Math.PI
// So, we're multiplying that with (i / 8) to place them equally far apart
var pos:Point = Point.polar(50, (i / 8) * Math.PI * 2);
// Finally, set the position of the ball
ball.x = pos.x;
ball.y = pos.y;
circles.push(ball);
}
I don't know actionscript3, so this exact code will not work, but it should give you a basic idea
for(int c = 0; c < 8; c++)
{
Ball ball;
ball.x = point.x;
ball.y = point.y;
ball.x += sin(toRadians((c/8) * 360));
ball.y += cos(toRadians((c/8) * 360));
circles.add(ball);
}
If you don't know what "sin" and "cos" do, or what "toRadians" means, just Google something like: "Sine Cosine Trigonometry". You'll find plenty of tutorials.
Here, I found this. It will teach you what "sin", "cos" and "radians" mean.
http://www.khanacademy.org/math/trigonometry
Obviously you could just stick with grapefrukt's answer, it works, but if you want to know what's really going on behind the hood in "Point.polar", check out those videos.

AS3 which item in an array has the lower value?

I’m trying to make a game like tower defence in AS3 and currently cant find solution to check which item in an array has the lower value of distance between enemy and turret, in order to choose which enemy to attack first.
I'm really stuck with this problem and asking for your help.
Here is a short code:
var enemyArray:Array = new Array();
var turretArray:Array = new Array();
addEventListener(Event.EnterFrame, loop);
// adding enemies
for(var i:int=0; i<3; i++){
var enemy:Enemy = new Enemy();
...
...
enemyArray.push(enemy);
addChild(enemy);
}
// adding turret
for(var t:int=0; t<2; t++){
var turret:Turret = new Turret();
...
...
turret.destinationX = 0;
turret.destinationY = 0;
turret.distance = 0;
turretArray.push(turret);
addChild(turret);
}
// loop
function loop(event:Event):void{
for(var j:int=enemyArray.length-1; j>=0; j--){
for(var k:int=turretArray.length-1; k>=0; k--){
// getting destination
turretArray[k].destinationX = turretArray[k].x - enemyArray[j].x;
turretArray[k].destinationY = turretArray[k].y - enemyArray[j].y;
// getting distance between turret and enemy
turretArray[k].distance = Math.sqrt(turretArray[k].destinationX*turretArray[k].destinationX+turretArray[k].destinationY*turretArray[k].destinationY);
// here i need to get min value from all turrets distance
}
}
}
Looks like you just need to be keeping track of the lowest value you've found as you go rather than overwriting it every time (if I've understood your code, correctly).
// loop
function loop(event:Event):void{
for(var k:int=turretArray.length-1; k>=0; k--)
{
turretArray[k].distance = -1;
for(var j:int=enemyArray.length-1; j>=0; j--)
{
var dx = turretArray[k].x - enemyArray[j].x;
var dy = turretArray[k].y - enemyArray[j].y;
var dist = Math.sqrt(dx * dx + dy * dy);
if(dist < turretArray[k].distance || turretArray[k].distance < 0)
{
turretArray[k].distance = dist;
turretArray[k].destinationX = dx;
turretArray[k].destinationY = dy;
}
}
}
}
Here, we store the initial distance value found in turretArray[k].distance, and only overwrite that if we find a lower one. We set it to -1 each time so we can tell if it's been set, yet, or not.
This is the equation you want:
http://www.mathopenref.com/coorddist.html
sqrt( (turret1X - turret2x)^2 + (turret1Y - turret2Y)^2 )

trying to get the cente lat/lon of a polygon

I am trying to populate a var "polyCenter" with the latlon for the center of a polygon and its driving me insane..
var paths = MapToolbar.features["shapeTab"]["shape_1"].getPath();
var i;
for (i = 0; i < paths.length; i++) {
bounds.extend(paths[i]);
}
polyCenter = bounds.getCenter();
alert(polyCenter);
It keeps returning (0,-180) for some reason..
Mathematically an irregular polygon does not have a center. They do however have a centroid (center of gravity) that is usually the approximate center.
Here is the equation to calculate the centroid of a polygon:
The equation in JavaScript:
function GetCentroid(paths){
var f;
var x = 0;
var y = 0;
var nPts = paths.length;
var j = nPts-1;
var area = 0;
for (var i = 0; i < nPts; j=i++) {
var pt1 = paths[i];
var pt2 = paths[j];
f = pt1.lat() * pt2.lng() - pt2.lat() * pt1.lng();
x += (pt1.lat() + pt2.lat()) * f;
y += (pt1.lng() + pt2.lng()) * f;
area += pt1.lat() * pt2.lng();
area -= pt1.lng() * pt2.lat();
}
area /= 2;
f = area * 6;
return new google.maps.LatLng(x/f, y/f);
}
Here is an updated fiddle based on #Argiropoulos answer.
Take a look at an example although this is not the center of a polygon except if it's a rectangle

Algorithm to solve the points of a evenly-distributed / even-gaps spiral?

First, just to give a visual idea of what I'm after, here's the closest result (yet not exactly what I'm after) image that I've found:
Here's the entire site-reference: http://www.mathematische-basteleien.de/spiral.htm
BUT, it doesn't exactly solve the problem I'm after. I would like to store an array of points of a very specific spiral algorithm.
The points are evenly distributed
The 360 degree cycles have an even gap
If I'm not mistaken, the first two points would be:
point[ 0 ] = new Point(0,0);
point[ 1 ] = new Point(1,0);
But where to go from here?
The only arguments I'd like to provide are:
the quantity of points I wish to resolve (length of array).
the distance between each points (pixels gap).
the distance between cycles.
It almost sounds, to me, that I have to calculate the "spiral-circumference" (if there's such a term) in order to plot the evenly distributed points along the spiral.
Can 2*PI*radius be reliably used for this calculation you think?
If it's been done before, please show some code example!
Fun little problem :)
If you look at the diagram closer, the sequence is clearly stated:
There are probably many solutions to drawing these, maybe more elegant, but here's mine:
You know the hypotenuse is square root of the current segment count+1
and the opposite side of the triangle is always 1.
Also you know that Sine(Math.sin) of the angle is equal to the opposite side divided by the hypotenuse.
from the old mnenonic SOH(Sine,Opposite,Hypotenuse),-CAH-TOA.
Math.sin(angle) = opp/hyp
You know the value of the sine for the angle, you know the two sides, but you don't know the angle yet, but you can use the arc sine function(Math.asin) for that
angle = Math.asin(opp/hyp)
Now you know the angle for each segment, and notice it increments with each line.
Now that you have an angle and a radius(the hypotenuse) you can use for polar to cartesian formula to convert that angle,radius pair to a x,y pair.
x = Math.cos(angle) * radius;
y = Math.sin(angle) * radius;
Since you asked for an actionscript solution, there Point class already provides this function for you through the polar() method. You pass it a radius and angle and it returns your x and y in a Point object.
Here's a little snippet which plots the spiral. You can control the number of segments by moving the mouse on the Y axis.
var sw:Number = stage.stageWidth,sh:Number = stage.stageHeight;
this.addEventListener(Event.ENTER_FRAME,update);
function update(event:Event):void{
drawTheodorus(144*(mouseY/sh),sw*.5,sh*.5,20);
}
//draw points
function drawTheodorus(segments:int,x:Number,y:Number,scale:Number):void{
graphics.clear();
var points:Array = getTheodorus(segments,scale);
for(var i:int = 0 ; i < segments; i++){
points[i].offset(x,y);
graphics.lineStyle(1,0x990000,1.05-(.05+i/segments));
graphics.moveTo(x,y);//move to centre
graphics.lineTo(points[i].x,points[i].y);//draw hypotenuse
graphics.lineStyle(1+(i*(i/segments)*.05),0,(.05+i/segments));
if(i > 0) graphics.lineTo(points[i-1].x,points[i-1].y);//draw opposite
}
}
//calculate points
function getTheodorus(segments:int = 1,scale:Number = 10):Array{
var result = [];
var radius:Number = 0;
var angle:Number = 0;
for(var i:int = 0 ; i < segments ; i++){
radius = Math.sqrt(i+1);
angle += Math.asin(1/radius);//sin(angle) = opposite/hypothenuse => used asin to get angle
result[i] = Point.polar(radius*scale,angle);//same as new Point(Math.cos(angle)*radius.scale,Math.sin(angle)*radius.scale)
}
return result;
}
This could've been written in less lines, but I wanted to split this into two functions:
one that deals only with computing the numbers, and the other which deals with drawing the lines.
Here are some screenshots:
For fun I added a version of this using ProcessingJS here.
Runs a bit slow, so I would recommend Chromium/Chrome for this.
Now you can actually run this code right here (move the mouse up and down):
var totalSegments = 850,hw = 320,hh = 240,segments;
var len = 10;
points = [];
function setup(){
createCanvas(640,480);
smooth();
colorMode(HSB,255,100,100);
stroke(0);
noFill();
//println("move cursor vertically");
}
function draw(){
background(0);
translate(hw,hh);
segments = floor(totalSegments*(mouseY/height));
points = getTheodorus(segments,len);
for(var i = 0 ; i < segments ; i++){
strokeWeight(1);
stroke(255-((i/segments) * 255),100,100,260-((i/segments) * 255));
line(0,0,points[i].x,points[i].y);
// strokeWeight(1+(i*(i/segments)*.01));
strokeWeight(2);
stroke(0,0,100,(20+i/segments));
if(i > 0) line(points[i].x,points[i].y,points[i-1].x,points[i-1].y);
}
}
function getTheodorus(segments,len){
var result = [];
var radius = 0;
var angle = 0;
for(var i = 0 ; i < segments ; i++){
radius = sqrt(i+1);
angle += asin(1/radius);
result[i] = new p5.Vector(cos(angle) * radius*len,sin(angle) * radius*len);
}
return result;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.4/p5.min.js"></script>
George's answer was excellent! I was looking for the solution for quite a while.
Here's the same code adjusted for PHP, in case it helps someone. I use the script to draw dots (= cities) for a map with X, Y coordinates. X starts from left, Y starts from bottom left.
<?
/**
* Initialize variables
**/
// MAXIMUM width & height of canvas (X: 0->400, Y: 0->400)
$width = 400;
// For loop iteration amount, adjust this manually
$segments = 10000;
// Scale for radius
$radiusScale = 2;
// Draw dot (e.g. a city in a game) for every N'th drawn point
$cityForEveryNthDot = 14;
/**
* Private variables
**/
$radius = 0;
$angle = 0;
$centerPoint = $width/2;
/**
* Container print
**/
print("<div style=\"width: ${width}px; height: ${width}px; background: #cdcdcd; z-index: 1; position: absolute; left: 0; top: 0;\"></div>");
/**
* Looper
**/
for($i=0;$i<$segments;$i++) {
// calculate radius and angle
$radius = sqrt($i+1) * $radiusScale;
$angle += asin(1/$radius);
// skip this point, if city won't be created here
if($i % $cityForEveryNthDot != 0) {
continue;
}
// calculate X & Y (from top left) for this point
$x = cos($angle) * $radius;
$y = sin($angle) * $radius;
// print dot
print("<div style=\"width: 1px; height: 1px; background: black; position: absolute; z-index: 2; left: " . round($x+$centerPoint) . "; top: " . round($y+$centerPoint) . ";\"></div>");
// calculate rounded X & Y (from bottom left)
$xNew = round($x+$centerPoint);
$yNew = round($width - ($y+$centerPoint));
// just some internal checks
if($xNew > 1 && $yNew > 1 && $xNew < $width && $yNew < $width) {
/**
* do something (e.g. store to database). Use xNew and yNew
**/
}
}