Skip to content

Commit

Permalink
Improve bus stops sort order in bus route page
Browse files Browse the repository at this point in the history
  • Loading branch information
yamamuteki committed Apr 29, 2016
1 parent c9e767a commit 4c9abdf
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 3 deletions.
3 changes: 2 additions & 1 deletion app/controllers/bus_routes_controller.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
class BusRoutesController < ApplicationController
def show
@bus_route = BusRoute.preload(:bus_route_tracks, bus_stops: [:bus_routes]).find(params[:id])
# Don't use preload for keeping bus stop order (Use fragment cache)
@bus_route = BusRoute.find(params[:id])
end
end
4 changes: 2 additions & 2 deletions app/models/bus_route.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
class BusRoute < ActiveRecord::Base
has_many :bus_route_tracks
has_many :bus_route_bus_stops
has_many :bus_stops, -> { order('name, latitude DESC') }, through: :bus_route_bus_stops
has_many :bus_route_bus_stops, -> { order(:bus_stop_number) }
has_many :bus_stops, through: :bus_route_bus_stops

enum bus_type: { private_bus: 1, public_bus: 2, community_bus: 3, demand_bus: 4, other: 5 }

Expand Down
27 changes: 27 additions & 0 deletions db/seeds.rb
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,34 @@ def load_bus_stops
end
end

def order_bus_stops
BusRouteBusStop.update_all(bus_stop_number: nil)

order_progress = ProgressBar.create(title: "Ordering", total: BusRoute.count, format: '%t: %J%% |%B|')
BusRoute.all.each do |bus_route|
index = 0
bus_route.bus_route_tracks.sort_by{|t| t.coordinates[0][1] }.each do |track|
track.coordinates.each do |coordinate|
latitude = coordinate[0]
longitude = coordinate[1]
bus_route.bus_route_bus_stops.each do |bus_route_bus_stop|
next if bus_route_bus_stop.bus_stop_number
bus_stop = bus_route_bus_stop.bus_stop
distance = (bus_stop.latitude - latitude) ** 2 + (bus_stop.longitude - longitude) ** 2
if distance < 0.000001 then
bus_route_bus_stop.bus_stop_number = index += 1
bus_route_bus_stop.save
break
end
end
end
end
order_progress.increment
end
end

ActiveRecord::Base.transaction do
load_bus_routes
load_bus_stops
order_bus_stops
end

0 comments on commit 4c9abdf

Please sign in to comment.