Converting X/ Y Circle Coordinates to functional Lat/ Lng - javascript

I wanted a random x/ y coordinate on the area of an intersection of two circles
My problem now is that i got the heavy part done, and it does work in the browser with Canvas for demonstration. But only on 2D Coordinates. Im using Google Maps, and i wanted to input two Circles with the Lat Lng positions and a radius. The result should have been the Lat/ Lang which i calculated on 2D.
But my mathematics end on real world coordinates..
so circle1.x and .y would be .lat and .lng for example.
/******************************************************************
Generate New Coord From Intersect
Generate random position point on cntersect area of two circles.
*******************************************************************/
var circle1 = {x : 0, y : 0, radius : 10};
var circle2 = {x : 0, y : 0, radius : 10};
var ctx;
var p2 = {x : 0, y : 0};
var p3 = {x : 0, y : 0};
var t3 = {x : 0, y : 0};
var t6 = {x : 0, y : 0};
var t7 = {x : 0, y : 0};
function GenerateNewCoordFromIntersect(circle1, circle2) {
var c = document.getElementById('canvasID');
c.width = 500;
c.height = 500;
ctx = c.getContext('2d');
drawCircle(circle1.x,circle1.y,circle1.radius,"red");
drawCircle(circle2.x,circle2.y,circle2.radius,"blue");
var distance = Math.sqrt(Math.pow(circle2.x-circle1.x,2) + Math.pow(circle2.y-circle1.y,2));
// then there are no solutions, the circles are separate.
if (distance > circle1.radius + circle2.radius ) {
return;
}
// then there are no solutions because one circle is contained within the other.
if (distance < circle1.radius - circle2.radius ) {
return;
}
// then the circles are coincident and there are an infinite number of solutions.
if (distance == 0 && circle1.radius == circle2.radius) {
return;
}
// random if take sector of circle 1 or 2
if (Math.random() > 0.5) {
var newcircle1 = JSON.parse(JSON.stringify(circle1));
var newcircle2 = JSON.parse(JSON.stringify(circle2));
circle1 = newcircle2;
circle2 = newcircle1;
}
// calc a
a = ((Math.pow(circle1.radius,2) - Math.pow(circle2.radius,2) + Math.pow(distance,2))) / (2 * distance);
// calc height
h = Math.sqrt(Math.pow(circle1.radius,2) - Math.pow(a,2));
// calc middle point of intersect
p2.x = circle1.x + a * (circle2.x - circle1.x) / distance;
p2.y = circle1.y + a * (circle2.y - circle1.y) / distance;
// calc upper radius intersect point
p3.x = p2.x + h * (circle2.y - circle1.y) / distance;
p3.y = p2.y - h * (circle2.x - circle1.x) / distance;
// random height for random point position
var randNumber = Math.random() / 2 + Math.random() * 0.5;
var radiusOfH = (h*2);
var randh = (randNumber) * radiusOfH - h;
// calc random Hypotenuse
var hypDistance = Math.abs(Math.sqrt(Math.pow(a,2) + Math.pow(randh,2)));
var randomHyp = (circle1.radius - hypDistance) + hypDistance;
// random point on line of middlepoint
t3.x = p2.x + ((randh) * (circle2.y - circle1.y)) / distance;
t3.y = p2.y - (randh) * (circle2.x - circle1.x) / distance;
// angle calc
var winkel = Math.atan(randh / a);
var newA = Math.cos(winkel) * randomHyp; //(randomHyp);
var newH = Math.sin(winkel) * randomHyp;//newA ;
t6.x = circle1.x + newA * (circle2.x - circle1.x) / distance;
t6.y = circle1.y + newA * (circle2.y - circle1.y) / distance;
t7.x = t6.x + newH * (circle2.y - circle1.y) / distance;
t7.y = t6.y - newH * (circle2.x - circle1.x) / distance;
randNumber = Math.random();
var xDist = (t7.x - t3.x) * (randNumber);
var yDist = (t7.y - t3.y) * (randNumber);
var rx = t3.x + xDist;
var ry = t3.y + yDist;
drawCircle(rx,ry,2,"blue");
}
function drawCircle(x, y, r, fill) {
ctx.beginPath();
ctx.arc(x,y,r,0,2*Math.PI);
ctx.strokeStyle = fill;
ctx.stroke();
}

You need to know the map projection that it's used to convert between lat/long coordinates to a x/y coordinates of a 2d plane.
You can find specific information for the Google Maps API here.

Related

Drawing parallel equidistant lines inside a circle

