使用地理坐标,将对象排序靠近用户的位置

时间:2015-04-02 12:37:04

标签: javascript angularjs geolocation ionic-framework geocoding

我想根据用户在AngularJS /离子应用程序中的位置来排序数组。更准确地说,这个想法是对最接近当前用户位置的餐馆进行排名

1 /在我的controller.js中,我有以下代码来获取用户当前的地理坐标:

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 /我使用以下控制器显示餐馆列表:

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

3 /餐馆存放在当地工厂:

 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 /问题:如何在我的HTML餐馆中排名和显示最接近用户的位置(可能表示以米为单位的距离与用户的位置?)

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

2 个答案:

答案 0 :(得分:1)

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;

})

答案 1 :(得分:0)

1)创建一个javascript restaurant

2)给餐馆班一个distanceFrom(lat, long)功能

3)调整工厂以返回restaurant而不是object s

4)restaurant函数

distanceFrom s的排序列表
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);
    }
}

用法:

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

获取两个纬度/逻辑对之间距离的javascript示例,请参见此处:Calculate distance between two latitude-longitude points? (Haversine formula)