Find the nearest point relative to a designated location

In my latest project, I have created a stunning panorama featuring a compass placed right in the middle. The compass is initially pointing towards the top center of the image.

Now, I am faced with the challenge of moving the compass as the viewer navigates through the 360 panorama. This movement creates an adjacent duplicate image, and what I aim to achieve is for the compass to always point towards the closest point on either side as the viewer moves from left to right or vice versa.

Although I have made some progress, the behavior of the compass doesn't align with my vision.

Here is the code snippet that I have been working on: https://gist.github.com/joeyhipolito/8678bf35dba7795de4d5

The approach I took was to define two points:

points.push({
  x: target.offset().left + (windowWidth) / 2,
  y: target.offset().top
});

points.push({
  x: (target.offset().left + (windowWidth) / 2) + (common.width / 2),
  y: target.offset().top
});

My next step was to calculate which point is closer to the reference using the Pythagorean theorem.

var closestPoint = points[0];
var closestValue = Math.sqrt(Math.pow(points[0].x, 2) + Math.pow(points[0].y, 2));

for (var i = 1; i >= points.length; i++) {
  var z = Math.sqrt(Math.pow(points[i].x, 2) + Math.pow(points[i].y, 2));
  if(z < closestValue) {
    closestPoint = points[i];
    closestValue = z;
  }
};

I would appreciate your insights on what might be missing in my implementation.

Answer №1

It appears that there may be a problem with the control of your for loop. The current implementation looks like this:

for (var i = 1; i >= points.length; i++) {
};

Due to the exit condition, this loop will not run as expected. The initial value of i is set to 1, which is already greater than the array's length (presumably 2 or more). Conversely, if the array length were less than or equal to 1, the loop would run indefinitely since i keeps increasing and i>=length remains true.

To address this issue, consider changing the exit condition to i<=length. This modification should improve the functionality of the minimum-finding logic within the loop.

Answer №2

Modify

//                 ↑↑
for ( let i = 1; i < points.length; i++ ) {
  // ...
};

into

//                 ↑
for ( let i = 1; i <= points.length; i++ ) {
  // ...
};

Another way to accomplish this is by utilizing Array.reduce(). Although it may not be as efficient, it can be more descriptive:

function calculateDistanceFromOrigin( point ) {
  return Math.sqrt( Math.pow( point, 2 ) + Math.pow( point, 2 ) );
}


