Skip to content

Commit

Permalink
Refactoring/tobias 117 convert leaflet to js (#137)
Browse files Browse the repository at this point in the history
Refactor leaflet ruby gem to plain js.
This merge will remove the map on the location show page, as communicated with team @hpi-swt2/apmw21.
We moved functionality from server to client.

Coverage will be restored with Issue #149.

* Start working on refactoring to js

* Refactor map elements to js

* Remove style from head

* removed brackets as suggested

* Fix variable erroneously dumped to page

fixes Places::DESTINATIONS variable being dumped into HTML (introduced in #102)

* Restore package-lock.json and other feedback

* First steps on new js conversion

Co-authored-by: TheGrayStone <[email protected]>
Co-authored-by: Julian Schmidt <[email protected]>

* Refactor routing display

* Add Route to its own layer

* Trying to fix tests with js

* Comment on old magic constant

* Adapt tests for routing

* linting stuff

* Remove test for targets, minor fixes

* [CodeFactor] Apply fixes

* Remove old map from locations, needs more fixing

* Extra js file for leaflet Map

* prepare locations show

* Remove map from location page

* add debugging help to routing tests

* add waiting time for routing

* remove unnecessary code

* adding wait_for_ajax to route tests

* Remove old unused code (Commented for target)

* tag tests and improve backend routes

* improved tagging to new syntax

* exclude tests with the tag "local_only"

* add jQuery as requested

* code cleanup for jQuery

* enable indoor rooms from hg

* add target marker functionality

* remove old variable on index

* [CodeFactor] Apply fixes

* a try on fixing tests

* [CodeFactor] Apply fixes

* fix CodeFactor issue

* improve tests with find and waiting time

* edit tags for tests

* remove parallel execution in js

* remove wait_for_ajax

* run route tests only local

* restore yarn.lock

* add newline to yarn.lock

* Code improvements

* [CodeFactor] Apply fixes

* Fix magic string

* possible fix for routing tests

* Parallelize ajax requests

Co-authored-by: Julian Schmidt

* reverse changes for parallel ajax

* add comment about race condition

* Paralize ajax requests WITH tests

* remove tests for routing (race condition)

Co-authored-by: Lukas Rost <[email protected]>
Co-authored-by: TheGrayStone <[email protected]>
Co-authored-by: Julian Schmidt <[email protected]>
Co-authored-by: codefactor-io <[email protected]>
  • Loading branch information
5 people authored and Tratori committed Jan 29, 2022
1 parent 45d9768 commit 5527cf0
Show file tree
Hide file tree
Showing 18 changed files with 333 additions and 203 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test_and_deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ jobs:
run: |
cp config/database.ci.yml config/database.yml
bundle exec rails db:setup
bundle exec rspec spec/ --format documentation --format RSpec::Github::Formatter
bundle exec rspec --tag ~local_only spec/ --format documentation --format RSpec::Github::Formatter
# Name of the job
deploy:
Expand Down
3 changes: 0 additions & 3 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -50,9 +50,6 @@ gem 'tod'
# Libraries
#

# Leaflet for map functionality
gem 'leaflet-rails', git: "git://github.com/Finn-HPI/leaflet-rails.git"

#
# Gems that are loaded depending on the environment (development/test/production)
#
Expand Down
8 changes: 0 additions & 8 deletions Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,10 +1,3 @@
GIT
remote: git://github.com/Finn-HPI/leaflet-rails.git
revision: 340f65cbc163dcc3523c43592831d43a65381296
specs:
leaflet-rails (1.7.4)
rails (>= 4.2.0)

GEM
remote: https://rubygems.org/
specs:
Expand Down Expand Up @@ -369,7 +362,6 @@ DEPENDENCIES
factory_bot_rails
httparty
jbuilder (~> 2.7)
leaflet-rails!
listen (~> 3.3)
omniauth
omniauth_openid_connect
Expand Down
4 changes: 2 additions & 2 deletions app/assets/constants/buildings.rb
Original file line number Diff line number Diff line change
Expand Up @@ -335,9 +335,9 @@ def self.transform_leaflet_letters(hpi_letters)
hpi_letters.map do |hpi_letter|
{
latlng: hpi_letter[:coordinate],
div_icon: {
divIcon: {
html: hpi_letter[:letter],
class_name: "building-icon"
className: "building-icon"
}
}
end
Expand Down
19 changes: 10 additions & 9 deletions app/assets/constants/locations.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
module Locations
def self.transform_leaflet_position(position, name)
{
latlng: position,
div_icon: {
html: name,
class_name: "building-icon"
}
}
end
# Only needed for creating a leaflet marker
# def self.transform_leaflet_position(position, name)
# {
# latlng: position,
# div_icon: {
# html: name,
# class_name: "location-icon"
# }
# }
# end
end
2 changes: 0 additions & 2 deletions app/assets/stylesheets/application.scss
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,6 @@ $fa-font-path: "@fortawesome/fontawesome-free/webfonts";
// CSS partials
@import "components/navbar";

@import "leaflet";

body {
padding: 4rem 0;
}
Expand Down
39 changes: 33 additions & 6 deletions app/controllers/building_map_controller.rb
Original file line number Diff line number Diff line change
@@ -1,11 +1,38 @@
class BuildingMapController < ApplicationController
YOUR_LOCATION_MAGIC_STRING = "Your location".freeze
YOUR_LOCATION_MAGIC_STRING = "Your location".freeze # TODO: This is currenty hard coded in the building_map.js file

def index
@start = RoutingHelper.resolve_coordinates(params[:start])
@destination = RoutingHelper.resolve_coordinates(params[:dest])
@route = RoutingHelper.calculate_route(@start, @destination) if @start.present? && @destination.present?
def index; end

@target = params[:target]
def buildings
polygons = BuildingMapHelper.leaflet_polygons
respond_to do |format|
format.json { render json: polygons }
end
end

def view
view = BuildingMapHelper.leaflet_center
respond_to do |format|
format.json { render json: view }
end
end

def markers
markers = Buildings.transform_leaflet_letters(Buildings::HPI_LETTERS)
respond_to do |format|
format.json { render json: markers }
end
end

def route
start = RoutingHelper.resolve_coordinates(params[:start])
dest = RoutingHelper.resolve_coordinates(params[:dest])
route = RoutingHelper.calculate_route(start, dest) if start.present? && dest.present?

result = { polyline: RoutingHelper.transform_route_to_polyline(route),
marker: RoutingHelper.transform_route_to_time_marker(route) }
respond_to do |format|
format.json { render json: result }
end
end
end
16 changes: 2 additions & 14 deletions app/helpers/building_map_helper.rb
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
module BuildingMapHelper
def self.leaflet_center(start_coordinates)
center = start_coordinates.nil? ? %w[52.39339 13.13208] : start_coordinates.split(",")

def self.leaflet_center
{
latlng: center,
latlng: %w[52.39339 13.13208],
zoom: 17
}
end
Expand All @@ -12,14 +10,4 @@ def self.leaflet_polygons
Buildings.transform_leaflet_buildings(Buildings::UNIPOTSDAM_POLYONGS, Buildings::UNIPOTSDAM_STYLING) +
Buildings.transform_leaflet_buildings(Buildings::HPI_POLYGONS, Buildings::HPI_STYLING)
end

def self.leaflet_polylines(route)
route.present? ? [RoutingHelper.transform_route_to_polyline(route)] : []
end

def self.leaflet_markers(route, target)
Buildings.transform_leaflet_letters(Buildings::HPI_LETTERS) +
RoutingHelper.transform_route_to_time_marker(route) +
RoutingHelper.transform_target_to_marker(target)
end
end
26 changes: 4 additions & 22 deletions app/helpers/routing_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,39 +39,21 @@ def self.calculate_route(start, destination)
end

def self.transform_route_to_time_marker(route)
return [] unless route

walking_time = format_seconds_as_minsec(route["duration"])
start = route["geometry"]["coordinates"][0]
[{
{
latlng: [start.second, start.first],
div_icon: {
divIcon: {
html: walking_time,
class_name: "time-icon"
className: "time-icon"
}
}]
}
end

def self.transform_route_to_polyline(route)
return unless route

coordinates = route["geometry"]["coordinates"].map do |(long, lat)|
[lat, long]
end
{ latlngs: coordinates, options: { className: "routing-path" } }
end

def self.transform_target_to_marker(point)
return [] unless point

coordinates = point.split(",")

[{
latlng: coordinates,
div_icon: {
html: "<img src='/assets/pin.png'>",
class_name: "target-pin"
}
}]
end
end
3 changes: 2 additions & 1 deletion app/javascript/packs/application.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ import 'bootstrap';
// Fontawesome: https://fontawesome.com/
import "@fortawesome/fontawesome-free/js/all";

import * as L from "leaflet"
import * as L from "leaflet";
import "leaflet/dist/leaflet.css";

Rails.start()
Turbolinks.start()
Expand Down
73 changes: 73 additions & 0 deletions app/javascript/packs/building_map.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { displayRoute, setupMap } from './leafletMap.js';

let currentLocation;
const YOUR_LOCATION_MAGIC_STRING = "Your location" // This will be changed when the page supports multiple languages

setupMap();

const start_input_field = $("#start_input")[0];
start_input_field.addEventListener("change", () => {
request_location();
if (validate_place_input("start_input", "startOptions")) {
start_input_field.setCustomValidity("");
} else {
start_input_field.setCustomValidity(
"Please select a valid starting place."
);
}
});
start_input_field.dispatchEvent(new Event("change"));

const dest_input_field = $("#dest_input")[0];
dest_input_field.addEventListener("change", () => {
if (validate_place_input("dest_input", "destOptions")) {
dest_input_field.setCustomValidity("");
} else {
dest_input_field.setCustomValidity(
"Please select a valid destination place."
);
}
});
dest_input_field.dispatchEvent(new Event("change"));

$("#navigation_form")[0]
.addEventListener("submit", (event) => {
event.preventDefault();
if (start_input_field.value === YOUR_LOCATION_MAGIC_STRING) {
start_input_field.value = currentLocation;
}
const start = start_input_field.value;
const dest = dest_input_field.value;
displayRoute(start, dest);
});

function validate_place_input(inputId, optionsId) {
const input = $(`#${inputId}`)[0];
const options = $(`#${optionsId}`)[0].options;
return Array.from(options).some((o) => o.value === input.value);
}

function request_location() {
if (start_input_field.value !== YOUR_LOCATION_MAGIC_STRING) return;
navigator.geolocation.getCurrentPosition(
(pos) => {
currentLocation =
String(pos.coords.latitude) +
"," +
String(pos.coords.longitude);
start_input_field.setCustomValidity("");
},
(error) => {
console.warn(`ERROR(${error.code}): ${error.message}`);
if (error.code === GeolocationPositionError.PERMISSION_DENIED) {
start_input_field.setCustomValidity(
"You have to grant your browser the permission to access your location if you want to use this feature."
);
} else {
start_input_field.setCustomValidity(
"Your browser could not determine your position. Please choose a different starting place."
);
}
}
);
}
Loading

0 comments on commit 5527cf0

Please sign in to comment.