I'm trying to draw parallel equidistant lines inside a circle. I've got to the stage that if i connect points from their opposite angles on the circumference I get parallel lines... but they're not equidistant...
Here's some code:
var num_lines = 8;
var num_points = num_lines * 2;
var start_angle = 100;
var points = [];
var radius = 200;
ctx.strokeCircle(w/2, h/2, radius, radius); // shorthand for ctx.arc( x, y, 5, 0, Math.PI * 2, true );
for (var i = 0; i < num_points; i++) {
var angle = 360/num_points * i;
ctx.fillStyle = "red";
if (i %2 == 0 ) ctx.fillStyle = "blue";
var x = w/2 + Math.cos(angle) * radius/2;
var y = h/2 + Math.sin(angle) * radius/2;
ctx.circle(x, y, 10, 10); // shorthand for ctx.arc( x, y, 5, 0, Math.PI * 2, true );
points.push({x: x, y: y});
}
for (var i = 0; i < num_lines; i++) {
ctx.line(points[i].x, points[i].y, points[points.length-i-1].x, points[points.length-i-1].y)
}
Use Pythagoras' theorem.
The ...
y: vertical position of the line relative to the center
x: horizontal distance of its endpoints from the center
r: radius of the circle
... must satisfy y^2 + x^2 = r^2.
Code:
var radius = 200;
var num_lines = 8;
// vertical spacing
var delta_y = (2.0 * radius) / (num_lines + 1);
ctx.strokeCircle(w/2, h/2, radius, radius);
for (var i = 0; i < num_lines; i++)
{
// applying pythagoras
var y = delta_y * (i + 1) - radius / 2;
var x = Math.sqrt(radius * radius - y * y);
// calculating endpoints
var left_x = w / 2 - x;
var right_x = w / 2 + x;
var end_y = h / 2 + y;
ctx.fillStyle = (i % 2 == 0) ? "blue" : "red";
ctx.circle(left_x, end_y, 10, 10);
ctx.circle(right_x, end_y, 10, 10);
ctx.line(left_x, end_y, right_x, end_y);
}
EDIT: rotation
To rotate a vector by angle a clockwise:
x' = x * cos(a) + y * sin(a)
y' = y * cos(a) - x * sin(a)
Code:
var radius = 200;
var num_lines = 50;
var angle = 60;
// temporary variables
var delta_y = (2.0 * radius) / (num_lines);
var cos_a = Math.cos(angle * Math.PI / 180.0);
var sin_a = Math.sin(angle * Math.PI / 180.0);
ctx.strokeCircle(w / 2, h / 2, radius * 2, radius * 2);
for (var i = 0; i < num_lines; i++)
{
// applying pythagoras
var y = delta_y * i - radius;
var x = Math.sqrt(radius * radius - y * y);
// rotating the displacement vector
var left_x = y * sin_a + x * cos_a;
var right_x = y * sin_a - x * cos_a;
var left_y = y * cos_a - x * sin_a;
var right_y = y * cos_a + x * sin_a;
ctx.fillStyle = (i % 2 == 0) ? "blue" : "red";
ctx.line(w / 2 + left_x , h / 2 + left_y ,
w / 2 + right_x, h / 2 + right_y);
}
got it to work like so... wondering how I can rotate the lines at an angle (mathematically, not using ctx.translate and ctx.rotate ):
var radius = 200;
var num_lines = 50;
// vertical spacing
var delta_y = (2.0 * radius) / (num_lines);
ctx.strokeCircle(w/2, h/2, radius * 2, radius * 2);
for (var i = 0; i < num_lines; i++)
{
// applying pythagoras
var y = delta_y * (i) - radius;
var x = Math.sqrt(radius * radius - y * y);
// calculating endpoints
var left_x = w / 2 - x;
var right_x = w / 2 + x;
var end_y = h / 2 + y;
ctx.fillStyle = (i % 2 == 0) ? "blue" : "red";
ctx.line(left_x, end_y, right_x, end_y);
}

Canvas perpendicular points to line

