0

I want to sort out an array according to the user's location in an AngularJS/ionic app. More precisely, the idea is to rank restaurants that would be the closest to the current user location

1/ in my controller.js, I have the following code that gets the user's current geocordinates :

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/ I use the following controller to display a list of 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/ Question: How do I rank and display in my HTML restaurants by closest to the user (possibly indicating 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>
lauWM
  • 659
  • 3
  • 10
  • 18

2 Answers2

1

Found and implemented 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(); //call to 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('building position')

    var position = {};

      // 1ST / AUTO GEOLOCATION OF USER 
      // displays a popup 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;

})
lauWM
  • 659
  • 3
  • 10
  • 18
0

1) create a javascript restaurant class

2) give the restaurant class a distanceFrom(lat, long) function

3) adapt your factory to return restaurants rather than objects

4) sort list of restaurants by 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);
    }
}

usage:

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);

for a javascript sample of getting distance between two latitude/ logitude pairs, see here: Calculate distance between two latitude-longitude points? (Haversine formula)

Community
  • 1
  • 1
paul
  • 21,653
  • 1
  • 53
  • 54
  • wow... how i'll do this ? ok thanks for guidance, will give it a go – lauWM Apr 02 '15 at 12:50
  • Thanks Paul for thoses details, sounds like something I could be able to implement! will let you know – lauWM Apr 02 '15 at 14:46
  • I am just trying to get the code work on a codepen, but beeing new in JS, I might miss something, would you mind having a look ? http://codepen.io/anon/pen/wBZRmv – lauWM Apr 03 '15 at 08:30
  • you have to implement `calculateDistanceBetween`, there is a link to an example of how to do this at the end of my answer – paul Apr 03 '15 at 09:31