By utilizing geocoordinates, arrange items in order of proximity to the individual's current location

Looking to organize an array based on the user's location in an AngularJS/ionic app. Specifically, the goal is to rank restaurants that are closest to the current user location

1/ Within my controller.js, I have the following code to retrieve the user's geocoordinates:

var onSuccess = function(position) {
    alert('Latitude: '          + position.coords.latitude          + '\n' +
          'Longitude: '         + position.coords.longitude         + '\n' +
          'Altitude: '          + position.coords.altitude          + '\n' +
          'Accuracy: '          + position.coords.accuracy          + '\n' +
          'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
          'Heading: '           + position.coords.heading           + '\n' +
          'Speed: '             + position.coords.speed             + '\n' +
          'Timestamp: '         + position.timestamp                + '\n');
    console.log(position.coords.latitude )
    console.log(position.coords.longitude)
};


    function onError(error) { // onError Callback receives a PositionError object
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);

2/ Using the following controller to list restaurants:

   // RESTAURANTLIST CONTROLLER
    .controller('restaurantlistController', function ($scope, $rootScope, restaurantsFactory) {
    "use strict";
    $scope.restaurantList = restaurantsFactory.getRestaurants(); 
})

3/ Restaurants are stored in a local factory:

 angular.module('wmapp.factory_restaurants', [])

.factory('restaurantsFactory', function () {
    "use strict";
    var factory = {
            Restaurants : [
                {Name: 'RestA', address: '45 Avenue Ledru-Rollin', cp: '75012', city: 'Paris', country: 'France', lat: 48.8482040, lng: 2.3706140, icon: 'local_icons.restaurantIcon'},
                {Name: 'RestB', address: '3 Rue Mansart', cp: '75009 ', city: 'Paris', country: 'France', lat: 48.8820390, lng: 2.3333150, icon: 'local_icons.restaurantIcon'},
                {Name: 'RestC', address: '41, rue Saint-André des Arts', cp: '75006', city: 'Paris', country: 'France', lat: 48.8532490, lng: 2.3409810, icon: 'local_icons.restaurantIcon'}

 // more restaurant 

            ],
            getRestaurants : function () {
                return factory.Restaurants;
            },
            getRestaurant : function (itemid) {
                var Restaurant = {};
                angular.forEach(factory.Restaurants, function (value, key) {
                    if (value.itemid === itemid) {
                        Restaurant = value;
                    }
                });
                return Restaurant;
            }
        };
    return factory;
});

4/ How can I arrange and display restaurants in my HTML based on proximity to the user (potentially showing distance in meters to the user's location)?

<ion-list>
  <ion-item ng-controller="loadingCtrl" bindonce ng-repeat="restaurant in restaurantList" href="#">

    <article class="item_frame">
        <img class="item_icon_circled" src="img/restauranticonv1redcircled.png">
        <h1 class="item_name_english2">{{restaurant.Name}}</h1>
        <span class="item_description">{{restaurant.subCuisine}}</span>
        <span class="item_description">{{restaurant.venueType}}</span>
        <span class="item_description">{{restaurant.subsubCuisine}}</span>
        <span class="item_description">{{restaurant.address}}</span>
        <span class="item_description">{{restaurant.cp}}</span>
        <span class="item_description">{{restaurant.city}}</span>
    </article><!--main article frame 1 -->  

  </ion-item>
</ion-list>

Answer №1

Discovered and successfully applied solution on Plunker

controller.js:

 var wmapp = angular.module('wmapp', ['wmapp.factory_restaurants','greatCircles'])

 // RESTAURANTLIST CONTROLLER
   .controller('restaurantlistController', function ($scope, $rootScope, restaurantsFactory,position,GreatCircle) {
    "use strict";
    $scope.restaurantList = restaurantsFactory.getRestaurants(); //calling the restaurantFactory
    $scope.position = position;

    $scope.distanceTo = function(restaurant) {
  var distance = GreatCircle.distance( restaurant.long,restaurant.lat, position.longitude, position.latitude)
  restaurant.distance = distance;
  distance = distance.toFixed(1);
  return distance;
}
})


.factory('position', function( $rootScope ){

    console.log('establishing position')

    var position = {};

      // 1ST / AUTO GEOLOCALIZATION OF USER 
      // shows a pop-up to indicate current user location - (disabled)
      // onSuccess Callback - This method accepts a Position object, which contains the current GPS coordinates
     var onSuccess = function(position2) {

          console.log(position2.coords.latitude )
          console.log(position2.coords.longitude)

          position.latitude = position2.coords.latitude;
          position.longitude = position2.coords.longitude;

          $rootScope.$digest()
      };

    function onError(error) { // onError Callback receives a PositionError object
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);

  return position;

})

Answer №2

1) Develop a JavaScript dining establishment class

2) Implement a distanceFrom(lat, long) function in the dining establishment class

3) Modify your factory to produce dining establishments instead of objects

4) Organize the collection of dining establishments using the distanceFrom function

function Restaurant(name, lat, long) {
    this.name = name;
    this.lat = lat;
    this.long = long;

    this.distanceFrom = function(long_from, lat_from) {
        return calculateDistanceBetween(this.lat, this.long, lat_from, long_from);
    }
}

example:

var myPosition = { lat: 50.0123, long: 49.4321 };
var someRestaurant = new Restaurant('The food', 51.1231, 48.213312);

var howFar = someRestaurant.distanceFrom(myPostion.lat, myPosition.long);