let nearestPoint = points.reduce(
  function( nearestPoint, currentPoint, index, array ) {
    let currentDistance = calculateDistanceFromOrigin( currentPoint ),
      closestDistance = calculateDistanceFromOrigin( nearestPoint );

    if ( currentDistance < closestDistance ) {
      return currentPoint;
    } else {
      return nearestPoint;
    }
  }
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modify the active link color in a Bootstrap menu by adjusting the CSS

Hi, I'm experiencing an issue with my CSS Bootstrap menu. I am unable to change the active link color, meaning that when I click on a link and move my mouse pointer out of the area, the link background turns white. I would like it to remain transparen ...

Suggestions for breaking out of the function update()?

Having some trouble escaping my update() function. Here's the attempt I've made: if (score.l1 > 20) { break; } However, all I get is an error message saying "Illegal break statement" ...

What is the most efficient method for transferring rows from an SQL Database to JavaScript?

Recently, I've been exploring the dynamic features of HTML5 IndexedDB controlled by Javascript and how to sync it with an SQL Server database for offline access. The challenge I'm facing is determining the most efficient method to transfer data ...

Compare an array of strings with an array of objects and provide a specific result for each comparison

I'm facing a simple array dilemma: I have two separate arrays - one containing strings and the other containing objects. What I need to do is compare them in a specific manner: The array of objects should verify if a property of each object is present ...

Troubleshooting a resizing problem in Angular's ag-grid

Is there a way to enable column resizing without allowing users to resize columns to the left side and create blank spaces on the right of the grid? Please refer to the image below for clarification. https://i.sstatic.net/cnhYn.png ...

How to Use JQuery to Capitalize the First Letter of Every Word in a Sentence

How can I capitalize the first letter of each word in a text field using JQuery? I've been struggling to achieve this. Here is the Bootstrap code that I'm currently using to extract data from a text field when a button is submitted <button cl ...

Display a series of messages using an Angular directive

Here is a sample HTML code: <section class="correspondence"> <header> <div class="from">{{ message.from }}</div> <div class="when">{{ message.when }}</div> </header> <div class="content"> { ...

Styling a Pie or Doughnut Chart with CSS

I am working on creating a doughnut chart with rounded segments using Recharts, and I want it to end up looking similar to this: Although I have come close to achieving the desired result, I am encountering some issues: Firstly, the first segment is over ...

Unable to obtain the vertices of the extremities due to the absence of labels on AxisHelper

My goal is to add labels on AxisHelper in Three.js that rotate along with it. I came across a helpful code snippet from this source: // Axes axes2 = new THREE.AxisHelper(70); // Axes labels addLabelAxes(); // Add axes to zoomScene zoomScene.add(axes2); ...

Could you assist me in obtaining $randomQ and $matchinA, and then triggering a jQuery refresh when $matchinA is entered?

Could someone kindly assist me with retrieving a random question, labeled as '$randomQuestion' (e.g., "What color is the sky?"), along with its corresponding answer, $matchingAnswer, from the quizID section of my SQL database? I would also like t ...

Having trouble choosing elements with angular.element within ng-repeat loop

In my HTML code, I am using an ngRepeat element: <ol id="animationFrame"> <li ng-repeat="animationImage in animationImages" ng-repeat-listener> <img ng-src="{{animationImage.src}}" id="{{animationImage.id}}"> </li> </ol& ...

The connection between React-redux @connect is malfunctioning, whereas using connect() functions smoothly

Is there an issue with using the @connect() syntax instead of export default connect()? It seems that when I stick to the traditional syntax class PhonePage extends Component { ... } export default connect(state => ({ testedByPhone: state.pho ...

Which is the best approach: placing AJAX calls inside or outside of a for-loop, or having the for-loop on the server

This question pertains to implementation. I am working with an array of tags and I need to retrieve data for each one individually, without needing them to communicate with one another. My goal is to fetch the data and save it in a designated location. W ...

Obtaining Input in NodeJS

I am working on a code that captures user input but I am facing an issue. Currently, the code does not wait for the input to be completed. I am looking for a solution where the code will pause until the user has entered their input. It is crucial for me th ...

Optimal approach for creating a CSS button with a dynamic size, gradient background and arrow design

I'm utilizing the Zurb Foundation framework and aiming to create dynamic call-to-action buttons with varying sizes, text, a background gradient, and a right-pointing arrow. There are three potential approaches I've envisioned: Employ an a el ...

Troubleshooting problem with Bootstrap 4 columns alignment - issue with nested columns wrapping

I attempted to create a column layout using Bootstrap 4, but unfortunately, the alignment is off. The nested columns do not display properly and the last one even breaks to a new line. <div class="row"> <div class="col-sm-3"> <d ...

Resolving the issue in handling the JS challenge called Powers - a combination of functions and arrays

Struggling with a simple task called Powers? Here's the challenge at hand: Numbers have Powers! They can transform themselves in various ways. One such transformation involves: replacing each 0 - with the absolute difference of its neighboring numbe ...

Updating binary files using Node.js

I am currently working on handling binary files in Node.js. My goal is to receive a binary file from the client, open it, convert it to hexadecimal, make some modifications, and then send back the updated binary file to the client. app.use('/read-bin ...

Having trouble implementing uppercase text in Bootstrap editable modules

Recently, I implemented the bootstrap editable function in my application and it was functioning perfectly. However, I am now looking to have the editable text always display in uppercase format. Unfortunately, I am unsure of how to achieve this. Any sugge ...

The label is not displaying the specified font-family in CSS

Below is a snippet of code that I am having trouble with: testing some content Additionally, here is the CSS code for it: label { font-family: "Andale Mono"; } The issue I am facing is that no matter which font style I try to apply, it does not seem to ...