Make draggable JSXGraph using JavaScript - javascript

How can I make a point label draggable in JSXGraph?
I'm able to make triangle using JSXGraph, but I cannot create draggable vertices of this graph.
Here is my code:
<script type="text/javascript">
board = JXG.JSXGraph.initBoard('jxgbox3',
{
axis:true,
boundingbox:[-5.9,8,5.9,-5.9],
keepaspectratio:true,
showCopyright:false,
showNavigation:false
});
var qr = [], arc2,isInDragMode;
qr[1] = board.create('point', [0,0],
{style:5,fillColor:'#ff00ff'});
qr[2] = board.create('point', [5,0],
{style:5,fillColor:'#ff00ff'});
qr[3] = board.create('point', [3.85,4.4],
{style:5,fillColor:'#ff00ff'});
var triArr1 = [qr[3],qr[2],qr[1]];
var tri = board.createElement('polygon',triArr1,
{strokeWidth:2, strokeColor:'#dd00dd',highlight:false});
var arc1 = board.create('nonreflexangle',triArr1,
{radius:1,name:'θ2'});
var triArr2 = [qr[2],qr[1],qr[3]];
var arc2 = board.create('nonreflexangle',triArr2,
{radius:1,name:'θ1'});
var triArr3 = [qr[1],qr[3],qr[2]];
var arc3 = board.create('nonreflexangle',triArr3,
,{fixed:false}, {radius:1,name:'θ3'});
board.create('text', [-5, 3, function ()
{
if(arc2.Value() > Math.PI)
{
ang2 = (360 - arc2.Value() * 180 / Math.PI).toFixed(1);
ang1 = (360 - arc1.Value() * 180 / Math.PI).toFixed(1);
ang3 = (360 - arc3.Value() * 180 / Math.PI).toFixed(1);
}
else
{
ang2 = (arc2.Value() * 180 / Math.PI).toFixed(1);
ang1 = (arc1.Value() * 180 / Math.PI).toFixed(1);
ang3 = (arc3.Value() * 180 / Math.PI).toFixed(1);
}
return '<p>θ_1 = ' + ang2 + '°</p>'+'<p>θ_2 = ' + ang1 + '°</p>'+'<p>θ_3 = ' + ang3 + '°</p>'+'<p>θ_1 + θ_2 + θ_3 = 180°</p>';
}],{fixed:false});

By default, labels are fixed. In your code the point labels are draggable if constructed with
qr[1] = board.create('point', [0,0],
{style:5, fillColor:'#ff00ff', label:{ fixed:false }});
qr[2] = board.create('point', [5,0],
{style:5, fillColor:'#ff00ff', label:{ fixed:false }});
qr[3] = board.create('point', [3.85,4.4],
{style:5, fillColor:'#ff00ff', label:{ fixed:false }});
For better handling on touch devices it is advisable to set ignoreLabels:false in initBoard():
board = JXG.JSXGraph.initBoard('jxgbox3',
{
axis: true,
ignoreLabels: false,
boundingbox:[-5.9,8,5.9,-5.9],
keepaspectratio:true,
showCopyright:false,
showNavigation:false
});

Related

Converting 360 degree view to equirectangular in node js?