I'm using Konva library to draw some stuff on HTML5 canvas.
I have given 2 points from user interaction by mouse click:
var A={x:'',y:''};
var B={x:'',y:''};
1) How to draw line line this?
My question is:
1) How to get perpendicular lines on each interval?
2) How to get distance from A to B point?
3) How to get all points on line from A to B?
4) How to get red points?
You have not explained what your line is so I am assuming it is a sin wave (though the image looks like circles stuck together???)
As MBo has given the basics this is just applying it to the wavy line.
// normalize a vector
function normalize(vec){
var length = Math.sqrt(vec.x * vec.x + vec.y * vec.y);
vec.x /= length;
vec.y /= length;
return vec;
}
// creates a wavy line
function wavyLine(start, end, waves, amplitude){
return ({
start,
end,
waves,
amplitude,
update(){
if(this.vec === undefined){
this.vec = {};
this.norm = {};
}
this.vec.x = this.end.x - this.start.x;
this.vec.y = this.end.y - this.start.y;
this.length = Math.sqrt(this.vec.x * this.vec.x + this.vec.y * this.vec.y);
this.norm.x = this.vec.x / this.length;
this.norm.y = this.vec.y / this.length;
return this;
}
}).update();
}
// draws a wavy line
function drawWavyLine(line) {
var x, stepSize, i, y, phase, dist;
ctx.beginPath();
stepSize = ctx.lineWidth;
ctx.moveTo(line.start.x, line.start.y);
for (i = stepSize; i < line.length; i+= stepSize) {
x = line.start.x + line.norm.x * i; // get point i pixels from start
y = line.start.y + line.norm.y * i; // get point i pixels from start
phase = (i / (line.length / line.waves)) * Math.PI * 2; // get the wave phase at this point
dist = Math.sin(phase) * line.amplitude; // get the distance from the line to the point on the wavy curve
x -= line.norm.y * dist;
y += line.norm.x * dist;
ctx.lineTo(x, y);
}
phase = line.waves * Math.PI * 2; // get the wave phase at this point
dist = Math.sin(phase) * line.amplitude; // get the distance from the line to the point on the wavy curve
ctx.lineTo(line.end.x - line.norm.y * dist, line.end.y + line.norm.x * dist);
ctx.stroke();
}
// find the closest point on a wavy line to a point returns the pos on the wave, tangent and point on the linear line
function closestPointOnLine(point,line){
var x = point.x - line.start.x;
var y = point.y - line.start.y;
// get the amount the line vec needs to be scaled so tat point is perpendicular to the line
var l = (line.vec.x * x + line.vec.y * y) / (line.length * line.length);
x = line.vec.x * l; // scale the vec
y = line.vec.y * l;
return pointAtDistance(Math.sqrt(x * x + y * y), line);
}
// find the point at (linear) distance along wavy line and return coordinate, coordinate on wave, and tangent
function pointAtDistance(distance,line){
var lenScale = line.length / line.waves; // scales the length into radians
var phase = distance * Math.PI * 2 / lenScale; // get the wave phase at this point
var dist = Math.sin(phase) * line.amplitude; // get the distance from the line to the point on the wavy curve
var slope = Math.cos(phase ) * Math.PI * 2 * line.amplitude / lenScale; // derivitive of sin(a*x) is -a*cos(a*x)
// transform tangent (slope) into a vector along the line. This vector is not a unit vector so normalize it
var tangent = normalize({
x : line.norm.x - line.norm.y * slope,
y : line.norm.y + line.norm.x * slope
});
// move from the line start to the point on the linear line at distance
var linear = {
x : line.start.x + line.norm.x * distance,
y : line.start.y + line.norm.y * distance
}
// move out perpendicular to the wavy part
return {
x : linear.x - line.norm.y * dist,
y : linear.y + line.norm.x * dist,
tangent,linear
};
}
// create a wavy line
var wLine = wavyLine({x:10,y:100},{x:300,y:100},3,50);
// draw the wavy line and show some points on it
function display(timer){
globalTime = timer;
ctx.setTransform(1,0,0,1,0,0); // reset transform
ctx.globalAlpha = 1; // reset alpha
ctx.clearRect(0,0,w,h);
var radius = Math.max(ch,cw);
// set up the wavy line
wLine.waves = Math.sin(timer / 10000) * 6;
wLine.start.x = Math.cos(timer / 50000) * radius + cw;
wLine.start.y = Math.sin(timer / 50000) * radius + ch;
wLine.end.x = -Math.cos(timer / 50000) * radius + cw;
wLine.end.y = -Math.sin(timer / 50000) * radius + ch ;
wLine.update();
// draw the linear line
ctx.lineWidth = 0.5;
ctx.strokeStyle = "blue";
ctx.beginPath();
ctx.moveTo(wLine.start.x, wLine.start.y);
ctx.lineTo(wLine.end.x, wLine.end.y);
ctx.stroke();
// draw the wavy line
ctx.lineWidth = 2;
ctx.strokeStyle = "black";
drawWavyLine(wLine);
// find point nearest mouse
var p = closestPointOnLine(mouse,wLine);
ctx.lineWidth = 1;
ctx.strokeStyle = "red";
ctx.beginPath();
ctx.arc(p.x,p.y,5,0,Math.PI * 2);
ctx.moveTo(p.x + p.tangent.x * 20,p.y + p.tangent.y * 20);
ctx.lineTo(p.x - p.tangent.y * 10,p.y + p.tangent.x * 10);
ctx.lineTo(p.x + p.tangent.y * 10,p.y - p.tangent.x * 10);
ctx.closePath();
ctx.stroke();
// find points at equal distance along line
ctx.lineWidth = 1;
ctx.strokeStyle = "blue";
ctx.beginPath();
for(var i = 0; i < w; i += w / 10){
var p = pointAtDistance(i,wLine);
ctx.moveTo(p.x + 5,p.y);
ctx.arc(p.x,p.y,5,0,Math.PI * 2);
ctx.moveTo(p.x,p.y);
ctx.lineTo(p.linear.x,p.linear.y);
ctx.moveTo(p.x + p.tangent.x * 40, p.y + p.tangent.y * 40);
ctx.lineTo(p.x - p.tangent.x * 40, p.y - p.tangent.y * 40);
}
ctx.stroke();
}
/******************************************************************************
The code from here down is generic full page mouse and canvas boiler plate
code. As I do many examples which all require the same mouse and canvas
functionality I have created this code to keep a consistent interface. The
Code may or may not be part of the answer.
This code may or may not have ES6 only sections so will require a transpiler
such as babel.js to run on legacy browsers.
*****************************************************************************/
// V2.0 ES6 version for Stackoverflow and Groover QuickRun
var w, h, cw, ch, canvas, ctx, mouse, globalTime = 0;
// You can declare onResize (Note the capital R) as a callback that is also
// called once at start up. Warning on first call canvas may not be at full
// size.
;(function(){
const RESIZE_DEBOUNCE_TIME = 100;
var resizeTimeoutHandle;
var firstRun = true;
function createCanvas () {
var c,cs;
cs = (c = document.createElement("canvas")).style;
cs.position = "absolute";
cs.top = cs.left = "0px";
cs.zIndex = 1000;
document.body.appendChild(c);
return c;
}
function resizeCanvas () {
if (canvas === undefined) { canvas = createCanvas() }
canvas.width = innerWidth;
canvas.height = innerHeight;
ctx = canvas.getContext("2d");
if (typeof setGlobals === "function") { setGlobals() }
if (typeof onResize === "function") {
clearTimeout(resizeTimeoutHandle);
if (firstRun) { onResize() }
else { resizeTimeoutHandle = setTimeout(onResize, RESIZE_DEBOUNCE_TIME) }
firstRun = false;
}
}
function setGlobals () {
cw = (w = canvas.width) / 2;
ch = (h = canvas.height) / 2;
}
mouse = (function () {
var m; // alias for mouse
var mouse = {
x : 0, y : 0, // mouse position and wheel
buttonRaw : 0,
buttonOnMasks : [0b1, 0b10, 0b100], // mouse button on masks
buttonOffMasks : [0b110, 0b101, 0b011], // mouse button off masks
bounds : null,
eventNames : "mousemove,mousedown,mouseup".split(","),
event(e) {
var t = e.type;
m.bounds = m.element.getBoundingClientRect();
m.x = e.pageX - m.bounds.left - scrollX;
m.y = e.pageY - m.bounds.top - scrollY;
if (t === "mousedown") { m.buttonRaw |= m.buttonOnMasks[e.which - 1] }
else if (t === "mouseup") { m.buttonRaw &= m.buttonOffMasks[e.which - 1] }
},
start(element) {
m.element = element === undefined ? document : element;
m.eventNames.forEach(name => document.addEventListener(name, mouse.event) );
},
}
m = mouse;
return mouse;
})();
function update(timer) { // Main update loop
globalTime = timer;
display(timer); // call demo code
requestAnimationFrame(update);
}
setTimeout(function(){
canvas = createCanvas();
mouse.start(canvas);
resizeCanvas();
window.addEventListener("resize", resizeCanvas);
requestAnimationFrame(update);
},0);
})();
We have points A and B. Difference vector
D.X = B.X - A.X
D.Y = B.Y - A.Y
Length = Sqrt(D.X * D.X + D.Y * D.Y)
normalized (unit) vector
uD.X = D.X / Length
uD.Y = D.Y / Length
perpendicular unit vector
P.X = - uD.Y
P.Y = uD.X
some red point:
R.X = A.X + uD.X * Dist + P.X * SideDist * SideSign
R.Y = A.Y + uD.Y * Dist + P.Y * SideDist * SideSign
where Dist is in range 0..Length
Dist = i / N * Length for N equidistant points
SideSign is +/- 1 for left and right side

