title: Rails Mongoid geo_near sort by distance
body: <p>What I'm trying to do is to sort mongoid geo_near(or within_circle) max_distance results by distance because I don't know why but it doesn't do that by default. </p>
  
  <p>I have mongoid_geospatial, mongoid_spacial and rgeo in my Rails gem file. I know mongoid_spacial has this ability but I could not use it and it caused problems with gmaps4rails. </p>
  
  <p>I'm trying on mongoid_geospatial(which uses mongoid libraries) with no success and I could not find any resource except this one <a href="https://stackoverflow.com/questions/18633636/mongodb-aggregate-geonear-maxdistance">https://stackoverflow.com/questions/18633636/mongodb-aggregate-geonear-maxdistance</a> but I don't know how to convert mongo that to mongoid.</p>
  
  <p>Any one had an experience on sorting geo_near or within_circle in mongoid? Any help will be greatly appreciated.</p>
  
  <p><strong>The code in my Controller</strong></p>
  
  <pre><code>      searchterm = session[:categoryid].to_s
        radius = session[:distance].to_f / 10       
        @places = Provider.all.where(:category.to_s =&gt; /.*#{searchterm}.*/)
        .geo_near([ session[:latitude].to_f,session[:longitude].to_f ]).max_distance(radius)    
  
        #@places = Provider.all.where(:category.to_s =&gt; /.*#{searchterm}.*/)
        #.within_circle(location: [[ session[:latitude].to_f,session[:longitude].to_f ], radius ])      
        #.sort(:servicescore.desc).sort(:pricescore.desc)
  </code></pre>
  
  <p><strong>The code in my model</strong></p>
  
  <pre><code>include Mongoid::Document 
    include Mongoid::Timestamps
    include Mongoid::Paranoia
    include Mongoid::Geospatial
    include Mongoid::MultiParameterAttributes
    include Mongoid::Slug
    include Mongoid::Spacial::Document  
    include Gmaps4rails::ActsAsGmappable
    acts_as_gmappable :lat =&gt; 'latitude', :lon =&gt; 'longitude', :process_geocoding =&gt; true,
                      :check_process =&gt; :prevent_geocoding,
                      :address =&gt; "business_address"
    field :location, :type =&gt; Point
    spatial_index :location
    field :officialname
    field :business_description
    field :category#, :type =&gt; Array
    field :business_type
    field :tax_office
    field :tax_number
    field :pin  
    field :business_phone
    field :web_site
    field :business_address   
    field :latitude
    field :longitude
  </code></pre>
  
  <h2>-------------------------------------------------------------------------------</h2>
  
  <h2>-------------------------------------------------------------------------------</h2>
  
  <p><strong>EDIT ON QUESTION</strong></p>
  
  <p><img src="https://i.stack.imgur.com/3OVxH.png" alt="map"></p>
  
  <p>I've tried almost anything related without success.  Read mongo and mongoid geo_near documentation. It does comment on storing location [lon, lat] order. I've tried both [lon, lat] and [lat, long] both when saving the provider and for the center location. Tried spherical geo_near and within_circle too.  Still without success.
   Geo_near returns my results incorrectly ordered as seen on the map above and on the list below. There should be something I'm missing but can't find it.</p>
  
  <p>The red parts are the "geo_near_distance" output results, the list is sorted according to those but they are wrong as seen on the map. The green calculation is jquery code I've been using that returns correct distances(though cannot use in controller).</p>
  
  <p>There should be something I'm missing. Can anyone spot that? </p>
  
  <p><img src="https://i.stack.imgur.com/XkxhP.png" alt="results"></p>
  
  <p>here is my latest code:</p>
  
  <p>Provider.rb</p>
  
  <pre><code>  field :location, :type =&gt; Array  # [lat,lng]
    index({ location: "2d" }, { min: -180, max: 180 })
    spatial_index :location  
  </code></pre>
  
  <p>Providers_controller</p>
  
  <pre><code>  center = [session[:longitude].to_f, session[:latitude].to_f]
    radious = 100
    searchterm = session[:categoryid].to_s
    radius = session[:distance].to_f / 10     
    @places = Provider.all.where(:category.to_s =&gt; /.*#{searchterm}.*/)
    .geo_near(center).max_distance(radious)#.spherical
    #.near(location: center)
    #.within_circle( location: [center,radius] )
    #.sort(:geo_near_distance.desc)
    #.geo_near([ session[:latitude].to_f,session[:longitude].to_f ]).max_distance(100).spherical   
    #.unit("km")
    #.geo_near([ session[:latitude].to_f,session[:longitude].to_f ], max_distance: radius, unit: "km".to_sym, spherical: true).sort_by!{|r| r.geo[:distance] }
    #.geo_near([ session[:latitude].to_f,session[:longitude].to_f ]).max_distance(radius)   
    #.sort(:geo_near_distance)
  </code></pre>
  
  <p>JQuery for the green part</p>
  
  <pre><code> var p1 = new LatLon(Geo.parseDMS($('#lat1_{{id}}').val()), Geo.parseDMS($('#lon1_{{id}}').val()));
      var p2 = new LatLon(Geo.parseDMS($('#lat2_{{id}}').val()), Geo.parseDMS($('#lon2_{{id}}').val()));
      var new_number = parseFloat(p1.distanceTo(p2)).toFixed(2);
      $('#result-distance_{{id}}').html(new_number+' km');
  </code></pre>
  
  <p>Data for Provider</p>
  
  <pre><code>{ "_id" : ObjectId("5295ef0fdd5063ce1600002a"), "workdonecount" : 0, "pricescore" : 0, "servicescore" : 0, "_slugs" : [  "5295ef0fdd5063ce1600002a-1" ], "officialname" : "çeşme", "business_description" : "dsadsa", "category" : "5280ad334b315241af406c79", "business_type" : "Ticari", "tax_office" : "dads", "tax_number" : "dss", "pin" : "", "business_address" : "Balçova/İzmir, Türkiye", "latitude" : 38.3692939, "longitude" : 27.093442, "pink" : false, "hizmetkutusu_verified" : false, "user_id" : ObjectId("52946f54dd50636df6000002"), "location" : [  27.093441999999982,  38.3692939 ], "gmaps" : true, "updated_at" : ISODate("2013-11-27T13:09:36.214Z"), "created_at" : ISODate("2013-11-27T13:09:36.214Z") }
  { "_id" : ObjectId("5295f248dd5063ce16000030"), "workdonecount" : 0, "pricescore" : 0, "servicescore" : 0, "_slugs" : [  "5295f248dd5063ce16000030-1" ], "officialname" : "izmirdsads", "business_description" : "dsdsadsdsa", "category" : "5280ad334b315241af406c79", "business_type" : "Ticari", "tax_office" : "dasds", "tax_number" : "dadsa", "pin" : "", "business_address" : "Çeşme, Türkiye", "latitude" : 38.32980999999999, "longitude" : 26.3149209, "pink" : false, "hizmetkutusu_verified" : false, "user_id" : ObjectId("52946f54dd50636df6000002"), "location" : [  26.31492090000006,  38.32980999999999 ], "gmaps" : true, "updated_at" : ISODate("2013-11-27T13:23:20.423Z"), "created_at" : ISODate("2013-11-27T13:23:20.423Z") }
  { "_id" : ObjectId("5295f260dd5063ce16000032"), "workdonecount" : 0, "pricescore" : 0, "servicescore" : 0, "_slugs" : [  "5295f260dd5063ce16000032-1" ], "officialname" : "dsadsa", "business_description" : "dsadsa", "category" : "5280ad334b315241af406c79", "business_type" : "Ticari", "tax_office" : "dsadsa", "tax_number" : "dsads", "pin" : "", "business_address" : "Çiğli, 35580 İzmir, Türkiye", "latitude" : 38.496303, "longitude" : 27.0603911, "pink" : false, "hizmetkutusu_verified" : false, "user_id" : ObjectId("52946f54dd50636df6000002"), "location" : [  27.06039110000006,  38.496303 ], "gmaps" : true, "provider_image" : "gmaps1.jpg", "updated_at" : ISODate("2013-11-27T13:23:44.686Z"), "created_at" : ISODate("2013-11-27T13:23:44.686Z") }
  { "_id" : ObjectId("5295eee3dd5063ce16000026"), "workdonecount" : 0, "pricescore" : 0, "servicescore" : 0, "_slugs" : [  "5295eee3dd5063ce16000026-1" ], "officialname" : "dsdsa", "business_description" : "dadsa", "category" : "5280ad334b315241af406c79", "business_type" : "Ticari", "tax_office" : "dsa", "tax_number" : "dads", "pin" : "", "business_address" : "Buca, İzmir, Türkiye", "latitude" : 38.38813400000001, "longitude" : 27.1753358, "pink" : false, "hizmetkutusu_verified" : false, "user_id" : ObjectId("52946f54dd50636df6000002"), "location" : [  27.291124800000034,  38.3337361 ], "gmaps" : true, "updated_at" : ISODate("2013-11-27T13:08:51.544Z"), "created_at" : ISODate("2013-11-27T13:08:51.544Z") }
  { "_id" : ObjectId("5295eef5dd5063ce16000028"), "workdonecount" : 0, "pricescore" : 0, "servicescore" : 0, "_slugs" : [  "5295eef5dd5063ce16000028-1" ], "officialname" : "dsdsdsa", "business_description" : "dadsds", "category" : "5280ad334b315241af406c79", "business_type" : "Ticari", "tax_office" : "dasds", "tax_number" : "dadsa", "pin" : "", "business_address" : "Bornova, 35100 İzmir, Türkiye", "latitude" : 38.466414, "longitude" : 27.2192191, "pink" : false, "hizmetkutusu_verified" : false, "user_id" : ObjectId("52946f54dd50636df6000002"), "location" : [  27.219219100000032,  38.466414 ], "gmaps" : true, "updated_at" : ISODate("2013-11-27T13:09:10.122Z"), "created_at" : ISODate("2013-11-27T13:09:10.122Z") }
  </code></pre>