I have been trying to convert the 360 degree camera, single fish eye image, to equirectangular viewer in node js for the past two days. In stackoverflow, the same question is asked and answered in pseudo code. I have been trying to convert pseudo code to node js and cleared some errors. Now the project runs without error but the output image is blank.
From that pseudo, I dont know the polar_w, polar_h and geo_w, geo_h, geo and polar value, so, it gave static value to show the output. Here is a link which i followed to convert pseudo code to node js.
How to convert spherical coordinates to equirectangular projection coordinates?.
Here is the code I tried for converting spherical image to equirectangular viewer:
exports.sphereImage=(request, response)=>{
var Jimp = require('jimp');
// Photo resolution
var img_w_px = 1280;
var img_h_px = 720;
var polar_w = 1280;
var polar_h = 720;
var geo_w = 1280;
var geo_h = 720;
var img_h_deg = 70;
var img_w_deg = 30;
// Camera field-of-view angles
var img_ha_deg = 70;
var img_va_deg = 40;
// Camera rotation angles
var hcam_deg = 230;
var vcam_deg = 60;
// Camera rotation angles in radians
var hcam_rad = hcam_deg/180.0*Math.PI;
var vcam_rad = vcam_rad/180.0*Math.PI;
// Rotation around y-axis for vertical rotation of camera
var rot_y = [
[Math.cos(vcam_rad), 0, Math.sin(vcam_rad)],
[0, 1, 0],
[-Math.sin(vcam_rad), 0, Math.cos(vcam_rad)]
];
// Rotation around z-axis for horizontal rotation of camera
var rot_z = [
[Math.cos(hcam_rad), -Math.sin(hcam_rad), 0],
[Math.sin(hcam_rad), Math.cos(hcam_rad), 0],
[0, 0, 1]
];
Jimp.read('./public/images/4-18-2-42.jpg', (err, lenna) => {
polar = new Jimp(img_w_px, img_h_px);
geo = new Jimp(img_w_px, img_h_px);
for(var i=0; i<img_h_px; ++i)
{
for(var j=0; j<img_w_px; ++j)
{
// var p = img.getPixelAt(i, j);
var p = lenna.getPixelColor(i, j)
// var p = getPixels(img, { x: i, y: j })
// Calculate relative position to center in degrees
var p_theta = (j - img_w_px / 2.0) / img_w_px * img_w_deg / 180.0 * Math.PI;
var p_phi = -(i - img_h_px / 2.0) / img_h_px * img_h_deg / 180.0 *Math. PI;
// Transform into cartesian coordinates
var p_x = Math.cos(p_phi) * Math.cos(p_theta);
var p_y = Math.cos(p_phi) * Math.sin(p_theta);
var p_z = Math.sin(p_phi);
var p0 = {p_x, p_y, p_z};
// Apply rotation matrices (note, z-axis is the vertical one)
// First vertically
var p1 = rot_y[1][2][3] * p0;
var p2 = rot_z[1][2][3] * p1;
// Transform back into spherical coordinates
var theta = Math.atan2(p2[1], p2[0]);
var phi = Math.asin(p2[2]);
// Retrieve longitude,latitude
var longitude = theta / Math.PI * 180.0;
var latitude = phi / Math.PI * 180.0;
// Now we can use longitude,latitude coordinates in many different
projections, such as:
// Polar projection
{
var polar_x_px = (0.5*Math.PI + phi)*0.5 * Math.cos(theta)
/Math.PI*180.0 * polar_w;
var polar_y_px = (0.5*Math.PI + phi)*0.5 * Math.sin(theta)
/Math.PI*180.0 * polar_h;
polar.setPixelColor(p, polar_x_px, polar_y_px);
}
// Geographical (=equirectangular) projection
{
var geo_x_px = (longitude + 180) * geo_w;
var geo_y_px = (latitude + 90) * geo_h;
// geo.setPixel(geo_x_px, geo_y_px, p.getRGB());
geo.setPixelColor(p, geo_x_px, geo_y_px);
}
// ...
}
}
geo.write('./public/images/4-18-2-42-00001.jpg');
polar.write('./public/images/4-18-2-42-00002.jpg');
});
}
And tried another method by slicing image into four parts to detect car. Sliced image into four parts using image-slice module and to read and write jimp module is used. But unfortunately cars not detected properly.
Here is the code i used for slicing image:
exports.sliceImage=(request, response)=>{
var imageToSlices = require('image-to-slices');
var lineXArray = [540, 540];
var lineYArray = [960, 960];
var source = './public/images/4-18-2-42.jpg'; // width: 300, height: 300
imageToSlices(source, lineXArray, lineYArray, {
saveToDir: './public/images/',
clipperOptions: {
canvas: require('canvas')
}
}, function() {
console.log('the source image has been sliced into 9 sections!');
});
}//sliceImage
And for detect car from image i used opencv4nodejs. Cars are not detected properly. here is the code i used for detect car:
function runDetectCarExample(img=null){
if(img==null){
img = cv.imread('./public/images/section-1.jpg');
}else
{
img=cv.imread(img);
}
const minConfidence = 0.06;
const predictions = classifyImg(img).filter(res => res.confidence > minConfidence && res.className=='car');
const drawClassDetections = makeDrawClassDetections(predictions);
const getRandomColor = () => new cv.Vec(Math.random() * 255, Math.random() * 255, 255);
drawClassDetections(img, 'car', getRandomColor);
cv.imwrite('./public/images/section-'+Math.random()+'.jpg', img);
var name="distanceFromCamera";
var focalLen= 1.6 ;//Focal length in mm
var realObjHeight=254 ;//Real Height of Object in mm
var cameraFrameHeight=960;//Height of Image in pxl
var imgHeight=960;//Image Height in pxl
var sensorHeight=10;//Sensor height in mm
var R = 6378.1 //#Radius of the Earth
var brng = 1.57 //#Bearing is 90 degrees converted to radians.
var hc=(200/100);//Camera height in m
predictions
.forEach((data)=> {
// imgHeight=img.rows;//Image Height in pxl
// realObjHeight=data.rect.height;
// data.rect[name]=((focalLen)*(realObjHeight)*
(cameraFrameHeight))/((imgHeight)*(sensorHeight));
var dc=(((data.rect.width * focalLen) / img.cols)*2.54)*100; // meters
console.log(Math.floor(parseInt(data.rect.width)));
// var dc=((Math.floor(parseInt(data.rect.width)* 0.264583) * focalLen) / img.cols); // mm
var lat1=13.0002855;//13.000356;
var lon1=80.2046441;//80.204632;
// Gate 13.0002855,80.2046441
// Brazil Polsec : -19.860566, -43.969436
// var d=Math.sqrt((dc*dc)+(hc*hc));
// d=(data.rect[name])/1000;
data.rect[name]=d=dc/1000;
lat1 =toRadians(lat1);
lon1 = toRadians(lon1);
brng =toRadians(90);
// lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/R) +
// Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng));
// lon2 = lon1 +
Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1),
// Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2));
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(d/6371) +
Math.cos(lat1) * Math.sin(d/6371) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(d/6371) * Math.cos(lat1),
Math.cos(d/6371) - Math.sin(lat1) * Math.sin(lat2));
lat2 = toDegrees(lat2);
lon2 = toDegrees(lon2);
data.rect['latLong']=lat2+','+lon2;
// console.log(brng);
});
response.send(predictions);
cv.imshowWait('img', img);
};
here is the fish eye image which need to be converted to equirectangular.
Any help much appreciated pls....
You are asking how to convert a 360deg fish-eye projection to an equirectangular projection.
In order to do this, for every pixel on the fish-eye image you need to know where to place in onto the output image.
Your input image is 1920x1080, let us assume you want to output it to an equirectangular projection of the same size.
The input circle mapping is defined as:
cx = 960; // center of circle on X-axis
cy = 540; // center of circle on Y-axis
radius = 540; // radius of circle
If you have a pixel at (x,y) in the input image, then we can calculate the spherical coordinates using:
dx = (x - cx) * 1.0 / radius;
dy = (y - cy) * 1.0 / radius;
theta_deg = atan2(dy, dx) / MATH_PI * 180;
phi_deg = acos(sqrt(dx*dx + dy*dy)) / MATH_PI * 180;
outputx = (theta_deg + 180) / 360.0 * outputwidth_px;
outputy = (phi_deg + 90) / 180.0 * outputheight_px;
So there we translated (x,y) from the fish-eye image to the (outputx,outputy) in the equirectangular image. In order to not leave the implementation as the dreaded "exercise to the reader", here is some sample Javascript-code using the Jimp-library as used by the OP:
var jimp = require('jimp');
var inputfile = 'input.png';
jimp.read(inputfile, function(err, inputimage)
{
var cx = 960;
var cy = 540;
var radius = 540;
var inputwidth = 1920;
var inputheight = 1080;
var outputwidth = 1920;
var outputheight = 1080;
new jimp(outputwidth, outputheight, 0x000000ff, function(err, outputimage)
{
for(var y=0;y<inputheight;++y)
{
for(var x=0;x<inputwidth;++x)
{
var color = inputimage.getPixelColor(x, y);
var dx = (x - cx) * 1.0 / radius;
var dy = (y - cy) * 1.0 / radius;
var theta_deg = Math.atan2(dy, dx) / Math.PI * 180;
var phi_deg = Math.acos(Math.sqrt(dx*dx + dy*dy)) / Math.PI * 180;
var outputx = Math.round((theta_deg + 180) / 360.0 * outputwidth);
var outputy = Math.round((phi_deg + 90) / 180.0 * outputheight);
outputimage.setPixelColor(color, outputx, outputy);
}
}
outputimage.write('output.png');
});
});
Note that you will still need to do blending of the pixel with neighbouring pixels (for the same reason as when you're resizing the image).
Additionally, in your case, you only have half of the sphere (you can't see the sun in the sky). So you would need to use var outputy = Math.round(phi_deg / 90.0 * outputheight). In order to keep the right aspect ratio, you might want to change the height to 540.
Also note that the given implementation may not be efficient at all, it's better to use the buffer directly.
Anyway, without blending I came up with the result as demonstrated here:
So in order to do blending, you could use the simplest method which is the nearest neighbour approach. In that case, you should invert the formulas in the above example. Instead of moving the pixels from the input image to the right place in the output image, you can go through every pixel in the output image and ask which input pixel we can use for that. This will avoid the black pixels, but may still show artifacts:
var jimp = require('jimp');
var inputfile = 'input.png';
jimp.read(inputfile, function(err, inputimage)
{
var cx = 960;
var cy = 540;
var radius = 540;
var inputwidth = 1920;
var inputheight = 1080;
var outputwidth = 1920;
var outputheight = 1080/2;
var blendmap = {};
new jimp(outputwidth, outputheight, 0x000000ff, function(err, outputimage)
{
for(var y=0;y<outputheight;++y)
{
for(var x=0;x<outputwidth;++x)
{
var theta_deg = 360 - x * 360.0 / outputwidth - 180;
var phi_deg = 90 - y * 90.0 / outputheight;
var r = Math.sin(phi_deg * Math.PI / 180)
var dx = Math.cos(theta_deg * Math.PI / 180) * r;
var dy = Math.sin(theta_deg * Math.PI / 180) * r;
var inputx = Math.round(dx * radius + cx);
var inputy = Math.round(dy * radius + cy);
outputimage.setPixelColor(inputimage.getPixelColor(inputx, inputy), x, y);
}
}
outputimage.write('output.png');
});
});
For reference, in order to convert between Cartesian and Spherical coordinate systems. These are the formulas (taken from here). Note that the z is in your case just 1, a so-called "unit" sphere, so you can just leave it out of the equations. You should also understand that since the camera is actually taking a picture in three dimensions, you also need formulas to work in three dimensions.
Here is the generated output image:
Since I don't see your original input image in your question anymore, in order for anyone to test the code from this answer, you can use the following image:
Run the code with:
mkdir /tmp/test
cd /tmp/test
npm install --permanent jimp
cat <<EOF >/tmp/test/main.js
... paste the javascript code from above ...
EOF
curl https://i.stack.imgur.com/0zWt6.png > input.png
node main.js
Note: In order to further improve the blending, you should remove the Math.round. So for instance, if you need to grab a pixel at x is 0.75, and the pixel on the left at x = 0 is white, and the pixel on the right at x = 1 is black. Then you want to mix both colors into a dark grey color (using ratio 0.75). You would have to do this for both dimensions simultaneously, if you want a nice result. But this should really be in a new question imho.

How to calculate the rotation angle of two constrained segments?

I have two vectors, the Y-aligned is fixed whereby the X-aligned is allowed to rotate. These vectors are connected together through two fixed-length segments. Given the angle between the two vectors (82.74) and the length of all segments, how can I get the angle of the two jointed segments (24.62 and 22.61)?
What is given: the magnitude of the vectors, and the angle between the X-axis and OG:
var magOG = 3,
magOE = 4,
magGH = 3,
magEH = 2,
angleGamma = 90;
This is my starting point: angleGamma = 90 - then, I will have following vectors:
var vOG = new vec2(-3,0),
vOE = new vec2(0,-4);
From here on, I am trying to get angleAlphaand angleBeta for values of angleGamma less than 90 degrees.
MAGNITUDE OF THE CONSTRAINED SEGMENTS:
Segments HG and HE must meet following conditions:
/
| OG*OG+ OE*OE = (HG + HE)*(HG + HE)
>
| OG - HG = OE - HE
\
which will lead to following two solutions (as pointed out in the accepted answer - bilateration):
Solution 1:
========================================================
HG = 0.5*(-Math.sqrt(OG*OG + OE*OE) + OG - OE)
HE = 0.5*(-Math.sqrt(OG*OG + OE*OE) - OG + OE)
Solution 2:
========================================================
HG = 0.5*(Math.sqrt(OG*OG + OE*OE) + OG - OE)
HE = 0.5*(Math.sqrt(OG*OG + OE*OE) - OG + OE)
SCRATCHPAD:
Here is a playground with the complete solution. The visualization library used here is the great JSXGraph. Thanks to the Center for Mobile Learning with Digital Technology of the Bayreuth University.
Credits for the circle intersection function: 01AutoMonkey in the accepted answer to this question: A JavaScript function that returns the x,y points of intersection between two circles?
function deg2rad(deg) {
return deg * Math.PI / 180;
}
function rad2deg(rad) {
return rad * 180 / Math.PI;
}
function lessThanEpsilon(x) {
return (Math.abs(x) < 0.00000000001);
}
function angleBetween(point1, point2) {
var x1 = point1.X(), y1 = point1.Y(), x2 = point2.X(), y2 = point2.Y();
var dy = y2 - y1, dx = x2 - x1;
var t = -Math.atan2(dx, dy); /* range (PI, -PI] */
return rad2deg(t); /* range (180, -180] */
}
function circleIntersection(circle1, circle2) {
var r1 = circle1.radius, cx1 = circle1.center.X(), cy1 = circle1.center.Y();
var r2 = circle2.radius, cx2 = circle2.center.X(), cy2 = circle2.center.Y();
var a, dx, dy, d, h, h2, rx, ry, x2, y2;
/* dx and dy are the vertical and horizontal distances between the circle centers. */
dx = cx2 - cx1;
dy = cy2 - cy1;
/* angle between circle centers */
var theta = Math.atan2(dy,dx);
/* vertical and horizontal components of the line connecting the circle centers */
var xs1 = r1*Math.cos(theta), ys1 = r1*Math.sin(theta), xs2 = r2*Math.cos(theta), ys2 = r2*Math.sin(theta);
/* intersection points of the line connecting the circle centers */
var sxA = cx1 + xs1, syA = cy1 + ys1, sxL = cx2 - xs2, syL = cy2 - ys2;
/* Determine the straight-line distance between the centers. */
d = Math.sqrt((dy*dy) + (dx*dx));
/* Check for solvability. */
if (d > (r1 + r2)) {
/* no solution. circles do not intersect. */
return [[sxA,syA], [sxL,syL]];
}
thetaA = -Math.PI - Math.atan2(cx1,cy1); /* Swap X-Y and re-orient to -Y */
xA = +r1*Math.sin(thetaA);
yA = -r1*Math.cos(thetaA);
ixA = cx1 - xA;
iyA = cy1 - yA;
thetaL = Math.atan(cx2/cy2);
xL = -r2*Math.sin(thetaL);
yL = -r2*Math.cos(thetaL);
ixL = cx2 - xL;
iyL = cy2 - yL;
if(d === 0 && r1 === r2) {
/* infinite solutions. circles are overlapping */
return [[ixA,iyA], [ixL,iyL]];
}
if (d < Math.abs(r1 - r2)) {
/* no solution. one circle is contained in the other */
return [[ixA,iyA], [ixL,iyL]];
}
/* 'point 2' is the point where the line through the circle intersection points crosses the line between the circle centers. */
/* Determine the distance from point 0 to point 2. */
a = ((r1*r1) - (r2*r2) + (d*d)) / (2.0 * d);
/* Determine the coordinates of point 2. */
x2 = cx1 + (dx * a/d);
y2 = cy1 + (dy * a/d);
/* Determine the distance from point 2 to either of the intersection points. */
h2 = r1*r1 - a*a;
h = lessThanEpsilon(h2) ? 0 : Math.sqrt(h2);
/* Now determine the offsets of the intersection points from point 2. */
rx = -dy * (h/d);
ry = +dx * (h/d);
/* Determine the absolute intersection points. */
var xi = x2 + rx, yi = y2 + ry;
var xi_prime = x2 - rx, yi_prime = y2 - ry;
return [[xi, yi], [xi_prime, yi_prime]];
}
function plot() {
var cases = [
{a: 1.1, l: 1.9, f: 0.3073},
{a: 1.0, l: 1.7, f: 0.3229}
];
var testCase = 1;
var magA = cases[testCase].a, magL = cases[testCase].l;
var maxS = Math.sqrt(magA*magA+magL*magL), magS1 = maxS * cases[testCase].f, magS2 = maxS - magS1;
var origin = [0,0], board = JXG.JSXGraph.initBoard('jxgbox', {boundingbox: [-5.0, 5.0, 5.0, -5.0], axis: true});
var drawAs = {dashed: {dash: 3, strokeWidth: 0.5, strokeColor: '#888888'} };
board.suspendUpdate();
var leftArm = board.create('slider', [[-4.5, 3], [-1.5, 3], [0, -64, -180]]);
var leftLeg = board.create('slider', [[-4.5, 2], [-1.5, 2], [0, -12, -30]]);
var rightArm = board.create('slider', [[0.5, 3], [3.5, 3], [0, 64, 180]]);
var rightLeg = board.create('slider', [[0.5, 2], [3.5, 2], [0, 12, 30]]);
var lh = board.create('point', [
function() { return +magA * Math.sin(deg2rad(leftArm.Value())); },
function() { return -magA * Math.cos(deg2rad(leftArm.Value())); }
], {size: 3, name: 'lh'});
var LA = board.create('line', [origin, lh], {straightFirst: false, straightLast: false, lastArrow: true});
var cLS1 = board.create('circle', [function() { return [lh.X(), lh.Y()]; }, function() { return magS1; }], drawAs.dashed);
var lf = board.create('point', [
function() { return +magL * Math.sin(deg2rad(leftLeg.Value())); },
function() { return -magL * Math.cos(deg2rad(leftLeg.Value())); }
], {size: 3, name: 'lf'});
var LL = board.create('line', [origin, lf], {straightFirst: false, straightLast: false, lastArrow: true});
var cLS2 = board.create('circle', [function() { return [lf.X(), lf.Y()]; }, function() { return magS2; }], drawAs.dashed);
var lx1 = board.create('point', [
function() { return circleIntersection(cLS1, cLS2)[0][0]; },
function() { return circleIntersection(cLS1, cLS2)[0][1]; }
], {size: 3, face:'x', name: 'lx1'});
var lx2 = board.create('point', [
function() { return circleIntersection(cLS1, cLS2)[1][0]; },
function() { return circleIntersection(cLS1, cLS2)[1][1]; }
], {size: 3, face:'x', name: 'lx2'});
/* Angle between lh, lx1 shall be between 0 and -180 */
var angleLAJ = board.create('text', [-3.7, 0.5, function(){ return angleBetween(lh, lx1).toFixed(2); }]);
/* Angle between lf, lx1 shall be between 0 and 180 */
var angleLLJ = board.create('text', [-2.7, 0.5, function(){ return angleBetween(lf, lx1).toFixed(2); }]);
var rh = board.create('point', [
function() { return +magA * Math.sin(deg2rad(rightArm.Value())); },
function() { return -magA * Math.cos(deg2rad(rightArm.Value())); }
], {size: 3, name: 'rh'});
var RA = board.create('line', [origin, rh], {straightFirst: false, straightLast: false, lastArrow: true});
var cRS1 = board.create('circle', [function() { return [rh.X(), rh.Y()]; }, function() { return magS1; }], drawAs.dashed);
var rf = board.create('point', [
function() { return +magL * Math.sin(deg2rad(rightLeg.Value())); },
function() { return -magL * Math.cos(deg2rad(rightLeg.Value())); }
], {size: 3, name: 'rf'});
var RL = board.create('line', [origin, rf], {straightFirst: false, straightLast: false, lastArrow: true});
var cRS2 = board.create('circle', [function() { return [rf.X(), rf.Y()]; }, function() { return magS2; }], drawAs.dashed);
var rx1 = board.create('point', [
function() { return circleIntersection(cRS1, cRS2)[1][0]; },
function() { return circleIntersection(cRS1, cRS2)[1][1]; }
], {size: 3, face:'x', name: 'rx1'});
var rx2 = board.create('point', [
function() { return circleIntersection(cRS1, cRS2)[0][0]; },
function() { return circleIntersection(cRS1, cRS2)[0][1]; }
], {size: 3, face:'x', name: 'rx2'});
var angleRAJ = board.create('text', [+1.3, 0.5, function(){ return angleBetween(rh, rx1).toFixed(2); }]);
var angleRLJ = board.create('text', [+2.3, 0.5, function(){ return angleBetween(rf, rx1).toFixed(2); }]);
board.unsuspendUpdate();
}
plot();
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/jsxgraph/0.99.7/jsxgraph.css" />
<link rel="stylesheet" href="style.css">
<script type="text/javascript" charset="UTF-8" src="//cdnjs.cloudflare.com/ajax/libs/jsxgraph/0.99.7/jsxgraphcore.js"></script>
</head>
<body>
<div id="jxgbox" class="jxgbox" style="width:580px; height:580px;"></div>
</body>
</html>
According to your sketch, the coordinates of E and G are:
E = (0, -magOE)
G = magOG * ( -sin(gamma), -cos(gamma) )
Then, calculating the position of H is a trilateration problem. Actually, it is just bilateration because you are missing a third distance. Hence, you will get two possible positions for H.
First, let us define a new coordinate system, where E lies at the origin and G lies on the x-axis. The x-axis direction in our original coordinate system is then:
x = (G - E) / ||G - E||
The y-axis is:
y = ( x.y, -x.x )
The coordinates of E and G in this new coordinate system are:
E* = (0, 0)
G* = (0, ||G - E||)
Now, we can easily find the coordinates of H in this coordinate system, up to the ambiguity mentioned earlier. I will abbreviate ||G - E|| = d like in the notation used in the Wikipedia article:
H.x* = (magGH * magGH - magEH * magEH + d * d) / (2 * d)
H.y* = +- sqrt(magGH * magGH - H.x* * H.x*)
Hence, we have two solutions for H.y, one positive and one negative.
Finally, we just need to transform H back into our original coordinate system:
H = x * H.x* + y * H.y* - (0, magOE)
Given the coordinates of H, calculating the angles is pretty straightforward:
alpha = arccos((H.x - G.x) / ||H - G||)
beta = arccos((H.y - E.y) / ||H - E||)
Example
Taking the values from your example
magOG = 3
magOE = 4
magGH = 3
magEH = 2
angleGamma = 82.74°
we first get:
E = (0, -4)
G = 3 * ( -sin(82.74°), -cos(82.74°) )
= (-2.976, -0.379)
Our coordinate system:
x = (-0.635, 0.773)
y = ( 0.773, 0.635)
In this coordinate system:
E* = (0, 0)
G* = (0, 4.687)
Then, the coordinates of H in our auxiliary coordinate system are:
H* = (2.877, +- 0.851)
I will only focus on the positive value for H*.y because this is the point that you marked in your sketch.
Transform back to original coordinate system:
H = (-1.169, -1.237)
And finally calculate the angles:
alpha = 25.41°
beta = 22.94°
The slight differences to your values are probably caused by rounding errors (either in my calculations or in yours).

Geolocation find closest coordinate match

I'm trying to create a Javascript function that can find the closest coordinate match in an array of coordinates.
My coordinates: 33.9321, 18.8602
These coordinates will vary, but the 4 locations listed below will stay the same.
Location1: 33.9143, 18.5701
Location2: 26.2041, 28.0473
Location3: 25.7479, 28.2293
Location4: 29.8587, 31.0218
try to run my code to see if it helps you.
I have used var home as your stargint point if browser didn't work for you.
Also I have saved all locations in var points so you can change that if you need.
Then I just look over each point and it will output in the console what is the distance to ref point. In your case it's the first point
var home = [ '33.9321', '18.8602' ];
var points = [
[ '33.9143', '18.5701' ],
[ '26.2041', '28.0473' ],
[ '25.7479', '28.2293' ],
[ '29.8587', '31.0218' ]
];
// loop over each point and output distance!
for( var i = 0; i < points.length; i++){
var diff = twoPointsDiff(home[0],home[1],points[i][0],points[i][1]);
console.log( 'distance from point' + (i+1) + ': ' + diff );
}
// helper fn to calc distance
function twoPointsDiff(lat1,lon1,lat2,lon2) {
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; // Distance in km
return d;
}
// helper fn to convert deg to radians
function deg2rad(deg) {
return deg * (Math.PI/180)
}

AngularJS convert geo coordinates from Lambert 2 to WSG84

Now I have geo coordinates of Lambert 2, like this
X:595833.007,
Y:2418927.985
In order to show this place in the google map, I need the related geo coordinates of WSG84, like this
X:48.7687954,
Y:2.27984782
Is there angularjs library which includes the this function ? Thanks in advance.
To realize the convertion of coordinates among different geodetic systems, I create this repo, angular-geo-converter. it is quite easy to use.
Add the script dependence of angular-geo-convert.js:
<script src="angular-geo-converter.js"></script>
Add the module dependence in your root module of your angular application:
angular.module('app',['geoConverter'])
Call the service in your controller
angular.module('app').controller('geoCtrl',['geoConverter',function(geoConverter){
var coordinates = geoConverter.lambert2wgs(595833,2418928);
var coordinateX = coordinates.latitude; // result:48.7687954
var coordinateY = coordinates.longitude; // result:2.27984782
}])
PS: The convertion in the answer of manzapanza is not correct.
Here I found the algorithm to convert Lambert 2 to WSG84 coords.
You should create a service:
(function(){
'user strict';
function Lambert2ToWSG84() {
var self = {};
self.convert = function(x, y) {
var newLongitude, newLatitude;
var n = 0.77164219;
var F = 1.81329763;
var thetaFudge = 0.00014204;
var e = 0.08199189;
var a = 6378388;
var xDiff = 149910;
var yDiff = 5400150;
var theta0 = 0.07604294;
var xReal = xDiff - x;
var yReal = yDiff - y;
var rho = Math.sqrt(xReal * xReal + yReal * yReal);
var theta = Math.atan(xReal / -yReal);
newLongitude = (theta0 + (theta + thetaFudge) / n) * 180 / Math.PI;
newLatitude = 0;
for (var i = 0; i < 5 ; ++i) {
newLatitude = (2 * Math.atan(Math.pow(F * a / rho, 1 / n) * Math.pow((1 + e * Math.sin(newLatitude)) / (1 - e * Math.sin(newLatitude)), e / 2))) - Math.PI / 2;
}
newLatitude *= 180 / Math.PI;
return {
lat: newLatitude,
lng: newLongitude
};
};
return self;
}
angular
.module('myModuleName')
.factory('Lambert2ToWSG84', Lambert2ToWSG84);
})();
And use it, for example, in a controller:
function MyCtrl(Lambert2ToWSG84) {
var vm = this;
vm.convert = function(x, y){
return Lambert2ToWSG84.convert(x, y);
};
}
MyCtrl.$inject = ['Lambert2ToWSG84'];
angular
.module('myModuleName')
.controller('MyCtrl', MyCtrl);
CHECK THE DEMO FIDDLE

JS variables and calculations failling;

Based on copy-engineering of someone else's code, I created the following code (see fiddle here) :
//INITIAL DATA:
var geometry.id = "Norway";
var bounds = [[-5, 40], [10, 50]];
// START CALCULATIONS
// WNES for West, North, East, South.
// WNES borders' geo-coordinates (decimal degrees)
var WNES = "",
WNES.item = geometry.id,
WNES.W = bounds[0][0],
WNES.N = bounds[1][1],
WNES.E = bounds[1][0],
WNES.S = bounds[0][1];
// Area's geo-dimensions (decimal degrees)
var WNES.geo_width = (WNES.E - WNES.W),
WNES.geo_height = (WNES.N - WNES.S);
// add a 5% padding on all WNES sides.
var WNESplus.W = WNES.W - WNES.geo_width * 0.05,
WNESplus.N = WNES.N + WNES.geo_height * 0.05,
WNESplus.E = WNES.E + WNES.geo_width * 0.05,
WNESplus.S = WNES.S - WNES.geo_height * 0.05,
WNESplus.geo_width = (WNESplus.E - WNESplus.W),
WNESplus.geo_height = (WNESplus.N - WNESplus.S);
// calcul center geo-coordinates
var WNES.lat_center = (WNES.S + WNES.N) / 2,
WNES.lon_center = (WNES.W + WNES.E) / 2;
//TEST:
console.log("Test" + WNESplus.N + " and " + WNESplus.geo_width);
This completely fails. It seems I do assignment, and semicolon use wrongly. What is my mistake, How to prossess properly ?
var is used to declare local variables. Using it to "declare" object properties is incorrect.
You should just be doing something like:
WNES.geo_width = (WNES.E - WNES.W);
WNES.geo_height = (WNES.N - WNES.S);
That said, you appear to be trying to assign properties to a literal string. This will not work. You should probably start with:
var WNES = {};
You are setting object properties without creating it. You can't use dot notation in variable declaration.
Try below:
//INITIAL DATA:
var bounds = [[-5, 40], [10, 50]];
var geometry = {};
geometry.id = "Norway";
// START CALCULATIONS
// WNES borders' geo-coordinates (decimal degrees for West, North, East, South borders)
var WNES = {};
WNES.item = geometry.id,
WNES.W = bounds[0][0],
WNES.N = bounds[1][1],
WNES.E = bounds[1][0],
WNES.S = bounds[0][1];
// Area's geo-dimensions (decimal degrees)
WNES.geo_width = (WNES.E - WNES.W),
WNES.geo_height = (WNES.N - WNES.S);
// add a 5% padding on all WNES sides.
var WNESplus = {};
WNESplus.W = WNES.W - WNES.geo_width * 0.05,
WNESplus.N = WNES.N + WNES.geo_height * 0.05,
WNESplus.E = WNES.E + WNES.geo_width * 0.05,
WNESplus.S = WNES.S - WNES.geo_height * 0.05,
WNESplus.geo_width = (WNESplus.E - WNESplus.W),
WNESplus.geo_height = (WNESplus.N - WNESplus.S);
// calcul center geo-coordinates
WNES.lat_center = (WNES.S + WNES.N) / 2,
WNES.lon_center = (WNES.W + WNES.E) / 2;
console.log("Test"+ WNESplus.N +" and "+ WNESplus.geo_width);
jsFiddle
You cannot assign properties of an object (geometry, WNES, WNESplus) using var. You have to first initialize them as objects and then assign properties:
//INITIAL DATA:
var bounds = [[-5, 40], [10, 50]];
var geometry = {};
geometry.id = "Norway";
// START CALCULATIONS
// WNES borders' geo-coordinates (decimal degrees for West, North, East, South borders)
var WNES = {};
WNES.item = geometry.id;
WNES.W = bounds[0][0];
WNES.N = bounds[1][1];
WNES.E = bounds[1][0];
WNES.S = bounds[0][1];
// Area's geo-dimensions (decimal degrees)
WNES.geo_width = (WNES.E - WNES.W);
WNES.geo_height = (WNES.N - WNES.S);
// add a 5% padding on all WNES sides.
var WNESplus = {};
WNESplus.W = WNES.W - WNES.geo_width * 0.05;
WNESplus.N = WNES.N + WNES.geo_height * 0.05;
WNESplus.E = WNES.E + WNES.geo_width * 0.05;
WNESplus.S = WNES.S - WNES.geo_height * 0.05;
WNESplus.geo_width = (WNESplus.E - WNESplus.W);
WNESplus.geo_height = (WNESplus.N - WNESplus.S);
// calcul center geo-coordinates
WNES.lat_center = (WNES.S + WNES.N) / 2;
WNES.lon_center = (WNES.W + WNES.E) / 2;
console.log("Test " + WNESplus.N + " and " + WNESplus.geo_width);
Here is workign jsFiddle
You are not allowed to declare a variable as an object in this format. Everything that includes dot notation or object, should be declared as var something = {}. And as an example:
This geometry.id = "Norway"; will 100% fail. But you can declare it as:
var geometry = { id: "Norway"}; and follow the same template for the others as well.

Categories

Resources