How to get bezier curve size in HTML5 canvas with cp2 point?

I want to get the rendered size (width/height) of a bézier curve in HTML5 canvas
context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
with this code, for instance
// control points
var cp1x = 200,
cp1y = 150,
cp2x = 260,
cp2y = 10;
var x = 0,
y = 0;
// calculation
var curveWidth = cp1x > x ? cp1x - x : x - cp1x,
curveHeight = cp1y > y ? cp1y - y : y - cp1y;
However, the cp2 point can increase the curve distance (length, size). I.e., suppose cp2 point is the red point in this image and its x coordinate is bigger than cp1's x, which looks to be the end point of the bézier curve:
So, how can I consider the length of cp2 point in curveWidth and in curveHeight to be exact?
To get extent of a quadratic bezier
The points
var x1 = ? // start
var y1 = ?
var x2 = ? // control
var y2 = ?
var x3 = ? // end
var y3 = ?
The extent
extent = {
minx : null,
miny : null,
maxx : null,
maxy : null,
}
The Math.
These equation apply for the x and y axis (thus two equations)
For quadratic bezier
F(u) = a(1-u)^2+2b(1-u)u+cu^2
which is more familiar in the form of a quadratic equation
Ax^2 + Bx + C = 0
so the bezier rearranged
F(u) = (a-2b+c)u^2+2(-a+b)u+a
We need the derivative so that becomes
2(a-2b+c)u-2a+2b
simplify divide common factor 2 to give
(a-2b+c)u + b - a = 0
separate out u
b-a = (a-2b + c)u
(b-a) / (a - 2b + c) = u
Then algorithm optimised for the fact the (b-a) part of (a-2b-c)
function solveB2(a,b,c){
var ba = b-a;
return ba / (ba - (c-b)); // the position on the curve of the maxima
}
var ux = solveB2(x1,x2,x3);
var uy = solveB2(y1,y2,y3);
These two values are positions along the curve so we now just have to find the coordinates of these two points. We need a function that finds a point on a quadratic bezier
function findPoint(u,x1,y1,x2,y2,x3,y3){ // returns array with x, and y at u
var xx1 = x1 + (x2 - x1) * u;
var yy1 = y1 + (y2 - y1) * u;
var xx2 = x2 + (x3 - x2) * u;
var yy2 = y2 + (y3 - y2) * u;
return [
xx1 + (xx2 - xx1) * u,
yy1 + (yy2 - yy1) * u
]
}
First check that they are on the curve and find the point at ux,uy
if(ux >= 0 && ux <= 1){
var px = findPoint(ux,x1,y1,x2,y2,x3,y3);
}
if(uy >= 0 && uy <= 1){
var py = findPoint(uy,x1,y1,x2,y2,x3,y3);
}
Now test against the extent
extent.minx = Math.min(x1,x3,px[0],py[0]);
extent.miny = Math.min(y1,y3,px[1],py[1]);
extent.maxx = Math.max(x1,x3,px[0],py[0]);
extent.maxy = Math.max(y1,y3,px[1],py[1]);
And you are done
extent has the coordinates of the box around the bezier. Top left (min) and bottom right (max)
You can also get the minimum bounding box if you rotate the bezier so that the start and end points fall on the x axis. Then do the above and the resulting rectangle is the minimum sized rectangle that can be placed around the bezier.
Cubics are much the same but just a lot more typing.
And a demo, just to make sure I got it all correct.
var canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 400;
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
var x1,y1,x2,y2,x3,y3;
var ux,uy,px,py;
var extent = {
minx : null,
miny : null,
maxx : null,
maxy : null,
}
function solveB2(a,b,c){
var ba = b-a;
return ba / (ba - (c-b)); // the position on the curve of the maxima
}
function findPoint(u,x1,y1,x2,y2,x3,y3){ // returns array with x, and y at u
var xx1 = x1 + (x2 - x1) * u;
var yy1 = y1 + (y2 - y1) * u;
var xx2 = x2 + (x3 - x2) * u;
var yy2 = y2 + (y3 - y2) * u;
return [
xx1 + (xx2 - xx1) * u,
yy1 + (yy2 - yy1) * u
]
}
function update(time){
ctx.clearRect(0,0,800,400);
// create random bezier
x1 = Math.cos(time / 1000) * 300 + 400;
y1 = Math.sin(time / 2100) * 150 + 200;
x2 = Math.cos((time + 3000) / 1200) * 300 + 400;
y2 = Math.sin(time / 2300) * 150 + 200;
x3 = Math.cos(time / 1400) * 300 + 400;
y3 = Math.sin(time / 2500) * 150 + 200;
// solve for bounds
var ux = solveB2(x1,x2,x3);
var uy = solveB2(y1,y2,y3);
if(ux >= 0 && ux <= 1){
px = findPoint(ux,x1,y1,x2,y2,x3,y3);
}else{
px = [x1,y1]; // a bit of a cheat but saves having to put in extra conditions
}
if(uy >= 0 && uy <= 1){
py = findPoint(uy,x1,y1,x2,y2,x3,y3);
}else{
py = [x3,y3]; // a bit of a cheat but saves having to put in extra conditions
}
extent.minx = Math.min(x1,x3,px[0],py[0]);
extent.miny = Math.min(y1,y3,px[1],py[1]);
extent.maxx = Math.max(x1,x3,px[0],py[0]);
extent.maxy = Math.max(y1,y3,px[1],py[1]);
// draw the rectangle
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
ctx.strokeRect(extent.minx,extent.miny,extent.maxx-extent.minx,extent.maxy-extent.miny);
ctx.fillStyle = "rgba(255,200,0,0.2)";
ctx.fillRect(extent.minx,extent.miny,extent.maxx-extent.minx,extent.maxy-extent.miny);
// show points
ctx.fillStyle = "blue";
ctx.fillRect(x1-3,y1-3,6,6);
ctx.fillRect(x3-3,y3-3,6,6);
ctx.fillStyle = "black";
ctx.fillRect(px[0]-4,px[1]-4,8,8);
ctx.fillRect(py[0]-4,py[1]-4,8,8);
ctx.lineWidth = 3;
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.quadraticCurveTo(x2,y2,x3,y3);
ctx.stroke();
// control point
ctx.lineWidth = 1;
ctx.strokeStyle = "#0a0";
ctx.strokeRect(x2-3,y2-3,6,6);
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.lineTo(x3,y3);
ctx.stroke();
// do it all again
requestAnimationFrame(update);
}
requestAnimationFrame(update);
UPDATE
While musing over the bezier I realised that I could remove a lot of code if I assumed that the bezier was normalised (the end points start at (0,0) and end at (1,1)) because the zeros can be removed and the ones simplified.
While changing the code I also realized that I had needlessly calculated the x and y for both the x and y extent coordinates. Giving 4 values while I only need 2.
The resulting code is much simpler. I remove the function solveB2 and findPoint as the calculations seam too trivial to bother with functions.
To find the x and y maxima from quadratic bezier defined with x1, y1, x2, y2, x3, y3
// solve quadratic for bounds by normalizing equation
var brx = x3 - x1; // get x range
var bx = x2 - x1; // get x control point offset
var x = bx / brx; // normalise control point which is used to check if maxima is in range
// do the same for the y points
var bry = y3 - y1;
var by = y2 - y1
var y = by / bry;
var px = [x1,y1]; // set defaults in case maximas outside range
if(x < 0 || x > 1){ // check if x maxima is on the curve
px[0] = bx * bx / (2 * bx - brx) + x1; // get the x maxima
}
if(y < 0 || y > 1){ // same as x
px[1] = by * by / (2 * by - bry) + y1;
}
// now only need to check the x and y maxima not the coordinates of the maxima
extent.minx = Math.min(x1,x3,px[0]);
extent.miny = Math.min(y1,y3,px[1]);
extent.maxx = Math.max(x1,x3,px[0]);
extent.maxy = Math.max(y1,y3,px[1]);
And the example code which has far better performance but unlike the previous demo this version does not calculate the actual coordinates of the x and y maximas.
var canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 400;
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
var x1,y1,x2,y2,x3,y3;
var ux,uy,px,py;
var extent = {
minx : null,
miny : null,
maxx : null,
maxy : null,
}
function update(time){
ctx.clearRect(0,0,800,400);
// create random bezier
x1 = Math.cos(time / 1000) * 300 + 400;
y1 = Math.sin(time / 2100) * 150 + 200;
x2 = Math.cos((time + 3000) / 1200) * 300 + 400;
y2 = Math.sin(time / 2300) * 150 + 200;
x3 = Math.cos(time / 1400) * 300 + 400;
y3 = Math.sin(time / 2500) * 150 + 200;
// solve quadratic for bounds by normalizing equation
var brx = x3 - x1; // get x range
var bx = x2 - x1; // get x control point offset
var x = bx / brx; // normalise control point which is used to check if maxima is in range
// do the same for the y points
var bry = y3 - y1;
var by = y2 - y1
var y = by / bry;
var px = [x1,y1]; // set defaults in case maximas outside range
if(x < 0 || x > 1){ // check if x maxima is on the curve
px[0] = bx * bx / (2 * bx - brx) + x1; // get the x maxima
}
if(y < 0 || y > 1){ // same as x
px[1] = by * by / (2 * by - bry) + y1;
}
// now only need to check the x and y maxima not the coordinates of the maxima
extent.minx = Math.min(x1,x3,px[0]);
extent.miny = Math.min(y1,y3,px[1]);
extent.maxx = Math.max(x1,x3,px[0]);
extent.maxy = Math.max(y1,y3,px[1]);
// draw the rectangle
ctx.strokeStyle = "red";
ctx.lineWidth = 2;
ctx.strokeRect(extent.minx,extent.miny,extent.maxx-extent.minx,extent.maxy-extent.miny);
ctx.fillStyle = "rgba(255,200,0,0.2)";
ctx.fillRect(extent.minx,extent.miny,extent.maxx-extent.minx,extent.maxy-extent.miny);
// show points
ctx.fillStyle = "blue";
ctx.fillRect(x1-3,y1-3,6,6);
ctx.fillRect(x3-3,y3-3,6,6);
ctx.fillStyle = "black";
ctx.fillRect(px[0]-4,px[1]-4,8,8);
ctx.lineWidth = 3;
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.quadraticCurveTo(x2,y2,x3,y3);
ctx.stroke();
// control point
ctx.lineWidth = 1;
ctx.strokeStyle = "#0a0";
ctx.strokeRect(x2-3,y2-3,6,6);
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.lineTo(x3,y3);
ctx.stroke();
// do it all again
requestAnimationFrame(update);
}
requestAnimationFrame(update);

