Angular Distance Calculation Techniques

I am developing an application for distance calculations using Angular, which consists of the following elements:

HTML:

<form [formGroup]="form" *ngIf="showForm">
<div formArrayName="distance" >
<table>
  <thead>
      <th> From Distance (Km) </th>
      <th> To Distance (Km) </th>
      <th> Fare Per Kilometer </th>
    </thead>
    <tbody>
    <tr 
      *ngFor="let item of form.get('distance').controls; let i = index" 
      [formGroupName]="i">
      <td>
      <input type="number" 
        placeholder="From" 
        formControlName="from">
        </td>
      <td>
        <input type="number"
          placeholder="To" 
          formControlName="to">
      </td>
       <td>
        <input type="number"
          placeholder="Fare Per Km" 
          formControlName="farePerKm">
      </td>
     </tr>
    </tbody>
   </table>
  </div>
</form>

TS:

  selectedValues(e) {
    this.showForm = true;
    this.form = this.fb.group({
      distance: this.fb.array([]),
    });
    const control = this.form.controls.distance as FormArray;
    if (e.target.value === "V1") {
      this.vehicleOne.forEach(data => {
        control.push(this.fb.group({
          from: [data.from, Validators.required],
          to: [data.to, Validators.required],
          farePerKm: [data.farePerKm, Validators.required]
        }));
      });
    }
    else if (e.target.value === "V2") {
      this.vehicleTwo.forEach(data => {
        control.push(this.fb.group({
          from: [data.from, Validators.required],
          to: [data.to, Validators.required],
          farePerKm: [data.farePerKm, Validators.required]
        }));
      });
    }
  }

The code above serves as a reference. The complete code can be found in the working example https://stackblitz.com/edit/disable-group-control-value-on-another-control-value-for-itrxah

Requirement: The objective is to provide the user with accurate fare calculation based on the vehicle selection and total distance travelled between two locations.

Upon selecting a vehicle, choosing the origin and destination locations, and inputting the distance traveled, the application should automatically calculate the total fare. For example, when selecting

Vehicle One(vehicle), Location A (From Location), Location C (To Location), 20KM (Total Distance traveled)
, the total fare should be updated to 350.

This calculation takes into account the fare per kilometer rates specified for each segment of the journey. There are different split-up calculations for each vehicle model.

Note: The structure mentioned in the code snippet may vary, as the actual application involves map-based distance calculations integrated within the form fields.

Main Requirement: The primary goal is to determine the total fare cost based on the total distance traveled by a rider in a specific vehicle, considering the fare breakdown according to kilometers covered as indicated below.

Below is an example of the fare split-up for Vehicle One, where traveling 20km would result in a total fare of 350 (For example).

From Distance (Km)  To Distance (Km)    Fare Per Kilometer

0                    5                   10

6                    20                  20

Answer №1

Create a function to calculate the price based on different fare rates.

Firstly, ensure that the "fares" are properly defined with corresponding values for "from" and "to". For example:

vehicleOne: any = [{ from: "0", to: "5", farePerKm: "10" }, 
                   { from: "5", to: "20", farePerKm: "20" }, //<--"from" should match "to" above
                   { from: "20", to: "50", farePerKm: "5" }] //<--"from" should match "to" above

Now, let's consider calculating the price for traveling 6km using vehicle "V1". Here is the function logic:

  getPrice(vehicleID: string, distance: number) {
    let fare: any[];
    switch (vehicleID) {
      case "V1":
        fare = this.vehicleOne;
        break;
      case "V2":
        fare = this.vehicleTwo;
        break;
    }
    let price: number = 0;
    let distanceCal = distance;
    
    // Rest of the code for calculating the total price based on fares
    
    return price;
  }

Instead of using a switch statement, you can enhance the code structure by organizing fares within vehicles as follows:

vehicles: any = [
   { id: "V1", vehicleName: "Vehicle One", fares: [{ from: "0", to: "5", farePerKm: "10" }, { from: "5", to: "20", farePerKm: "20" }] },
   { id: "V2", vehicleName: "Vehicle Two", fares: [{ from: "0", to: "10", farePerKm: "15" }, { from: "10", to: "20", farePerKm: "12" }] }

Update the getPrice function accordingly to access fares directly from the selected vehicle:

getPrice(vehicleId: string, distance: number) {
    let fare= this.vehicles.find(x=>x.id==vehicleID).fares;
    .... //Continue with the rest of the code
}

Note: Ensure to convert string values to numbers using "+" in your calculations. Note2: It's important to thoroughly test the function. You can do a quick check in ngOnInit like:

for (let distance=0;distance<30;distance++)
      console.log(distance,this.getPrice("V1",distance))

Answer №2

Here is a helpful guide to address your issue. I have only included the necessary code modifications to point you in the right direction. Please keep in mind that this is not a complete solution but rather a hint to assist you.

To begin, in your AppModule, include the FormsModule to enable the use of the ngModule directive.

import { ReactiveFormsModule, FormsModule } from '@angular/forms';

@NgModule({
imports:      [ BrowserModule, ReactiveFormsModule, FormsModule ],
...

In your TypeScript file, introduce the following variables:

protected totalFare: string;
protected chosenVehicle: any;
protected selectedDistance: any;

Add to your vehicles list as follows:

vehicles: any = [
{ id: "V1", vehicleName: "Vehicle One", fares: [{ from: "0", to: "5", farePerKm: "10" }, { from: "6", to: "20", farePerKm: "20" }] },
{ id: "V2", vehicleName: "Vehicle Two", fares: [{ from: "0", to: "10", farePerKm: "15" }, { from: "11", to: "20", farePerKm: "12" }] }

Then, implement the following method:

protected onDistanceSelection(): void {
    const vehicle = this.vehicles.filter(el => el.id === this.chosenVehicle)[0];
    this.totalFare = vehicle.fares[0].farePerKm;
}

In your HTML file, make these adjustments:

<select (change)="selectedValues($event)" [(ngModel)]="chosenVehicle">
  <option value="undefined" disabled selected> Choose a vehicle </option>
  <option *ngFor="let vehicle of vehicles" [value]="vehicle.id"> {{  vehicle.vehicleName  }} </option>
</select>

...

<input type="text" [(ngModel)]="totalFare" placeholder="Total fare">

Please take note of the correction made for "undefined" in your code to ensure that the dropdowns display the correct text at the beginning.

By selecting a vehicle and distance, the fare per kilometer of the chosen vehicle will be displayed in the total fare textbox. This should provide a starting point for your calculations within onDistanceSelection(). You can also utilize selectedDistance in this function.

Enjoy exploring further! ;)

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

Achieving a function call within a Backbone view in Backbone.js

Is it possible to call the plotPort function from the plotLoc function using this.plotPort() instead of self.plotPort()? It seems to not work for Internet Explorer when using self.plotPort(). As a workaround, I added an event to lLoca upon reset to call ...

React import syntax using dot notation

I've noticed a trend in many react frameworks recommending dot notation for imports. For example, instead of: import Y from 'X/Y'; <Y /> they suggest using: import X from 'X'; <X.Y /> Both methods seem to work ...

Updating the content in an HTML document using jQuery

In my workflow, I am utilizing jquery ajax to retrieve information from a PHP file. data = <option>Peter</option><option>Maria</option> Following that, I aim to leverage jquery to insert this data after the initial option. <s ...

Strange Phenomenon in Node/Express.js: Vanishing Array Elements

My goal is to extract information from a database and store it in an array for further processing. However, I am facing an issue where the elements disappear after being added in a for-loop, resulting in an empty array. // PROBLEM: all_prices-elements dis ...

The issue with window.open failing to pass query strings in the URL to the backend

I am currently developing a node app with express, which allows users to send customized emails using html templates and nodemailer. The main functionality includes inputting the recipient's name, email, and selecting an email template. Everything is ...

Removing an HTML element entirely

Although I am utilizing .remove() method and it is effectively removing the desired element, upon inspecting the page source by right-clicking in a browser window, I can still see those removed elements. It seems like they are not being permanently delet ...

The assigned value of the computed property name does not match the specified type in Record

Whenever I attempt to set a value for a Record utilizing a computed property name, a type error is thrown: function Test<N extends string, M extends {}>(name: N, model: M) { const record: Record<N, M> = { [name]: model }; } The error messa ...

Failure in Retrieving Fresh Information via Ajax Call

My web application utilizes polling to constantly update the status of a music player. To achieve this, I have implemented a method using setInterval to execute an Ajax call every half second. This setup functions as intended on a variety of browsers inclu ...

Implementing a Click Event Listener in Amcharts Map Visualization

While working on a world map using am5charts in HTML/JS, I encountered an issue where modified countries seem to ignore the click event after "setAll". It appears that defining new attributes before the click event prevents me from accessing those variable ...

Is dart2js trying to compile CSS files?

It seems like the compiler dart2js is attempting to compile the CSS files from bootstrap. I tried searching online for a solution, but couldn't find any helpful information. I'm not really sure what keywords to use in my search. My previous proj ...

What is the process for setting data to the value attribute in an input tag, retrieved from a firebase database?

I utilized the following code snippet to retrieve data from Firebase database and store it in the Name variable. var userId = localStorage.getItem('keyName'); var dbRefName = firebase.database().ref() .child(& ...

Preventing redirection post-AJAX call using jQuery

Currently, I am attempting to implement a basic form submission using AJAX to send data to submit.php for database storage. However, upon submission, the page redirects to submit.php instead of staying on the current page. How can I make it submit without ...

Tips for modifying HTML elements using Javascript after a link is clicked

Imagine a scenario where there is a DIV called "videoplayer" containing an image within it. Is there a straightforward method to modify the HTML content inside this DIV when a link is clicked? For instance, the current content of the DIV is as follows: ...

Is it considered acceptable to incorporate my connection in all requests within NodeJS?

I currently have three files in my application: db.js, app.js, and commentController.js. I am continuously including the database connection in every request to avoid repeating the code. However, I am unsure if this approach is secure or if there is a bett ...

Utilizing Ajax Success Function with Distinct Div Element Identifiers

My question is a bit complex. I have a while loop that goes through an SQL query and displays all the articles found in the database. <div class='dislike_box'> <a href='#' class='counter'> <im ...

"Encountering a Challenge: Cannot Assign Array to ngFor Directive in Ionic App, Displaying

I have encountered an issue while fetching product categories using API. The problem lies in the fact that the categories are being retrieved as an object instead of an Array which is required for *ngFor to work in Ionic. Any assistance on how to define th ...

The error message "req.body undefined in NEXT JS" pops

Feeling lost and confused? I'm encountering an 'undefined' issue while attempting to upload my form data to Supabase. The data is being passed as undefined to the API, but when I inspect it within the submit handler, it displays correctly b ...

Error Message: "Issue with jQuery mobile: Uncaught TypeError - Unable to read property 'abort' of undefined during AJAX request"

Hey there, I recently created a website using jQuery Mobile and implemented the autocomplete feature. However, I encountered an error message saying Cannot read property 'abort' of undefined. Here is the code snippet: <div id="myPage"> ...

Angular 4 routerLink displaying incorrect component

I have set up my app-routing.module.ts with the following routes: const appRoutes: Routes = [ {path: '', component: MainComponent, children:[ {path: '', component: AppComponent, children:[ {path: 'home', component ...

Using jQuery to include Chinese characters in a request header

When making a jQuery post request, I need to set client information in the header. This is how my call looks: jQuery.ajax({ url : myURL, type : "POST", beforeSend : function(request){ request.setRequestHeader('someInfo', clie ...