to view a JavaScript demonstration on calculating the distance between two sets of latitude/longitude coordinates, visit: Calculate distance between two latitude-longitude points? (Haversine formula)

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

Sending multiple objects using Ajax and fetching them in PHP

I'm facing an issue with posting a form and an array to my PHP script. My current approach involves using the following code: var json_data = JSON.stringify(data_vendor); //array to be posted $.ajax({ url: &ap ...

Utilizing jQuery.ajax() to retrieve the child div from a separate page

Can anyone help me figure out how to use jQuery ajax() to load two children contents from an external page? I want a pre-loader to display before the main content loads. Below is the code snippet that I have tried. $.ajax({ url: 'notification.htm ...

An issue arises even with the proper configuration in place: "SessionNotCreatedError: session cannot be established as Chrome version needs to fall within the range of 70 to 73."

During my automated testing with selenium-webdriver, I encountered an issue while building a driver using chromedriver. Everything was functioning perfectly until one day, when I ran a test and received the following error message: SessionNotCreatedErro ...

How to Target HTML Tags Locally using CSS Modules in Next.js?

I am looking to implement smooth scrolling specifically on one page in my Next.js application, such as my blog. Instead of applying it to the entire site through the globals.css file, I need a way to inject scroll-behavior: smooth; into the html tag only f ...

CSS: Unexpected value, received NaNrgb

I was attempting to incorporate a checkbox into a Bootstrap form that turns green when it is checked. Here is the code I used: function updateColor() { $("#check1").animate({ "background-color": "rgb(209, 231, 221)" }); } <script src="http ...

Refrain from showing content beneath a certain element

Is there a way to hide all content that appears after a specific element, such as a particular class of div? The issue I am facing involves using a 1&1 webpage builder with a restrictive layout-template enforced by my boss. I am trying to remove the foote ...

Data is not showing up in input fields in AngularJS ng-form after using ng-show

Currently, I'm developing a wizard-style view that hides different sections of a form to present the form in stages like a wizard. While navigating through the wizard and switching between steps, the model associated with the form gets updated. Howev ...

"Deactivate the escaping feature in PHP when using heredoc syntax

My PHP code generates minified JS output using the heredoc. Take a look at this snippet: function prerefresh(){$("#len").empty();predata.forEach(item)} I've highlighted that the {$ is causing issues with variable escaping in my heredoc. Is there a ...

What options do I have for sorting through my inventory using the search feature?

Having some trouble setting up isotope filtering on my search bar. I have managed to get the Isotope function working on checkboxes, but for some reason, my search bar isn't functioning as expected. I found a solution online for filtering results bas ...

How can I defer Tween.js animation in three.js until a button is specifically clicked?

I am trying to implement a tween animation for my camera in three.js that should only start when a specific object is clicked. This object can be within the scene or it could be a simple HTML button. The code snippet below demonstrates how the camera anima ...

increasing the size of an array in react javascript

componentWillMount(){ this.adjustOrder(); } componentDidMount(){} adjustOrder(){ var reorderedArray = []; this.state.reservation1.length = 9; for (var i = 0; i < this.state.reservation1.length; i++) { if(this.state.reservation1[i]){ r ...

Dealing with object properties that may not always be present in Vue.js template tags

Encountering a fatal error TypeError: Cannot read properties of null (reading 'propThatSometimesDoesNotExist') when utilizing the code below: <template> <div> <img v-if="obj.propThatSometimesDoesNotExist" :src=" ...

What is the best way to determine which section of a promise chain is responsible for an error in Javascript?

(Please excuse any errors in my English) I am currently studying JavaScript promises. Below is a simple JavaScript code snippet for node.js (using node.js version v10.0.0) that asynchronously reads and parses a JSON file using promise chaining. const fs ...

Fading in and out occurs several times while scrolling through the window

My goal is to update the logo image source with a fadeIn and fadeOut effect when scrolling up or down. The issue I'm facing is that the effect happens multiple times even after just one scroll, resulting in the logo flashing many times before finally ...

What steps do you need to take in order to transform this individual slideshow script into numerous slideshows

I came across this code online that effectively creates a slideshow. https://css-tricks.com/snippets/jquery/simple-auto-playing-slideshow/ Is there a way to modify the code to support multiple slideshows? I've made several attempts without success ...

Facing issues using Angular 5 for PUT requests due to 401 errors

When attempting to update data using the PUT Method in my angular service and express routes, I encountered a 401 error. Here is my service code: //401 makeAdmin(_id) { this.loadToken() let headers = new Headers() headers.append('Authorization& ...

Clicking on Fixed Positioning triggers a reset

When I activate the sidebar by clicking the menu button, it remains fixed in position until the first scroll. However, if I interact with the sidebar by clicking on it, the button resets and goes back to the top of the page. This issue seems to only occur ...

Allow only numerical values through an ion-input in Ionic 4, preventing the input of letters and special characters

I am currently developing an application in Ionic 4 that requires users to enter only integer numbers (0-9). I need to prevent any other characters such as alphabets, dots, or plus signs from being entered. However, the methods I have tried so far have not ...

Utilizing the props value for emission within the emits array: A guide

While attempting to list a custom event in the component's emits option, I encountered a console error. The code looked like this: PARENT <Btn event-name="toggleSideMenu" @toggle-side-menu="toggleHandler"> togg ...

Having trouble loading CSS and JavaScript files in CodeIgniter version 3.0.4?

I am facing an issue with loading my CSS and JS files in the view file. I have already added them to the folder and set the base URL. These codes were working fine with a project I previously did on an older version of CodeIgniter. What could be causing ...