Calculate the mid point of latitude and longitude co-ordinates

Does anyone know the best way to go about getting the mid-point of a pair of latitude and longitude points?
I mm using d3.js to draw points on a map and need to draw a curved line between two points, so I need to create a mid point to draw a curve in the lines.
Please see image below for a better understanding of what I am trying to do:
Apologies for the long script - it just seemed fun to draw stuff :-). I've marked off sections that are not required
// your latitude / longitude
var co2 = [70, 48];
var co1 = [-70, -28];
// NOT REQUIRED
var ctx = document.getElementById("myChart").getContext("2d");
function drawPoint(color, point) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(point.x, point.y, 5, 0, 2 * Math.PI, false);
ctx.fill();
}
function drawCircle(point, r) {
ctx.strokeStyle = 'gray';
ctx.setLineDash([5, 5]);
ctx.beginPath();
ctx.arc(point.x, point.y, r, 0, 2 * Math.PI, false);
ctx.stroke();
}
// REQUIRED
// convert to cartesian
var projection = d3.geo.equirectangular()
var cot1 = projection(co1);
var cot2 = projection(co2);
var p0 = { x: cot1[0], y: cot1[1] };
var p1 = { x: cot2[0], y: cot2[1] };
// NOT REQUIRED
drawPoint('green', p0);
drawPoint('green', p1);
// REQUIRED
function dfn(p0, p1) {
return Math.pow(Math.pow(p0.x - p1.x, 2) + Math.pow(p0.y - p1.y, 2), 0.5);
}
// from http://math.stackexchange.com/a/87374
var d = dfn(p0, p1);
var m = {
x: (p0.x + p1.x) / 2,
y: (p0.y + p1.y) / 2,
}
var u = (p1.x - p0.x) / d
var v = (p1.y - p0.y) / d;
// increase 1, if you want a larger curvature
var r = d * 1;
var h = Math.pow(Math.pow(r, 2) - Math.pow(d, 2) / 4, 0.5);
// 2 possible centers
var c1 = {
x: m.x - h * v,
y: m.y + h * u
}
var c2 = {
x: m.x + h * v,
y: m.y - h * u
}
// NOT REQUIRED
drawPoint('gray', c1)
drawPoint('gray', c2)
drawCircle(c1, r)
drawCircle(c2, r)
// REQUIRED
// from http://math.stackexchange.com/a/919423
function mfn(p0, p1, c) {
// the -c1 is for moving the center to 0 and back again
var mt1 = {
x: r * (p0.x + p1.x - c.x * 2) / Math.pow(Math.pow(p0.x + p1.x - c.x * 2, 2) + Math.pow(p0.y + p1.y - c.y * 2, 2), 0.5)
};
mt1.y = (p0.y + p1.y - c.y * 2) / (p0.x + p1.x - c.x * 2) * mt1.x;
var ma = {
x: mt1.x + c.x,
y: mt1.y + c.y,
}
var mb = {
x: -mt1.x + c.x,
y: -mt1.y + c.y,
}
return (dfn(ma, p0) < dfn(mb, p0)) ? ma : mb;
}
var m1 = mfn(p0, p1, c1);
var m2 = mfn(p0, p1, c2);
var mo1 = projection.invert([m1.x, m1.y]);
var mo2 = projection.invert([m2.x, m2.y]);
// NOT REQUIRED
drawPoint('blue', m1);
drawPoint('blue', m2);
// your final output (in lat long)
console.log(mo1);
console.log(mo2);
Fiddle - https://jsfiddle.net/srjuc2gd/
And here's just the relevant portion (most of it is just copy-pasta from the beginning of this answer)
var Q31428016 = (function () {
// adjust curvature
var CURVATURE = 1;
// project to convert from lat / long to cartesian
var projection = d3.geo.equirectangular();
// distance between p0 and p1
function dfn(p0, p1) {
return Math.pow(Math.pow(p0.x - p1.x, 2) + Math.pow(p0.y - p1.y, 2), 0.5);
}
// mid point between p0 and p1
function cfn(p0, p1) {
return {
x: (p0.x + p1.x) / 2,
y: (p0.y + p1.y) / 2,
}
}
// get arc midpoint given end points, center and radius - http://math.stackexchange.com/a/919423
function mfn(p0, p1, c, r) {
var m = cfn(p0, p1);
// the -c1 is for moving the center to 0 and back again
var mt1 = {
x: r * (m.x - c.x) / Math.pow(Math.pow(m.x - c.x, 2) + Math.pow(m.y - c.y, 2), 0.5)
};
mt1.y = (m.y - c.y) / (m.x - c.x) * mt1.x;
var ma = {
x: mt1.x + c.x,
y: mt1.y + c.y,
}
var mb = {
x: -mt1.x + c.x,
y: -mt1.y + c.y,
}
return (dfn(ma, p0) < dfn(mb, p0)) ? ma : mb;
}
var Q31428016 = {};
Q31428016.convert = function (co1, co2) {
// convert to cartesian
var cot1 = projection(co1);
var cot2 = projection(co2);
var p0 = { x: cot1[0], y: cot1[1] };
var p1 = { x: cot2[0], y: cot2[1] };
// get center - http://math.stackexchange.com/a/87374
var d = dfn(p0, p1);
var m = cfn(p0, p1);
var u = (p1.x - p0.x) / d
var v = (p1.y - p0.y) / d;
var r = d * CURVATURE;
var h = Math.pow(Math.pow(r, 2) - Math.pow(d, 2) / 4, 0.5);
// 2 possible centers
var c1 = {
x: m.x - h * v,
y: m.y + h * u
}
var c2 = {
x: m.x + h * v,
y: m.y - h * u
}
// get arc midpoints
var m1 = mfn(p0, p1, c1, r);
var m2 = mfn(p0, p1, c2, r);
// convert back to lat / long
var mo1 = projection.invert([m1.x, m1.y]);
var mo2 = projection.invert([m2.x, m2.y]);
return [mo1, mo2]
}
return Q31428016;
})();
// your latitude / longitude
var co1 = [-70, -28];
var co2 = [70, 48];
var mo = Q31428016.convert(co1, co2)
// your output
console.log(mo[0]);
console.log(mo[1]);
For the accurate side:
You may use the Esri web API. Nothing beats decades of experience implementing the hard side of projection systems and datums... Athough the ArcGIS for Server line is a commercial product, the JS API is free, and here there's a pure JS function that does just what you want : geometryEngine.densify ; that function requires an interval parameter, that you can, in your case, get by dividing by two the results of geometryEngine.geodesicLength
That'll need you to get acquainted with the Polyline class in a very basic way, such as var mySegment = new Polyline([[50,3], [55,8]]); and probably nothing further.
For the visual side :
Your segment has two middles ? You may also be interested in geometryEngine.offset ; first offset the original segment once in each direction, then get the center point for each of the resulting segments.
For the practical side :
Given the short distances involved, provided you're not dealing with a weird place that'd be too close to the poles, I'd simply go with an arithmetic average of X and Y, and then add/subtract a rotated vector to offset your two "middles". Doing it this way would be both lighter on the machine (no libs to load from a CDN), easier on you, and as long as the purpose of it is a nice display, the result will be more than good enough.
(added as per comment : a sample)
// Your known starting points, and a k factor of your choice.
var a = {x:3, y:50};
var b = {x:8, y:55};
var k = 0.2;
// Intermediate values
var vab = {x:b.x-a.x, y:b.y-a.y};
var v_rotated = {x:-k*vab.y, y:k*vab.x};
var middle = {x:a.x+vab.x/2, y:a.y+vab.y/2};
// Your two resulting points
var result_i = {x: middle.x + v_rotated.x, y: middle.y + v_rotated.y};
var result_j = {x: middle.x - v_rotated.x, y: middle.y - v_rotated.y};
Check this question, you can use it to find the middle of your coordination on google map. I customized it to use with d3js.
Hope this help you.
In D3
function midpoint (lat1, lng1, lat2, lng2) {
lat1= deg2rad(lat1);
lng1= deg2rad(lng1);
lat2= deg2rad(lat2);
lng2= deg2rad(lng2);
dlng = lng2 - lng1;
Bx = Math.cos(lat2) * Math.cos(dlng);
By = Math.cos(lat2) * Math.sin(dlng);
lat3 = Math.atan2( Math.sin(lat1)+Math.sin(lat2),
Math.sqrt((Math.cos(lat1)+Bx)*(Math.cos(lat1)+Bx) + By*By ));
lng3 = lng1 + Math.atan2(By, (Math.cos(lat1) + Bx));
return (lat3*180)/Math.PI .' '. (lng3*180)/Math.PI;
}
function deg2rad (degrees) {
return degrees * Math.PI / 180;
};
Update 1
If you try to draw curve line, you should create a path with coordination such as :
var lat1=53.507651,lng1=10.046997,lat2=52.234528,lng2=10.695190;
var svg=d3.select("body").append("svg").attr({width:700 , height:600});
svg.append("path").attr("d", function (d) {
var dC="M "+lat1+","+lng1+ " A " + midpoint (lat1, lng1, lat2, lng2)
+ " 0 1,0 " +lat2 +" , "+lng2 +"Z";
return dC;
})
.style("fill","none").style("stroke" ,"steelblue");
You need to create your curve line as you want in d3.
JsFiddle here.
I always use geo-lib
and works

Draw a nice neat arc without the massive right angle and have nice corners instead

I've made an arc in Raphael what I was aiming for was just one arc with out the
big right angle in it.
So just one smooth curved line without the right angle.
It's pretty basic and uses the Raphael elliptical arc.
You can see it at http://jsfiddle.net/mailrox/uuAjV/1/
Here's the code:
var raph = Raphael(0, 0, 1000, 1000);
var x = 150;
var y = 150;
var r = 100; //radius
var value = 100;
var maxValue = 360;
var pi = Math.PI;
var cos = Math.cos;
var sin = Math.sin;
var t = (pi/2) * 3; //translate
var rad = (pi*2 * (maxValue-value)) / maxValue + t;
var p = [
"M", x, y,
"l", r * cos(t), r * sin(t),
"A", r, r, 0, +(rad > pi + t), 1, x + r * cos(rad), y + r * sin(rad),
"z"
];
var param = {"stroke-width": 30}
var d = raph.path(p).attr(param);
One way I've done is I could mask the right-angle sections of the lines out however I'd rather not have this and just have once nice curve opposed to managing both that current path and a mask over the top.
Really appreciate some help with this thanks!
Try this. Just take the close path (the 'z') off your SVG path definition (note I didn't test this solution):
var raph = Raphael(0, 0, 1000, 1000);
var x = 150;
var y = 150;
var r = 100; //radius
var value = 100;
var maxValue = 360;
var pi = Math.PI;
var cos = Math.cos;
var sin = Math.sin;
var t = (pi/2) * 3; //translate
var rad = (pi*2 * (maxValue-value)) / maxValue + t;
var p = [
"M", x, y,
"l", r * cos(t), r * sin(t),
"A", r, r, 0, +(rad > pi + t), 1, x + r * cos(rad), y + r * sin(rad)
];
var param = {"stroke-width": 30}
var d = raph.path(p).attr(param);
jsFiddle
You can extend the Raphael object to include an arc function.
The arc calculation has been modfied from Raphael's 'Polar clock' demo: http://raphaeljs.com/polar-clock.html
Demo: http://jsfiddle.net/TmVHq/
Raphael.fn.arc = function(cx, cy, value, total, radius) {
var alpha = 360 / total * value,
a = (90 - alpha) * Math.PI / 180,
x = cx + radius * Math.cos(a),
y = cy - radius * Math.sin(a),
path;
if (total === value) {
path = [['M', cx, cy - radius], ['A', radius, radius, 0, 1, 1, (cx - 0.01), cy - radius]];
} else {
path = [['M', cx, cy - radius], ['A', radius, radius, 0, +(alpha > 180), 1, x, y]];
}
return this.path(path);
}
var Paper = new Raphael('canvas', 300, 300);
var arc = Paper.arc(150, 150, 270, 360, 100);
arc.attr('stroke-width', 15);​

Categories