inherit_from: .rubocop_todo.yml
+require:
+ - rubocop-performance
+ - rubocop-rails
+
AllCops:
TargetRubyVersion: 2.5
- 'app/controllers/application_controller.rb'
- 'app/controllers/site_controller.rb'
+Metrics/BlockLength:
+ Exclude:
+ - 'config/routes.rb'
+
Naming/FileName:
Exclude:
- 'script/deliver-message'
# This configuration was generated by
# `rubocop --auto-gen-config`
-# on 2018-09-19 14:24:02 +0100 using RuboCop version 0.58.2.
+# on 2019-06-05 09:04:25 +0100 using RuboCop version 0.71.0.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.
-# Offense count: 32
+# Offense count: 33
# Configuration parameters: AllowSafeAssignment.
Lint/AssignmentInCondition:
Exclude:
+ - 'app/controllers/api/traces_controller.rb'
+ - 'app/controllers/api/user_preferences_controller.rb'
- 'app/controllers/application_controller.rb'
- 'app/controllers/geocoder_controller.rb'
- 'app/controllers/notes_controller.rb'
- - 'app/controllers/api/traces_controller.rb'
- 'app/controllers/traces_controller.rb'
- 'app/controllers/users_controller.rb'
- - 'app/controllers/api/user_preferences_controller.rb'
- 'app/helpers/application_helper.rb'
- - 'app/helpers/browse_helper.rb'
- 'app/helpers/browse_tags_helper.rb'
- - 'app/models/client_application.rb'
- 'app/mailers/notifier.rb'
+ - 'app/models/client_application.rb'
- 'lib/nominatim.rb'
- 'lib/osm.rb'
- 'script/deliver-message'
# Offense count: 4
+# Configuration parameters: AllowComments.
Lint/HandleExceptions:
Exclude:
- 'app/controllers/api/amf_controller.rb'
- 'app/controllers/users_controller.rb'
-# Offense count: 692
+# Offense count: 703
Metrics/AbcSize:
- Max: 283
+ Max: 279
# Offense count: 40
# Configuration parameters: CountComments, ExcludedMethods.
# ExcludedMethods: refine
Metrics/BlockLength:
- Max: 262
+ Max: 71
-# Offense count: 11
+# Offense count: 15
# Configuration parameters: CountBlocks.
Metrics/BlockNesting:
Max: 5
-# Offense count: 63
+# Offense count: 68
# Configuration parameters: CountComments.
Metrics/ClassLength:
- Max: 1627
+ Max: 1397
-# Offense count: 72
+# Offense count: 73
Metrics/CyclomaticComplexity:
- Max: 23
+ Max: 22
-# Offense count: 691
-# Configuration parameters: CountComments.
+# Offense count: 714
+# Configuration parameters: CountComments, ExcludedMethods.
Metrics/MethodLength:
Max: 179
-# Offense count: 2
+# Offense count: 1
# Configuration parameters: CountComments.
Metrics/ModuleLength:
- Max: 135
+ Max: 107
# Offense count: 4
# Configuration parameters: CountKeywordArgs.
Metrics/ParameterLists:
Max: 9
-# Offense count: 72
+# Offense count: 71
Metrics/PerceivedComplexity:
- Max: 23
+ Max: 25
# Offense count: 6
Naming/AccessorMethodName:
- 'db/migrate/20120208194454_add_domain_to_acl.rb'
- 'db/migrate/20120404205604_add_user_and_description_to_redaction.rb'
-# Offense count: 2
-# Configuration parameters: Include.
-# Include: app/**/*.rb, config/**/*.rb, lib/**/*.rb
-Rails/Exit:
- Exclude:
- - 'lib/**/*.rake'
- - 'lib/daemons/gpx_import.rb'
-
# Offense count: 2
# Configuration parameters: Include.
# Include: app/models/**/*.rb
- 'app/models/changeset.rb'
- 'app/models/user.rb'
+# Offense count: 11
+# Configuration parameters: Include.
+# Include: app/helpers/**/*.rb
+Rails/HelperInstanceVariable:
+ Exclude:
+ - 'app/helpers/application_helper.rb'
+ - 'app/helpers/title_helper.rb'
+ - 'app/helpers/trace_helper.rb'
+
# Offense count: 5
# Configuration parameters: Include.
# Include: db/migrate/*.rb
- 'db/migrate/025_add_end_time_to_changesets.rb'
- 'db/migrate/20120404205604_add_user_and_description_to_redaction.rb'
-# Offense count: 20
+# Offense count: 18
Rails/OutputSafety:
Exclude:
- 'app/controllers/users_controller.rb'
- 'app/helpers/note_helper.rb'
- 'app/helpers/open_graph_helper.rb'
- 'app/helpers/user_blocks_helper.rb'
- - 'app/helpers/user_roles_helper.rb'
- 'lib/rich_text.rb'
- 'test/helpers/application_helper_test.rb'
-# Offense count: 86
+# Offense count: 94
+# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
# SupportedStyles: strict, flexible
Rails/TimeZone:
Exclude:
- 'test/models/message_test.rb'
-# Offense count: 230
+# Offense count: 255
Style/Documentation:
Enabled: false
-# Offense count: 462
+# Offense count: 503
# Cop supports --auto-correct.
# Configuration parameters: EnforcedStyle.
-# SupportedStyles: when_needed, always, never
+# SupportedStyles: always, never
Style/FrozenStringLiteralComment:
Enabled: false
Exclude:
- 'app/controllers/api/ways_controller.rb'
-# Offense count: 70
+# Offense count: 74
# Cop supports --auto-correct.
# Configuration parameters: Strict.
Style/NumericLiterals:
MinDigits: 11
-# Offense count: 3080
-# Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
+# Offense count: 3320
+# Cop supports --auto-correct.
+# Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
# URISchemes: http, https
Metrics/LineLength:
Max: 1073
-sudo: false
+dist: xenial
language: ruby
rvm:
- - 2.5.1
-cache: bundler
+ - 2.5.3
+cache:
+ - bundler
addons:
postgresql: 9.5
apt:
global:
- OSM_MEMCACHE_SERVERS="127.0.0.1"
before_script:
+ - sed -e "/idle_in_transaction_session_timeout/d" -e 's/ IMMUTABLE / /' -e "s/AS '.*libpgosm.*',/AS 'libpgosm',/" -e "/^--/d" db/structure.sql > db/structure.expected
- psql -U postgres -c "CREATE DATABASE openstreetmap"
- psql -U postgres -c "CREATE EXTENSION btree_gist" openstreetmap
- make -C db/functions libpgosm.so
- bundle exec rake i18n:js:export
script:
- bundle exec rubocop -f fuubar
- - bundle exec rake jshint
+ - bundle exec rake eslint:run_all
- bundle exec erblint .
+ - bundle exec rake db:structure:dump
+ - sed -e "/idle_in_transaction_session_timeout/d" -e 's/ IMMUTABLE / /' -e "s/AS '.*libpgosm.*',/AS 'libpgosm',/" -e "/^--/d" db/structure.sql > db/structure.actual
+ - diff -uw db/structure.expected db/structure.actual
- bundle exec rake test:db
gem "json"
# Use postgres as the database
-gem "pg", "~> 0.18"
+gem "pg"
# Use SCSS for stylesheets
gem "sassc-rails"
gem "rack-cors"
gem "rails-i18n", "~> 4.0.0"
gem "record_tag_helper"
-gem "rinku", "= 2.0.4", :require => "rails_rinku"
+gem "rinku", ">= 2.0.6", :require => "rails_rinku"
+gem "strong_migrations"
gem "validates_email_format_of", ">= 1.5.1"
# Native OSM extensions
gem "minitest", "~> 5.1", :platforms => [:ruby_19, :ruby_20]
gem "rails-controller-testing"
gem "rubocop"
+ gem "rubocop-performance"
+ gem "rubocop-rails"
gem "webmock"
end
gem "capybara", "~> 2.13"
gem "coveralls", :require => false
gem "erb_lint", :require => false
+ gem "eslint-rails-ee"
+ gem "execjs"
gem "factory_bot_rails"
- gem "jshint"
gem "poltergeist"
gem "puma", "~> 3.7"
+ gem "therubyracer", :platforms => :ruby
end
remote: https://rubygems.org/
specs:
SystemTimer (1.2.3)
- aasm (5.0.2)
+ aasm (5.0.5)
concurrent-ruby (~> 1.0)
actioncable (5.2.3)
actionpack (= 5.2.3)
activemodel (= 5.2.3)
activesupport (= 5.2.3)
arel (>= 9.0)
- activerecord-import (1.0.1)
+ activerecord-import (1.0.2)
activerecord (>= 3.2)
activestorage (5.2.3)
actionpack (= 5.2.3)
tzinfo (~> 1.1)
addressable (2.6.0)
public_suffix (>= 2.0.2, < 4.0)
- annotate (2.7.4)
- activerecord (>= 3.2, < 6.0)
+ annotate (2.7.5)
+ activerecord (>= 3.2, < 7.0)
rake (>= 10.4, < 13.0)
arel (9.0.0)
ast (2.4.0)
bigdecimal (1.1.0)
binding_of_caller (0.8.0)
debug_inspector (>= 0.0.1)
- bootsnap (1.4.2)
+ bootsnap (1.4.4)
msgpack (~> 1.0)
browser (2.5.3)
builder (3.2.3)
- cancancan (2.3.0)
+ cancancan (3.0.1)
canonical-rails (0.2.5)
rails (>= 4.1, < 6.1)
capybara (2.18.0)
coffee-script-source
execjs
coffee-script-source (1.12.2)
+ colorize (0.8.1)
composite_primary_keys (11.1.0)
activerecord (~> 5.2.1)
concurrent-ruby (1.1.5)
activesupport (>= 3.0)
deep_merge (~> 1.2.1)
dry-validation (>= 0.12.2)
- coveralls (0.8.22)
+ coveralls (0.8.23)
json (>= 1.8, < 3)
simplecov (~> 0.16.1)
term-ansicolor (~> 1.3)
- thor (~> 0.19.4)
+ thor (>= 0.19.4, < 2.0)
tins (~> 1.6)
crack (0.4.3)
safe_yaml (~> 1.0.0)
activerecord (>= 3.0, < 5.3)
delayed_job (>= 3.0, < 5)
docile (1.3.1)
- dry-configurable (0.8.2)
+ dry-configurable (0.8.3)
concurrent-ruby (~> 1.0)
dry-core (~> 0.4, >= 0.4.7)
dry-container (0.7.0)
concurrent-ruby (~> 1.0)
dry-equalizer (0.2.2)
dry-inflector (0.1.2)
- dry-logic (0.5.0)
- dry-container (~> 0.2, >= 0.2.6)
+ dry-logic (0.6.1)
+ concurrent-ruby (~> 1.0)
dry-core (~> 0.2)
dry-equalizer (~> 0.2)
dry-types (0.14.1)
dry-equalizer (~> 0.2)
dry-inflector (~> 0.1, >= 0.1.2)
dry-logic (~> 0.5, >= 0.5)
- dry-validation (0.13.1)
+ dry-validation (0.13.3)
concurrent-ruby (~> 1.0)
dry-configurable (~> 0.1, >= 0.1.3)
dry-core (~> 0.2, >= 0.2.1)
rubocop (~> 0.51)
smart_properties
erubi (1.8.0)
+ eslint-rails-ee (1.0.2)
+ colorize
+ execjs
+ railties (>= 3.2)
execjs (2.7.0)
exifr (1.3.6)
factory_bot (5.0.2)
activesupport (>= 4.2.0)
- factory_bot_rails (5.0.1)
- factory_bot (~> 5.0.0)
+ factory_bot_rails (5.0.2)
+ factory_bot (~> 5.0.2)
railties (>= 4.2.0)
- fakefs (0.20.0)
+ fakefs (0.20.1)
faraday (0.15.4)
multipart-post (>= 1.2, < 3)
- ffi (1.10.0)
- fspath (3.1.0)
+ ffi (1.11.1)
+ fspath (3.1.1)
gd2-ffij (0.4.0)
ffi (>= 1.0.0)
geoip (1.6.4)
globalid (0.4.2)
activesupport (>= 4.2.0)
- hashdiff (0.3.8)
+ hashdiff (0.4.0)
hashie (3.6.0)
html_tokenizer (0.0.7)
htmlentities (4.3.4)
http_accept_language (2.0.5)
i18n (0.9.5)
concurrent-ruby (~> 1.0)
- i18n-js (3.2.1)
+ i18n-js (3.2.3)
i18n (>= 0.6.6)
- image_optim (0.26.3)
+ image_optim (0.26.4)
exifr (~> 1.2, >= 1.2.2)
fspath (~> 3.0)
image_size (>= 1.5, < 3)
in_threads (~> 1.3)
progress (~> 3.0, >= 3.0.1)
- image_optim_rails (0.4.1)
+ image_optim_rails (0.4.2)
image_optim (~> 0.24)
rails
sprockets
- image_size (2.0.0)
- in_threads (1.5.1)
+ image_size (2.0.1)
+ in_threads (1.5.2)
jaro_winkler (1.5.2)
jquery-rails (4.3.3)
rails-dom-testing (>= 1, < 3)
railties (>= 4.2.0)
thor (>= 0.14, < 2.0)
- jshint (1.5.0)
- execjs (>= 1.4.0)
- multi_json (~> 1.0)
- therubyracer (~> 0.12.1)
json (2.2.0)
jsonify (0.3.1)
multi_json (~> 1.0)
jsonify-rails (0.3.2)
actionpack
jsonify (< 0.4.0)
- jwt (2.1.0)
+ jwt (2.2.1)
kgio (2.11.2)
kramdown (2.1.0)
libv8 (3.16.14.19)
method_source (0.9.2)
mime-types (3.2.2)
mime-types-data (~> 3.2015)
- mime-types-data (3.2018.0812)
+ mime-types-data (3.2019.0331)
mimemagic (0.3.3)
mini_mime (1.0.1)
mini_portile2 (2.4.0)
minitest (5.11.3)
- msgpack (1.2.9)
+ msgpack (1.2.10)
multi_json (1.13.1)
multi_xml (0.6.0)
- multipart-post (2.0.0)
+ multipart-post (2.1.1)
nio4r (2.3.1)
- nokogiri (1.10.2)
+ nokogiri (1.10.3)
mini_portile2 (~> 2.4.0)
nokogumbo (2.0.1)
nokogiri (~> 1.8, >= 1.8.4)
omniauth-github (1.3.0)
omniauth (~> 1.5)
omniauth-oauth2 (>= 1.4.0, < 2.0)
- omniauth-google-oauth2 (0.6.1)
+ omniauth-google-oauth2 (0.7.0)
jwt (>= 2.0)
omniauth (>= 1.1.1)
omniauth-oauth2 (>= 1.5)
mime-types
mimemagic (~> 0.3.0)
terrapin (~> 0.6.0)
- parallel (1.16.0)
- parser (2.6.2.0)
+ parallel (1.17.0)
+ parser (2.6.3.0)
ast (~> 2.4.0)
- pg (0.21.0)
+ pg (1.1.4)
poltergeist (1.18.1)
capybara (>= 2.1, < 4)
cliver (~> 0.3.1)
websocket-driver (>= 0.2.0)
- progress (3.5.0)
+ progress (3.5.1)
psych (3.1.0)
- public_suffix (3.0.3)
+ public_suffix (3.1.0)
puma (3.12.1)
quad_tile (1.0.1)
r2 (0.2.7)
- rack (2.0.6)
+ rack (2.0.7)
rack-cors (1.0.3)
rack-openid (1.3.1)
rack (>= 1.1.0)
ref (2.0.0)
request_store (1.4.1)
rack (>= 1.4)
- rinku (2.0.4)
- rotp (4.1.0)
+ rinku (2.0.6)
+ rotp (5.0.0)
addressable (~> 2.5)
- rubocop (0.66.0)
+ rubocop (0.71.0)
jaro_winkler (~> 1.5.1)
parallel (~> 1.10)
- parser (>= 2.5, != 2.5.1.1)
- psych (>= 3.1.0)
+ parser (>= 2.6)
rainbow (>= 2.2.2, < 4.0)
ruby-progressbar (~> 1.7)
- unicode-display_width (>= 1.4.0, < 1.6)
+ unicode-display_width (>= 1.4.0, < 1.7)
+ rubocop-performance (1.3.0)
+ rubocop (>= 0.68.0)
+ rubocop-rails (2.0.0)
+ rack (>= 2.0)
+ rubocop (>= 0.70.0)
ruby-openid (2.7.0)
- ruby-progressbar (1.10.0)
+ ruby-progressbar (1.10.1)
ruby_dep (1.5.0)
safe_yaml (1.0.5)
sanitize (5.0.0)
sassc (2.0.1)
ffi (~> 1.9)
rake
- sassc-rails (2.1.0)
+ sassc-rails (2.1.1)
railties (>= 4.0.0)
sassc (>= 2.0)
sprockets (> 3.0)
json (>= 1.8, < 3)
simplecov-html (~> 0.10.0)
simplecov-html (0.10.2)
- smart_properties (1.13.1)
+ smart_properties (1.14.0)
sprockets (3.7.2)
concurrent-ruby (~> 1.0)
rack (> 1, < 3)
actionpack (>= 4.0)
activesupport (>= 4.0)
sprockets (>= 3.0.0)
+ strong_migrations (0.4.0)
+ activerecord (>= 5)
term-ansicolor (1.7.1)
tins (~> 1.0)
terrapin (0.6.0)
therubyracer (0.12.3)
libv8 (~> 3.16.14.15)
ref
- thor (0.19.4)
+ thor (0.20.3)
thread_safe (0.3.6)
tilt (2.0.9)
- tins (1.20.2)
+ tins (1.20.3)
tzinfo (1.2.5)
thread_safe (~> 0.1)
uglifier (4.1.20)
execjs (>= 0.3.0, < 3)
- unicode-display_width (1.5.0)
+ unicode-display_width (1.6.0)
validates_email_format_of (1.6.3)
i18n
vendorer (0.2.0)
- webmock (3.5.1)
+ webmock (3.6.0)
addressable (>= 2.3.6)
crack (>= 0.3.2)
- hashdiff
+ hashdiff (>= 0.4.0, < 2.0.0)
websocket-driver (0.7.0)
websocket-extensions (>= 0.1.0)
websocket-extensions (0.1.3)
delayed_job_active_record
dynamic_form
erb_lint
+ eslint-rails-ee
+ execjs
factory_bot_rails
fakefs
faraday
i18n-js (>= 3.0.0)
image_optim_rails
jquery-rails
- jshint
json
jsonify-rails
kgio
omniauth-windowslive
openstreetmap-deadlock_retry (>= 1.3.0)
paperclip (~> 5.2)
- pg (~> 0.18)
+ pg
poltergeist
psych
puma (~> 3.7)
rails-controller-testing
rails-i18n (~> 4.0.0)
record_tag_helper
- rinku (= 2.0.4)
+ rinku (>= 2.0.6)
rotp
rubocop
+ rubocop-performance
+ rubocop-rails
sanitize
sassc-rails
secure_headers
+ strong_migrations
+ therubyracer
uglifier (>= 1.3.0)
validates_email_format_of (>= 1.5.1)
vendorer
end
folder 'leaflet' do
- file 'leaflet.js', 'https://unpkg.com/leaflet@1.4.0/dist/leaflet-src.js'
- file 'leaflet.css', 'https://unpkg.com/leaflet@1.4.0/dist/leaflet.css'
+ file 'leaflet.js', 'https://unpkg.com/leaflet@1.5.1/dist/leaflet-src.js'
+ file 'leaflet.css', 'https://unpkg.com/leaflet@1.5.1/dist/leaflet.css'
[ 'layers.png', 'layers-2x.png',
'marker-icon.png', 'marker-icon-2x.png',
'marker-shadow.png' ].each do |image|
- file "images/#{image}", "https://unpkg.com/leaflet@1.4.0/dist/images/#{image}"
+ file "images/#{image}", "https://unpkg.com/leaflet@1.5.1/dist/images/#{image}"
end
from 'git://github.com/aratcliffe/Leaflet.contextmenu.git', :tag => 'v1.5.0' do
if Settings.status != "database_offline"
can [:index, :new, :create, :show, :edit, :update, :destroy], ClientApplication
- can [:create, :edit, :comment, :subscribe, :unsubscribe], DiaryEntry
+ can [:new, :create, :edit, :update, :comment, :subscribe, :unsubscribe], DiaryEntry
can [:new, :create, :reply, :show, :inbox, :outbox, :mark, :destroy], Message
can [:close, :reopen], Note
can [:new, :create], Report
end
if user.administrator?
- can [:hide, :hidecomment], [DiaryEntry, DiaryComment]
+ can [:hide, :unhide, :hidecomment, :unhidecomment], [DiaryEntry, DiaryComment]
can [:index, :show, :resolve, :ignore, :reopen], Issue
can :create, IssueComment
can [:set_status, :delete, :index], User
can [:show, :download, :query], Changeset
can [:index, :create, :comment, :feed, :show, :search], Note
can :index, Tracepoint
- can [:api_users, :api_read], User
+ can [:index, :show], User
can [:index, :show], Node
can [:index, :show, :full, :ways_for_node], Way
can [:index, :show, :full, :relations_for_node, :relations_for_way, :relations_for_relation], Relation
can [:new, :create, :reply, :show, :inbox, :outbox, :mark, :destroy], Message
can [:close, :reopen], Note
can [:new, :create], Report
- can [:api_create, :api_read, :api_update, :api_delete, :api_data], Trace
- can [:api_details, :api_gpx_files], User
+ can [:create, :show, :update, :destroy, :data], Trace
+ can [:details, :gpx_files], User
can [:read, :read_one, :update, :update_one, :delete_one], UserPreference
if user.terms_agreed?
def initialize(token)
if Settings.status != "database_offline"
can [:create, :comment, :close, :reopen], Note if capability?(token, :allow_write_notes)
- can [:api_read, :api_data], Trace if capability?(token, :allow_read_gpx)
- can [:api_create, :api_update, :api_delete], Trace if capability?(token, :allow_write_gpx)
- can [:api_details], User if capability?(token, :allow_read_prefs)
- can [:api_gpx_files], User if capability?(token, :allow_read_gpx)
+ can [:show, :data], Trace if capability?(token, :allow_read_gpx)
+ can [:create, :update, :destroy], Trace if capability?(token, :allow_write_gpx)
+ can [:details], User if capability?(token, :allow_read_prefs)
+ can [:gpx_files], User if capability?(token, :allow_read_gpx)
can [:read, :read_one], UserPreference if capability?(token, :allow_read_prefs)
can [:update, :update_one, :delete_one], UserPreference if capability?(token, :allow_write_prefs)
//= require richtext
//= require querystring
-var querystring = require('querystring-component');
+var querystring = require("querystring-component");
/*
* Called as the user scrolls/zooms around to maniplate hrefs of the
* view tab and various other links
*/
window.updateLinks = function (loc, zoom, layers, object) {
- $(".geolink").each(function(index, link) {
+ $(".geolink").each(function (index, link) {
var href = link.href.split(/[?#]/)[0],
args = querystring.parse(link.search.substring(1)),
editlink = $(link).hasClass("editlink");
}
var query = querystring.stringify(args);
- if (query) href += '?' + query;
+ if (query) href += "?" + query;
args = {
lat: loc.lat,
- lon: 'lon' in loc ? loc.lon : loc.lng,
+ lon: "lon" in loc ? loc.lon : loc.lng,
zoom: zoom
};
});
var editDisabled = zoom < 13;
- $('#edit_tab')
- .tooltip({placement: 'bottom'})
- .off('click.minzoom')
- .on('click.minzoom', function() { return !editDisabled; })
- .toggleClass('disabled', editDisabled)
- .attr('data-original-title', editDisabled ?
- I18n.t('javascripts.site.edit_disabled_tooltip') : '');
+ $("#edit_tab")
+ .tooltip({ placement: "bottom" })
+ .off("click.minzoom")
+ .on("click.minzoom", function () { return !editDisabled; })
+ .toggleClass("disabled", editDisabled)
+ .attr("data-original-title", editDisabled ?
+ I18n.t("javascripts.site.edit_disabled_tooltip") : "");
};
window.maximiseMap = function () {
* to defer the measurement slightly as a workaround.
*/
setTimeout(function () {
- $("header").children(":visible").each(function (i,e) {
+ $("header").children(":visible").each(function (i, e) {
headerWidth = headerWidth + $(e).outerWidth();
});
$("body").addClass("compact");
- $("header").children(":visible").each(function (i,e) {
+ $("header").children(":visible").each(function (i, e) {
compactWidth = compactWidth + $(e).outerWidth();
});
$(window).resize(updateHeader);
}, 0);
- $("#menu-icon").on("click", function(e) {
+ $("#menu-icon").on("click", function (e) {
e.preventDefault();
$("header").toggleClass("closed");
});
- $("nav.primary li a").on("click", function() {
+ $("nav.primary li a").on("click", function () {
$("header").toggleClass("closed");
});
map.removeLayer(marker);
}
- marker = L.marker(e.latlng, {icon: OSM.getUserIcon()}).addTo(map)
- .bindPopup(I18n.t('diary_entries.edit.marker_text'));
+ marker = L.marker(e.latlng, { icon: OSM.getUserIcon() }).addTo(map)
+ .bindPopup(I18n.t("diary_entries.edit.marker_text"));
}
$("#usemap").click(function (e) {
var params = $("#map").data();
var centre = [params.lat, params.lon];
- var position = $('html').attr('dir') === 'rtl' ? 'topleft' : 'topright';
+ var position = $("html").attr("dir") === "rtl" ? "topleft" : "topright";
map = L.map("map", {
attributionControl: false,
zoomControl: false
}).addLayer(new L.OSM.Mapnik());
- L.OSM.zoom({position: position})
+ L.OSM.zoom({ position: position })
.addTo(map);
map.setView(centre, params.zoom);
if ($("#latitude").val() && $("#longitude").val()) {
- marker = L.marker(centre, {icon: OSM.getUserIcon()}).addTo(map)
- .bindPopup(I18n.t('diary_entries.edit.marker_text'));
+ marker = L.marker(centre, { icon: OSM.getUserIcon() }).addTo(map)
+ .bindPopup(I18n.t("diary_entries.edit.marker_text"));
}
map.on("click", setLocation);
-$(document).ready(function() {
+$(document).ready(function () {
var params = OSM.params();
- var url = '/note/new';
+ var url = "/note/new";
if (params.lat && params.lon) {
params.lat = parseFloat(params.lat);
params.lon = parseFloat(params.lon);
params.zoom = params.zoom || 17;
url += OSM.formatHash(params);
}
- $('.icon.note').attr('href', url);
+ $(".icon.note").attr("href", url);
});
/* globals iD */
-document.addEventListener("DOMContentLoaded", function() {
+document.addEventListener("DOMContentLoaded", function () {
var container = document.getElementById("id-container");
- if (typeof iD === 'undefined' || !iD.Detect().support) {
- container.innerHTML = 'This editor is supported ' +
- 'in Firefox, Chrome, Safari, Opera, Edge, and Internet Explorer 11. ' +
- 'Please upgrade your browser or use Potlatch 2 to edit the map.';
- container.className = 'unsupported';
+ if (typeof iD === "undefined" || !iD.Detect().support) {
+ container.innerHTML = "This editor is supported " +
+ "in Firefox, Chrome, Safari, Opera, Edge, and Internet Explorer 11. " +
+ "Please upgrade your browser or use Potlatch 2 to edit the map.";
+ container.className = "unsupported";
} else {
var id = iD.Context()
.embed(true)
oauth_token_secret: container.dataset.tokenSecret
});
- id.map().on('move.embed', parent.$.throttle(250, function() {
+ id.map().on("move.embed", parent.$.throttle(250, function () {
if (id.inIntro()) return;
var zoom = ~~id.map().zoom(),
center = id.map().center(),
// 0ms timeout to avoid iframe JS context weirdness.
// http://bl.ocks.org/jfirebaugh/5439412
- setTimeout(function() {
+ setTimeout(function () {
id.map().centerZoom(
[data.lon, data.lat],
Math.max(data.zoom || 15, 13));
$(document).ready(function () {
var loaderTimeout;
- OSM.loadSidebarContent = function(path, callback) {
+ var map = new L.OSM.Map("map", {
+ zoomControl: false,
+ layerControl: false,
+ contextmenu: true
+ });
+
+ OSM.loadSidebarContent = function (path, callback) {
map.setSidebarOverlaid(false);
clearTimeout(loaderTimeout);
- loaderTimeout = setTimeout(function() {
- $('#sidebar_loader').show();
+ loaderTimeout = setTimeout(function () {
+ $("#sidebar_loader").show();
}, 200);
// IE<10 doesn't respect Vary: X-Requested-With header, so
// prevent caching the XHR response as a full-page URL.
- if (path.indexOf('?') >= 0) {
- path += '&xhr=1';
+ if (path.indexOf("?") >= 0) {
+ path += "&xhr=1";
} else {
- path += '?xhr=1';
+ path += "?xhr=1";
}
- $('#sidebar_content')
+ $("#sidebar_content")
.empty();
$.ajax({
url: path,
dataType: "html",
- complete: function(xhr) {
+ complete: function (xhr) {
clearTimeout(loaderTimeout);
- $('#flash').empty();
- $('#sidebar_loader').hide();
+ $("#flash").empty();
+ $("#sidebar_loader").hide();
var content = $(xhr.responseText);
- if (xhr.getResponseHeader('X-Page-Title')) {
- var title = xhr.getResponseHeader('X-Page-Title');
+ if (xhr.getResponseHeader("X-Page-Title")) {
+ var title = xhr.getResponseHeader("X-Page-Title");
document.title = decodeURIComponent(title);
}
- $('head')
- .find('link[type="application/atom+xml"]')
+ $("head")
+ .find("link[type=\"application/atom+xml\"]")
.remove();
- $('head')
- .append(content.filter('link[type="application/atom+xml"]'));
+ $("head")
+ .append(content.filter("link[type=\"application/atom+xml\"]"));
- $('#sidebar_content').html(content.not('link[type="application/atom+xml"]'));
+ $("#sidebar_content").html(content.not("link[type=\"application/atom+xml\"]"));
if (callback) {
callback();
var params = OSM.mapParams();
- var map = new L.OSM.Map("map", {
- zoomControl: false,
- layerControl: false,
- contextmenu: true
- });
-
- map.attributionControl.setPrefix('');
+ map.attributionControl.setPrefix("");
map.updateLayers(params.layers);
}
});
- var position = $('html').attr('dir') === 'rtl' ? 'topleft' : 'topright';
+ var position = $("html").attr("dir") === "rtl" ? "topleft" : "topright";
- L.OSM.zoom({position: position})
+ L.OSM.zoom({ position: position })
.addTo(map);
var locate = L.control.locate({
position: position,
- icon: 'icon geolocate',
- iconLoading: 'icon geolocate',
+ icon: "icon geolocate",
+ iconLoading: "icon geolocate",
strings: {
- title: I18n.t('javascripts.map.locate.title'),
- popup: I18n.t('javascripts.map.locate.popup')
+ title: I18n.t("javascripts.map.locate.title"),
+ popup: I18n.t("javascripts.map.locate.popup")
}
}).addTo(map);
var locateContainer = locate.getContainer();
$(locateContainer)
- .removeClass('leaflet-control-locate leaflet-bar')
- .addClass('control-locate')
+ .removeClass("leaflet-control-locate leaflet-bar")
+ .addClass("control-locate")
.children("a")
- .attr('href', '#')
- .removeClass('leaflet-bar-part leaflet-bar-part-single')
- .addClass('control-button');
+ .attr("href", "#")
+ .removeClass("leaflet-bar-part leaflet-bar-part-single")
+ .addClass("control-button");
- var sidebar = L.OSM.sidebar('#map-ui')
+ var sidebar = L.OSM.sidebar("#map-ui")
.addTo(map);
L.OSM.layers({
}).addTo(map);
L.OSM.share({
- position: position,
- sidebar: sidebar,
- short: true
+ "position": position,
+ "sidebar": sidebar,
+ "short": true
}).addTo(map);
L.OSM.note({
OSM.initializeContextMenu(map);
- if (OSM.STATUS !== 'api_offline' && OSM.STATUS !== 'database_offline') {
+ if (OSM.STATUS !== "api_offline" && OSM.STATUS !== "database_offline") {
OSM.initializeNotes(map);
if (params.layers.indexOf(map.noteLayer.options.code) >= 0) {
map.addLayer(map.noteLayer);
}
}
- var placement = $('html').attr('dir') === 'rtl' ? 'right' : 'left';
- $('.leaflet-control .control-button').tooltip({placement: placement, container: 'body'});
+ var placement = $("html").attr("dir") === "rtl" ? "right" : "left";
+ $(".leaflet-control .control-button").tooltip({ placement: placement, container: "body" });
var expiry = new Date();
expiry.setYear(expiry.getFullYear() + 10);
- map.on('moveend layeradd layerremove', function() {
+ map.on("moveend layeradd layerremove", function () {
updateLinks(
map.getCenter().wrap(),
map.getZoom(),
map.getLayersCode(),
map._object);
- $.removeCookie('_osm_location');
- $.cookie('_osm_location', OSM.locationCookie(map), { expires: expiry, path: '/' });
+ $.removeCookie("_osm_location");
+ $.cookie("_osm_location", OSM.locationCookie(map), { expires: expiry, path: "/" });
});
- if ($.cookie('_osm_welcome') !== 'hide') {
- $('.welcome').addClass('visible');
+ if ($.cookie("_osm_welcome") !== "hide") {
+ $(".welcome").addClass("visible");
}
- $('.welcome .close-wrap').on('click', function() {
- $('.welcome').removeClass('visible');
- $.cookie('_osm_welcome', 'hide', { expires: expiry, path: '/' });
+ $(".welcome .close-wrap").on("click", function () {
+ $(".welcome").removeClass("visible");
+ $.cookie("_osm_welcome", "hide", { expires: expiry, path: "/" });
});
var bannerExpiry = new Date();
bannerExpiry.setYear(bannerExpiry.getFullYear() + 1);
- $('#banner .close-wrap').on('click', function(e) {
+ $("#banner .close-wrap").on("click", function (e) {
var cookieId = e.target.id;
- $('#banner').hide();
+ $("#banner").hide();
e.preventDefault();
if (cookieId) {
- $.cookie(cookieId, 'hide', { expires: bannerExpiry, path: '/' });
+ $.cookie(cookieId, "hide", { expires: bannerExpiry, path: "/" });
}
});
if (OSM.PIWIK) {
- map.on('layeradd', function (e) {
+ map.on("layeradd", function (e) {
if (e.layer.options) {
var goal = OSM.PIWIK.goals[e.layer.options.keyid];
if (goal) {
- $('body').trigger('piwikgoal', goal);
+ $("body").trigger("piwikgoal", goal);
}
}
});
L.marker([params.mlat, params.mlon]).addTo(map);
}
- $("#homeanchor").on("click", function(e) {
+ $("#homeanchor").on("click", function (e) {
e.preventDefault();
var data = $(this).data(),
center = L.latLng(data.lat, data.lon);
map.setView(center, data.zoom);
- L.marker(center, {icon: OSM.getUserIcon()}).addTo(map);
+ L.marker(center, { icon: OSM.getUserIcon() }).addTo(map);
});
function remoteEditHandler(bbox, object) {
bottom: bbox.getSouth() - 0.0001
};
- if (location.protocol === 'http' ||
- bowser.check({chrome: "53", firefox: "55"})) {
+ if (location.protocol === "http" ||
+ bowser.check({ chrome: "53", firefox: "55" })) {
url = "http://127.0.0.1:8111/load_and_zoom?";
} else {
url = "https://127.0.0.1:8112/load_and_zoom?";
if (object) query.select = object.type + object.id;
- var iframe = $('<iframe>')
+ var iframe = $("<iframe>")
.hide()
- .appendTo('body')
+ .appendTo("body")
.attr("src", url + querystring.stringify(query))
- .on('load', function() {
+ .on("load", function () {
$(this).remove();
loaded = true;
});
setTimeout(function () {
if (!loaded) {
- alert(I18n.t('site.index.remote_failed'));
+ alert(I18n.t("site.index.remote_failed"));
iframe.remove();
}
}, 1000);
return false;
}
- $("a[data-editor=remote]").click(function(e) {
+ $("a[data-editor=remote]").click(function (e) {
var params = OSM.mapParams(this.search);
remoteEditHandler(map.getBounds(), params.object);
e.preventDefault();
});
if (OSM.params().edit_help) {
- $('#editanchor')
- .removeAttr('title')
+ $("#editanchor")
+ .removeAttr("title")
.tooltip({
- placement: 'bottom',
- title: I18n.t('javascripts.edit_help')
+ placement: "bottom",
+ title: I18n.t("javascripts.edit_help")
})
- .tooltip('show');
+ .tooltip("show");
- $('body').one('click', function() {
- $('#editanchor').tooltip('hide');
+ $("body").one("click", function () {
+ $("#editanchor").tooltip("hide");
});
}
- OSM.Index = function(map) {
+ OSM.Index = function (map) {
var page = {};
- page.pushstate = page.popstate = function() {
+ page.pushstate = page.popstate = function () {
map.setSidebarOverlaid(true);
- document.title = I18n.t('layouts.project_name.title');
+ document.title = I18n.t("layouts.project_name.title");
};
- page.load = function() {
+ page.load = function () {
var params = querystring.parse(location.search.substring(1));
if (params.query) {
$("#sidebar .search_form input[name=query]").value(params.query);
return page;
};
- OSM.Browse = function(map, type) {
+ OSM.Browse = function (map, type) {
var page = {};
- page.pushstate = page.popstate = function(path, id) {
- OSM.loadSidebarContent(path, function() {
+ page.pushstate = page.popstate = function (path, id) {
+ OSM.loadSidebarContent(path, function () {
addObject(type, id);
});
};
- page.load = function(path, id) {
+ page.load = function (path, id) {
addObject(type, id, true);
};
function addObject(type, id, center) {
- map.addObject({type: type, id: parseInt(id)}, function(bounds) {
+ map.addObject({ type: type, id: parseInt(id, 10) }, function (bounds) {
if (!window.location.hash && bounds.isValid() &&
(center || !map.getBounds().contains(bounds))) {
OSM.router.withoutMoveListener(function () {
});
}
- page.unload = function() {
+ page.unload = function () {
map.removeObject();
};
var history = OSM.History(map);
OSM.router = OSM.Router(map, {
- "/": OSM.Index(map),
- "/search": OSM.Search(map),
- "/directions": OSM.Directions(map),
- "/export": OSM.Export(map),
- "/note/new": OSM.NewNote(map),
- "/history/friends": history,
- "/history/nearby": history,
- "/history": history,
+ "/": OSM.Index(map),
+ "/search": OSM.Search(map),
+ "/directions": OSM.Directions(map),
+ "/export": OSM.Export(map),
+ "/note/new": OSM.NewNote(map),
+ "/history/friends": history,
+ "/history/nearby": history,
+ "/history": history,
"/user/:display_name/history": history,
- "/note/:id": OSM.Note(map),
- "/node/:id(/history)": OSM.Browse(map, 'node'),
- "/way/:id(/history)": OSM.Browse(map, 'way'),
- "/relation/:id(/history)": OSM.Browse(map, 'relation'),
- "/changeset/:id": OSM.Changeset(map),
- "/query": OSM.Query(map)
+ "/note/:id": OSM.Note(map),
+ "/node/:id(/history)": OSM.Browse(map, "node"),
+ "/way/:id(/history)": OSM.Browse(map, "way"),
+ "/relation/:id(/history)": OSM.Browse(map, "relation"),
+ "/changeset/:id": OSM.Changeset(map),
+ "/query": OSM.Query(map)
});
if (OSM.preferred_editor === "remote" && document.location.pathname === "/edit") {
OSM.router.load();
- $(document).on("click", "a", function(e) {
- if (e.isDefaultPrevented() || e.isPropagationStopped())
+ $(document).on("click", "a", function (e) {
+ if (e.isDefaultPrevented() || e.isPropagationStopped()) {
return;
+ }
// Open links in a new tab as normal.
- if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
+ if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
return;
+ }
// Ignore cross-protocol and cross-origin links.
- if (location.protocol !== this.protocol || location.host !== this.host)
+ if (location.protocol !== this.protocol || location.host !== this.host) {
return;
+ }
- if (OSM.router.route(this.pathname + this.search + this.hash))
+ if (OSM.router.route(this.pathname + this.search + this.hash)) {
e.preventDefault();
+ }
});
});
onSelect(e.layer);
});
- map.on('layeradd', function (e) {
+ map.on("layeradd", function (e) {
if (e.layer === dataLayer) {
map.on("moveend", updateData);
updateData();
}
});
- map.on('layerremove', function (e) {
+ map.on("layerremove", function (e) {
if (e.layer === dataLayer) {
map.off("moveend", updateData);
- $('#browse_status').empty();
+ $("#browse_status").empty();
}
});
}
function displayFeatureWarning(count, limit, add, cancel) {
- $('#browse_status').html(
+ $("#browse_status").html(
$("<p class='warning'></p>")
.text(I18n.t("browse.start_rjs.feature_warning", { num_features: count, max_features: limit }))
.prepend(
.click(cancel))
.append(
$("<input type='submit'>")
- .val(I18n.t('browse.start_rjs.load_data'))
+ .val(I18n.t("browse.start_rjs.load_data"))
.click(add)));
}
var features = dataLayer.buildFeatures(xml);
function addFeatures() {
- $('#browse_status').empty();
+ $("#browse_status").empty();
dataLayer.addData(features);
browseBounds = bounds;
}
function cancelAddFeatures() {
- $('#browse_status').empty();
+ $("#browse_status").empty();
}
if (features.length < maxFeatures) {
// Redraw in selected style
layer.originalStyle = layer.options;
- layer.setStyle({color: '#0000ff', weight: 8});
+ layer.setStyle({ color: "#0000ff", weight: 8 });
- OSM.router.route('/' + layer.feature.type + '/' + layer.feature.id);
+ OSM.router.route("/" + layer.feature.type + "/" + layer.feature.id);
// Stash the currently drawn feature
selectedLayer = layer;
OSM.Changeset = function (map) {
var page = {},
- content = $('#sidebar_content'),
+ content = $("#sidebar_content"),
currentChangesetId;
- page.pushstate = page.popstate = function(path, id) {
- OSM.loadSidebarContent(path, function() {
+ page.pushstate = page.popstate = function (path, id) {
+ OSM.loadSidebarContent(path, function () {
page.load(path, id);
});
};
- page.load = function(path, id) {
- if(id)
- currentChangesetId = id;
+ page.load = function (path, id) {
+ if (id) currentChangesetId = id;
initialize();
addChangeset(currentChangesetId, true);
};
function addChangeset(id, center) {
- map.addObject({type: 'changeset', id: parseInt(id)}, function(bounds) {
+ map.addObject({ type: "changeset", id: parseInt(id, 10) }, function (bounds) {
if (!window.location.hash && bounds.isValid() &&
(center || !map.getBounds().contains(bounds))) {
OSM.router.withoutMoveListener(function () {
$(form).find("input[type=submit]").prop("disabled", true);
- if(include_data) {
- data = {text: $(form.text).val()};
+ if (include_data) {
+ data = { text: $(form.text).val() };
} else {
data = {};
}
}
});
- content.find("textarea").val('').trigger("input");
+ content.find("textarea").val("").trigger("input");
}
- page.unload = function() {
+ page.unload = function () {
map.removeObject();
};
else map.contextmenu.enable();
});
- var updateMenu = function updateMenu () {
+ var updateMenu = function updateMenu() {
map.contextmenu.setDisabled(2, map.getZoom() < 12);
map.contextmenu.setDisabled(4, map.getZoom() < 14);
};
var awaitingRoute; // true if we've asked the engine for a route and are waiting to hear back
var chosenEngine;
- var popup = L.popup({autoPanPadding: [100, 100]});
+ var popup = L.popup({ autoPanPadding: [100, 100] });
var polyline = L.polyline([], {
- color: '#03f',
+ color: "#03f",
opacity: 0.3,
weight: 10
});
var highlight = L.polyline([], {
- color: '#ff0',
+ color: "#ff0",
opacity: 0.5,
weight: 12
});
var expiry = new Date();
expiry.setYear(expiry.getFullYear() + 10);
+ var engines = OSM.Directions.engines;
+
+ engines.sort(function (a, b) {
+ a = I18n.t("javascripts.directions.engines." + a.id);
+ b = I18n.t("javascripts.directions.engines." + b.id);
+ return a.localeCompare(b);
+ });
+
+ var select = $("select.routing_engines");
+
+ engines.forEach(function (engine, i) {
+ select.append("<option value='" + i + "'>" + I18n.t("javascripts.directions.engines." + engine.id) + "</option>");
+ });
+
function Endpoint(input, iconUrl) {
var endpoint = {};
autoPan: true
});
- endpoint.marker.on('drag dragend', function (e) {
- var dragging = (e.type === 'drag');
+ endpoint.marker.on("drag dragend", function (e) {
+ var dragging = (e.type === "drag");
if (dragging && !chosenEngine.draggable) return;
if (dragging && awaitingRoute) return;
endpoint.setLatLng(e.target.getLatLng());
}
});
- input.on("keydown", function() {
+ input.on("keydown", function () {
input.removeClass("error");
});
input.on("change", function (e) {
awaitingGeocode = true;
-
+
// make text the same in both text boxes
var value = e.target.value;
endpoint.setValue(value);
});
- endpoint.setValue = function(value, latlng) {
+ endpoint.setValue = function (value, latlng) {
endpoint.value = value;
delete endpoint.latlng;
input.removeClass("error");
}
};
- endpoint.getGeocode = function() {
+ endpoint.getGeocode = function () {
// if no one has entered a value yet, then we can't geocode, so don't
// even try.
if (!endpoint.value) {
endpoint.awaitingGeocode = true;
- $.getJSON(OSM.NOMINATIM_URL + 'search?q=' + encodeURIComponent(endpoint.value) + '&format=json', function (json) {
+ $.getJSON(OSM.NOMINATIM_URL + "search?q=" + encodeURIComponent(endpoint.value) + "&format=json", function (json) {
endpoint.awaitingGeocode = false;
endpoint.hasGeocode = true;
if (json.length === 0) {
input.addClass("error");
- alert(I18n.t('javascripts.directions.errors.no_place', {place: endpoint.value}));
+ alert(I18n.t("javascripts.directions.errors.no_place", { place: endpoint.value }));
return;
}
return endpoint;
}
- $(".directions_form .reverse_directions").on("click", function() {
+ $(".directions_form .reverse_directions").on("click", function () {
var from = endpoints[0].latlng,
to = endpoints[1].latlng;
}));
});
- $(".directions_form .close").on("click", function(e) {
+ $(".directions_form .close").on("click", function (e) {
e.preventDefault();
var route_from = endpoints[0].value;
if (route_from) {
var m = Math.round(s / 60);
var h = Math.floor(m / 60);
m -= h * 60;
- return h + ":" + (m < 10 ? '0' : '') + m;
+ return h + ":" + (m < 10 ? "0" : "") + m;
}
function findEngine(id) {
- return engines.findIndex(function(engine) {
+ return engines.findIndex(function (engine) {
return engine.id === id;
});
}
OSM.router.replace("/directions?" + querystring.stringify({
engine: chosenEngine.id,
- route: o.lat.toFixed(precision) + ',' + o.lng.toFixed(precision) + ';' +
- d.lat.toFixed(precision) + ',' + d.lng.toFixed(precision)
+ route: o.lat.toFixed(precision) + "," + o.lng.toFixed(precision) + ";" +
+ d.lat.toFixed(precision) + "," + d.lng.toFixed(precision)
}));
// copy loading item to sidebar and display it. we copy it, rather than
// just using it in-place and replacing it in case it has to be used
// again.
- $('#sidebar_content').html($('.directions_form .loader_copy').html());
+ $("#sidebar_content").html($(".directions_form .loader_copy").html());
map.setSidebarOverlaid(false);
awaitingRoute = chosenEngine.getRoute([o, d], function (err, route) {
map.removeLayer(polyline);
if (reportErrors) {
- $('#sidebar_content').html('<p class="search_results_error">' + I18n.t('javascripts.directions.errors.no_route') + '</p>');
+ $("#sidebar_content").html("<p class=\"search_results_error\">" + I18n.t("javascripts.directions.errors.no_route") + "</p>");
}
return;
map.fitBounds(polyline.getBounds().pad(0.05));
}
- var html = '<h2><a class="geolink" href="#">' +
- '<span class="icon close"></span></a>' + I18n.t('javascripts.directions.directions') +
- '</h2><p id="routing_summary">' +
- I18n.t('javascripts.directions.distance') + ': ' + formatDistance(route.distance) + '. ' +
- I18n.t('javascripts.directions.time') + ': ' + formatTime(route.time) + '.';
- if (typeof route.ascend !== 'undefined' && typeof route.descend !== 'undefined') {
- html += '<br />' +
- I18n.t('javascripts.directions.ascend') + ': ' + Math.round(route.ascend) + 'm. ' +
- I18n.t('javascripts.directions.descend') + ': ' + Math.round(route.descend) +'m.';
+ var html = "<h2><a class=\"geolink\" href=\"#\">" +
+ "<span class=\"icon close\"></span></a>" + I18n.t("javascripts.directions.directions") +
+ "</h2><p id=\"routing_summary\">" +
+ I18n.t("javascripts.directions.distance") + ": " + formatDistance(route.distance) + ". " +
+ I18n.t("javascripts.directions.time") + ": " + formatTime(route.time) + ".";
+ if (typeof route.ascend !== "undefined" && typeof route.descend !== "undefined") {
+ html += "<br />" +
+ I18n.t("javascripts.directions.ascend") + ": " + Math.round(route.ascend) + "m. " +
+ I18n.t("javascripts.directions.descend") + ": " + Math.round(route.descend) + "m.";
}
- html += '</p><table id="turnbyturn" />';
+ html += "</p><table id=\"turnbyturn\" />";
- $('#sidebar_content')
+ $("#sidebar_content")
.html(html);
// Add each row
- var cumulative = 0;
route.steps.forEach(function (step) {
var ll = step[0],
direction = step[1],
dist = step[3],
lineseg = step[4];
- cumulative += dist;
-
if (dist < 5) {
dist = "";
} else if (dist < 200) {
- dist = Math.round(dist / 10) * 10 + "m";
+ dist = String(Math.round(dist / 10) * 10) + "m";
} else if (dist < 1500) {
- dist = Math.round(dist / 100) * 100 + "m";
+ dist = String(Math.round(dist / 100) * 100) + "m";
} else if (dist < 5000) {
- dist = Math.round(dist / 100) / 10 + "km";
+ dist = String(Math.round(dist / 100) / 10) + "km";
} else {
- dist = Math.round(dist / 1000) + "km";
+ dist = String(Math.round(dist / 1000)) + "km";
}
var row = $("<tr class='turn'/>");
row.append("<td class='instruction'>" + instruction);
row.append("<td class='distance'>" + dist);
- row.on('click', function () {
+ row.on("click", function () {
popup
.setLatLng(ll)
.setContent("<p>" + instruction + "</p>")
map.removeLayer(highlight);
});
- $('#turnbyturn').append(row);
+ $("#turnbyturn").append(row);
});
- $('#sidebar_content').append('<p id="routing_credit">' +
- I18n.t('javascripts.directions.instructions.courtesy', {link: chosenEngine.creditline}) +
- '</p>');
+ $("#sidebar_content").append("<p id=\"routing_credit\">" +
+ I18n.t("javascripts.directions.instructions.courtesy", { link: chosenEngine.creditline }) +
+ "</p>");
- $('#sidebar_content a.geolink').on('click', function(e) {
+ $("#sidebar_content a.geolink").on("click", function (e) {
e.preventDefault();
map.removeLayer(polyline);
- $('#sidebar_content').html('');
+ $("#sidebar_content").html("");
map.setSidebarOverlaid(true);
// TODO: collapse width of sidebar back to previous
});
});
}
- var engines = OSM.Directions.engines;
-
- engines.sort(function (a, b) {
- a = I18n.t('javascripts.directions.engines.' + a.id);
- b = I18n.t('javascripts.directions.engines.' + b.id);
- return a.localeCompare(b);
- });
-
- var select = $('select.routing_engines');
-
- engines.forEach(function(engine, i) {
- select.append("<option value='" + i + "'>" + I18n.t('javascripts.directions.engines.' + engine.id) + "</option>");
- });
-
- var chosenEngineIndex = findEngine('fossgis_osrm_car');
- if ($.cookie('_osm_directions_engine')) {
- chosenEngineIndex = findEngine($.cookie('_osm_directions_engine'));
+ var chosenEngineIndex = findEngine("fossgis_osrm_car");
+ if ($.cookie("_osm_directions_engine")) {
+ chosenEngineIndex = findEngine($.cookie("_osm_directions_engine"));
}
setEngine(chosenEngineIndex);
select.on("change", function (e) {
chosenEngine = engines[e.target.selectedIndex];
- $.cookie('_osm_directions_engine', chosenEngine.id, { expires: expiry, path: '/' });
+ $.cookie("_osm_directions_engine", chosenEngine.id, { expires: expiry, path: "/" });
if (map.hasLayer(polyline)) {
getRoute(true, true);
}
});
- $(".directions_form").on("submit", function(e) {
+ $(".directions_form").on("submit", function (e) {
e.preventDefault();
getRoute(true, true);
});
- $(".routing_marker").on('dragstart', function (e) {
+ $(".routing_marker").on("dragstart", function (e) {
var dt = e.originalEvent.dataTransfer;
- dt.effectAllowed = 'move';
- var dragData = { type: $(this).data('type') };
- dt.setData('text', JSON.stringify(dragData));
+ dt.effectAllowed = "move";
+ var dragData = { type: $(this).data("type") };
+ dt.setData("text", JSON.stringify(dragData));
if (dt.setDragImage) {
var img = $("<img>").attr("src", $(e.originalEvent.target).attr("src"));
dt.setDragImage(img.get(0), 12, 21);
var page = {};
- page.pushstate = page.popstate = function() {
+ page.pushstate = page.popstate = function () {
$(".search_form").hide();
$(".directions_form").show();
- $("#map").on('dragend dragover', function (e) {
+ $("#map").on("dragend dragover", function (e) {
e.preventDefault();
});
- $("#map").on('drop', function (e) {
+ $("#map").on("drop", function (e) {
e.preventDefault();
var oe = e.originalEvent;
- var dragData = JSON.parse(oe.dataTransfer.getData('text'));
+ var dragData = JSON.parse(oe.dataTransfer.getData("text"));
var type = dragData.type;
var pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
pt.y += 20;
var ll = map.containerPointToLatLng(pt);
- endpoints[type === 'from' ? 0 : 1].setLatLng(ll);
+ endpoints[type === "from" ? 0 : 1].setLatLng(ll);
getRoute(true, true);
});
var params = querystring.parse(location.search.substring(1)),
- route = (params.route || '').split(';'),
- from = route[0] && L.latLng(route[0].split(',')),
- to = route[1] && L.latLng(route[1].split(','));
+ route = (params.route || "").split(";"),
+ from = route[0] && L.latLng(route[0].split(",")),
+ to = route[1] && L.latLng(route[1].split(","));
if (params.engine) {
var engineIndex = findEngine(params.engine);
getRoute(true, true);
};
- page.load = function() {
+ page.load = function () {
page.pushstate();
};
- page.unload = function() {
+ page.unload = function () {
$(".search_form").show();
$(".directions_form").hide();
- $("#map").off('dragend dragover drop');
+ $("#map").off("dragend dragover drop");
map
.removeLayer(popup)
return {
id: id,
- creditline: '<a href="https://routing.openstreetmap.de/about.html" target="_blank">FOSSGIS Routing Service</a>',
+ creditline: "<a href=\"https://routing.openstreetmap.de/about.html\" target=\"_blank\">FOSSGIS Routing Service</a>",
draggable: true,
- _transformSteps: function(input_steps, line) {
+ _transformSteps: function (input_steps, line) {
var INSTRUCTION_TEMPLATE = {
- 'continue': 'javascripts.directions.instructions.continue',
- 'merge right': 'javascripts.directions.instructions.merge_right',
- 'merge left': 'javascripts.directions.instructions.merge_left',
- 'off ramp right': 'javascripts.directions.instructions.offramp_right',
- 'off ramp left': 'javascripts.directions.instructions.offramp_left',
- 'on ramp right': 'javascripts.directions.instructions.onramp_right',
- 'on ramp left': 'javascripts.directions.instructions.onramp_left',
- 'fork right': 'javascripts.directions.instructions.fork_right',
- 'fork left': 'javascripts.directions.instructions.fork_left',
- 'end of road right': 'javascripts.directions.instructions.endofroad_right',
- 'end of road left': 'javascripts.directions.instructions.endofroad_left',
- 'turn straight': 'javascripts.directions.instructions.continue',
- 'turn slight right': 'javascripts.directions.instructions.slight_right',
- 'turn right': 'javascripts.directions.instructions.turn_right',
- 'turn sharp right': 'javascripts.directions.instructions.sharp_right',
- 'turn uturn': 'javascripts.directions.instructions.uturn',
- 'turn sharp left': 'javascripts.directions.instructions.sharp_left',
- 'turn left': 'javascripts.directions.instructions.turn_left',
- 'turn slight left': 'javascripts.directions.instructions.slight_left',
- 'roundabout': 'javascripts.directions.instructions.roundabout',
- 'rotary': 'javascripts.directions.instructions.roundabout',
- 'exit roundabout': 'javascripts.directions.instructions.exit_roundabout',
- 'exit rotary': 'javascripts.directions.instructions.exit_roundabout',
- 'depart': 'javascripts.directions.instructions.start',
- 'arrive': 'javascripts.directions.instructions.destination',
+ "continue": "javascripts.directions.instructions.continue",
+ "merge right": "javascripts.directions.instructions.merge_right",
+ "merge left": "javascripts.directions.instructions.merge_left",
+ "off ramp right": "javascripts.directions.instructions.offramp_right",
+ "off ramp left": "javascripts.directions.instructions.offramp_left",
+ "on ramp right": "javascripts.directions.instructions.onramp_right",
+ "on ramp left": "javascripts.directions.instructions.onramp_left",
+ "fork right": "javascripts.directions.instructions.fork_right",
+ "fork left": "javascripts.directions.instructions.fork_left",
+ "end of road right": "javascripts.directions.instructions.endofroad_right",
+ "end of road left": "javascripts.directions.instructions.endofroad_left",
+ "turn straight": "javascripts.directions.instructions.continue",
+ "turn slight right": "javascripts.directions.instructions.slight_right",
+ "turn right": "javascripts.directions.instructions.turn_right",
+ "turn sharp right": "javascripts.directions.instructions.sharp_right",
+ "turn uturn": "javascripts.directions.instructions.uturn",
+ "turn sharp left": "javascripts.directions.instructions.sharp_left",
+ "turn left": "javascripts.directions.instructions.turn_left",
+ "turn slight left": "javascripts.directions.instructions.slight_left",
+ "roundabout": "javascripts.directions.instructions.roundabout",
+ "rotary": "javascripts.directions.instructions.roundabout",
+ "exit roundabout": "javascripts.directions.instructions.exit_roundabout",
+ "exit rotary": "javascripts.directions.instructions.exit_roundabout",
+ "depart": "javascripts.directions.instructions.start",
+ "arrive": "javascripts.directions.instructions.destination"
};
var ICON_MAP = {
- 'continue': 0,
- 'merge right': 21,
- 'merge left': 20,
- 'off ramp right': 24,
- 'off ramp left': 25,
- 'on ramp right': 2,
- 'on ramp left': 6,
- 'fork right': 18,
- 'fork left': 19,
- 'end of road right': 22,
- 'end of road left': 23,
- 'turn straight': 0,
- 'turn slight right': 1,
- 'turn right': 2,
- 'turn sharp right': 3,
- 'turn uturn': 4,
- 'turn slight left': 5,
- 'turn left': 6,
- 'turn sharp left': 7,
- 'roundabout': 10,
- 'rotary': 10,
- 'exit roundabout': 10,
- 'exit rotary': 10,
- 'depart': 8,
- 'arrive': 14
+ "continue": 0,
+ "merge right": 21,
+ "merge left": 20,
+ "off ramp right": 24,
+ "off ramp left": 25,
+ "on ramp right": 2,
+ "on ramp left": 6,
+ "fork right": 18,
+ "fork left": 19,
+ "end of road right": 22,
+ "end of road left": 23,
+ "turn straight": 0,
+ "turn slight right": 1,
+ "turn right": 2,
+ "turn sharp right": 3,
+ "turn uturn": 4,
+ "turn slight left": 5,
+ "turn left": 6,
+ "turn sharp left": 7,
+ "roundabout": 10,
+ "rotary": 10,
+ "exit roundabout": 10,
+ "exit rotary": 10,
+ "depart": 8,
+ "arrive": 14
};
- var numToWord = function(num) {
- return ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"][num-1];
+ var numToWord = function (num) {
+ return ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"][num - 1];
};
- var transformed_steps = input_steps.map(function(step, idx) {
+ var transformed_steps = input_steps.map(function (step, idx) {
var maneuver_id;
// special case handling
switch (step.maneuver.type) {
- case 'on ramp':
- case 'off ramp':
- case 'merge':
- case 'end of road':
- case 'fork':
- maneuver_id = step.maneuver.type + ' ' + (step.maneuver.modifier.indexOf('left') >= 0 ? 'left' : 'right');
+ case "on ramp":
+ case "off ramp":
+ case "merge":
+ case "end of road":
+ case "fork":
+ maneuver_id = step.maneuver.type + " " + (step.maneuver.modifier.indexOf("left") >= 0 ? "left" : "right");
break;
- case 'depart':
- case 'arrive':
- case 'roundabout':
- case 'rotary':
- case 'exit roundabout':
- case 'exit rotary':
+ case "depart":
+ case "arrive":
+ case "roundabout":
+ case "rotary":
+ case "exit roundabout":
+ case "exit rotary":
maneuver_id = step.maneuver.type;
break;
- case 'roundabout turn':
- case 'turn':
+ case "roundabout turn":
+ case "turn":
maneuver_id = "turn " + step.maneuver.modifier;
break;
// for unknown types the fallback is turn
var template = INSTRUCTION_TEMPLATE[maneuver_id];
// convert lat,lng pairs to LatLng objects
- var step_geometry = L.PolylineUtil.decode(step.geometry, { precision: 5 }).map(function(a) { return L.latLng(a); }) ;
+ var step_geometry = L.PolylineUtil.decode(step.geometry, { precision: 5 }).map(function (a) { return L.latLng(a); });
// append step_geometry on line
Array.prototype.push.apply(line, step_geometry);
} else if (step.ref) {
name = "<b>" + step.ref + "</b>";
} else {
- name = I18n.t('javascripts.directions.instructions.unnamed');
+ name = I18n.t("javascripts.directions.instructions.unnamed");
namedRoad = false;
}
} else if (step.maneuver.type.match(/^(rotary|roundabout)$/)) {
if (step.maneuver.exit) {
if (step.maneuver.exit <= 10) {
- instText += I18n.t(template + '_with_exit_ordinal', { exit: I18n.t('javascripts.directions.instructions.exit_counts.' + numToWord(step.maneuver.exit)), name: name });
+ instText += I18n.t(template + "_with_exit_ordinal", { exit: I18n.t("javascripts.directions.instructions.exit_counts." + numToWord(step.maneuver.exit)), name: name });
} else {
- instText += I18n.t(template + '_with_exit', { exit: step.maneuver.exit, name: name });
+ instText += I18n.t(template + "_with_exit", { exit: step.maneuver.exit, name: name });
}
} else {
- instText += I18n.t(template + '_without_exit', { name: name });
+ instText += I18n.t(template + "_without_exit", { name: name });
}
} else if (step.maneuver.type.match(/^(on ramp|off ramp)$/)) {
var params = {};
}
instText += I18n.t(template, params);
} else {
- instText += I18n.t(template + '_without_exit', { name: name });
+ instText += I18n.t(template + "_without_exit", { name: name });
}
return [[step.maneuver.location[1], step.maneuver.location[0]], ICON_MAP[maneuver_id], instText, step.distance, step_geometry];
});
},
getRoute: function (points, callback) {
-
var params = [
{ name: "overview", value: "false" },
{ name: "geometries", value: "polyline" },
if (cachedHints.length === points.length) {
- params.push({name: "hints", value: cachedHints.join(";")});
+ params.push({ name: "hints", value: cachedHints.join(";") });
} else {
// invalidate cache
cachedHints = [];
}
- var encoded_coords = points.map(function(p) {
- return p.lng + ',' + p.lat;
- }).join(';');
+ var encoded_coords = points.map(function (p) {
+ return p.lng + "," + p.lat;
+ }).join(";");
var req_url = OSM.FOSSGIS_OSRM_URL + "routed-" + vehicleType + "/route/v1/driving/" + encoded_coords;
var onResponse = function (data) {
- if (data.code !== 'Ok')
+ if (data.code !== "Ok") {
return callback(true);
+ }
- cachedHints = data.waypoints.map(function(wp) {
+ cachedHints = data.waypoints.map(function (wp) {
return wp.hint;
});
"-3": 7, // sharp left
"-2": 6, // left
"-1": 5, // slight left
- 0: 0, // straight
- 1: 1, // slight right
- 2: 2, // right
- 3: 3, // sharp right
- 4: 14, // finish reached
- 5: 14, // via reached
- 6: 10 // roundabout
+ "0": 0, // straight
+ "1": 1, // slight right
+ "2": 2, // right
+ "3": 3, // sharp right
+ "4": 14, // finish reached
+ "5": 14, // via reached
+ "6": 10 // roundabout
};
return {
id: id,
- creditline: '<a href="https://www.graphhopper.com/" target="_blank">Graphhopper</a>',
+ creditline: "<a href=\"https://www.graphhopper.com/\" target=\"_blank\">Graphhopper</a>",
draggable: false,
getRoute: function (points, callback) {
return $.ajax({
url: OSM.GRAPHHOPPER_URL,
data: {
- vehicle: vehicleType,
- locale: I18n.currentLocale(),
- key: "LijBPDQGfu7Iiq80w3HzwB4RUDJbMbhs6BU0dEnn",
+ "vehicle": vehicleType,
+ "locale": I18n.currentLocale(),
+ "key": "LijBPDQGfu7Iiq80w3HzwB4RUDJbMbhs6BU0dEnn",
"ch.disable": vehicleType === "car",
- elevation: false,
- instructions: true,
- point: points.map(function (p) { return p.lat + "," + p.lng; })
+ "elevation": false,
+ "instructions": true,
+ "point": points.map(function (p) { return p.lat + "," + p.lng; })
},
traditional: true,
dataType: "json",
success: function (data) {
- if (!data.paths || data.paths.length === 0)
+ if (!data.paths || data.paths.length === 0) {
return callback(true);
+ }
var path = data.paths[0];
var line = L.PolylineUtil.decode(path.points);
var distInMeter = instr.distance;
var lineseg = [];
for (var j = instr.interval[0]; j <= instr.interval[1]; j++) {
- lineseg.push({lat: line[j][0], lng: line[j][1]});
+ lineseg.push({ lat: line[j][0], lng: line[j][1] });
}
steps.push([
- {lat: latLng[0], lng: latLng[1]},
+ { lat: latLng[0], lng: latLng[1] },
instrCode,
instrText,
distInMeter,
-OSM.Export = function(map) {
+OSM.Export = function (map) {
var page = {};
var locationFilter = new L.LocationFilter({
if (getBounds().getSize() > OSM.MAX_REQUEST_AREA) e.preventDefault();
}
- page.pushstate = page.popstate = function(path) {
+ page.pushstate = page.popstate = function (path) {
$("#export_tab").addClass("current");
OSM.loadSidebarContent(path, page.load);
};
- page.load = function() {
+ page.load = function () {
map
.addLayer(locationFilter)
.on("moveend", update);
return map.getState();
};
- page.unload = function() {
+ page.unload = function () {
map
.removeLayer(locationFilter)
.off("moveend", update);
//= require jquery.simulate
-OSM.History = function(map) {
+OSM.History = function (map) {
var page = {};
$("#sidebar_content")
})
.on("mousedown", "[data-changeset]", function () {
var moved = false;
- $(this).one("click", function (e) {
- if (!moved && !$(e.target).is('a')) {
- clickChangeset($(this).data("changeset").id, e);
- }
- }).one("mousemove", function () {
- moved = true;
- });
+ $(this)
+ .one("click", function (e) {
+ if (!moved && !$(e.target).is("a")) {
+ clickChangeset($(this).data("changeset").id, e);
+ }
+ })
+ .one("mousemove", function () {
+ moved = true;
+ });
});
var group = L.featureGroup()
clickChangeset(e.layer.id, e);
});
- group.getLayerId = function(layer) {
+ group.getLayerId = function (layer) {
return layer.id;
};
function highlightChangeset(id) {
- group.getLayer(id).setStyle({fillOpacity: 0.3, color: "#FF6600", weight: 3});
+ group.getLayer(id).setStyle({ fillOpacity: 0.3, color: "#FF6600", weight: 3 });
$("#changeset_" + id).addClass("selected");
}
function unHighlightChangeset(id) {
- group.getLayer(id).setStyle({fillOpacity: 0, color: "#FF9500", weight: 2});
+ group.getLayer(id).setStyle({ fillOpacity: 0, color: "#FF9500", weight: 2 });
$("#changeset_" + id).removeClass("selected");
}
}
function update() {
- var data = {list: '1'};
+ var data = { list: "1" };
- if (window.location.pathname === '/history') {
+ if (window.location.pathname === "/history") {
data.bbox = map.getBounds().wrap().toBBoxString();
}
url: window.location.pathname,
method: "GET",
data: data,
- success: function(html) {
- $('#sidebar_content .changesets').html(html);
+ success: function (html) {
+ $("#sidebar_content .changesets").html(html);
updateMap();
}
});
- var feedLink = $('link[type="application/atom+xml"]'),
- feedHref = feedLink.attr('href').split('?')[0];
+ var feedLink = $("link[type=\"application/atom+xml\"]"),
+ feedHref = feedLink.attr("href").split("?")[0];
- feedLink.attr('href', feedHref + '?bbox=' + data.bbox);
+ feedLink.attr("href", feedHref + "?bbox=" + data.bbox);
}
function loadMore(e) {
$(this).hide();
div.find(".loader").show();
- $.get($(this).attr("href"), function(data) {
+ $.get($(this).attr("href"), function (data) {
div.replaceWith(data);
updateMap();
});
function updateBounds() {
group.clearLayers();
- changesets.forEach(function(changeset) {
+ changesets.forEach(function (changeset) {
var bottomLeft = map.project(L.latLng(changeset.bbox.minlat, changeset.bbox.minlon)),
topRight = map.project(L.latLng(changeset.bbox.maxlat, changeset.bbox.maxlon)),
width = topRight.x - bottomLeft.x,
for (var i = 0; i < changesets.length; ++i) {
var changeset = changesets[i],
rect = L.rectangle(changeset.bounds,
- {weight: 2, color: "#FF9500", opacity: 1, fillColor: "#FFFFAF", fillOpacity: 0});
+ { weight: 2, color: "#FF9500", opacity: 1, fillColor: "#FFFFAF", fillOpacity: 0 });
rect.id = changeset.id;
rect.addTo(group);
}
}
function updateMap() {
- changesets = $("[data-changeset]").map(function (index,element) {
- return $(element).data('changeset');
+ changesets = $("[data-changeset]").map(function (index, element) {
+ return $(element).data("changeset");
}).get().filter(function (changeset) {
return changeset.bbox;
});
updateBounds();
- if (window.location.pathname !== '/history') {
+ if (window.location.pathname !== "/history") {
var bounds = group.getBounds();
if (bounds.isValid()) map.fitBounds(bounds);
}
}
- page.pushstate = page.popstate = function(path) {
+ page.pushstate = page.popstate = function (path) {
$("#history_tab").addClass("current");
OSM.loadSidebarContent(path, page.load);
};
- page.load = function() {
+ page.load = function () {
map.addLayer(group);
- if (window.location.pathname === '/history') {
+ if (window.location.pathname === "/history") {
map.on("moveend", update);
}
update();
};
- page.unload = function() {
+ page.unload = function () {
map.removeLayer(group);
map.off("moveend", update);
-OSM.NewNote = function(map) {
+OSM.NewNote = function (map) {
var noteLayer = map.noteLayer,
- content = $('#sidebar_content'),
+ content = $("#sidebar_content"),
page = {},
addNoteButton = $(".control-note .control-button"),
newNote,
e.preventDefault();
e.stopPropagation();
- if ($(this).hasClass('disabled')) return;
+ if ($(this).hasClass("disabled")) return;
- OSM.router.route('/note/new');
+ OSM.router.route("/note/new");
});
function createNote(marker, form, url) {
newNote = null;
noteLayer.removeLayer(marker);
addNoteButton.removeClass("active");
- OSM.router.route('/note/' + feature.properties.id);
+ OSM.router.route("/note/" + feature.properties.id);
}
}
};
function newHalo(loc, a) {
- if (a === 'dragstart' && map.hasLayer(halo)) {
+ if (a === "dragstart" && map.hasLayer(halo)) {
map.removeLayer(halo);
} else {
if (map.hasLayer(halo)) map.removeLayer(halo);
map.addLayer(noteLayer);
- var params = querystring.parse(path.substring(path.indexOf('?') + 1));
+ var params = querystring.parse(path.substring(path.indexOf("?") + 1));
var markerLatlng;
if (params.lat && params.lon) {
});
newNote = L.marker(markerLatlng, {
- icon: noteIcons["new"],
+ icon: noteIcons.new,
opacity: 0.9,
draggable: true
});
- newNote.on("dragstart dragend", function(a) {
+ newNote.on("dragstart dragend", function (a) {
newHalo(newNote.getLatLng(), a.type);
});
newNote.on("remove", function () {
addNoteButton.removeClass("active");
- }).on("dragstart",function () {
+ }).on("dragstart", function () {
$(newNote).stopTime("removenote");
}).on("dragend", function () {
content.find("textarea").focus();
$(e.target.form.add).prop("disabled", $(e.target).val() === "");
}
- content.find('input[type=submit]').on('click', function (e) {
+ content.find("input[type=submit]").on("click", function (e) {
e.preventDefault();
- createNote(newNote, e.target.form, '/api/0.6/notes.json');
+ createNote(newNote, e.target.form, "/api/0.6/notes.json");
});
return map.getState();
OSM.Note = function (map) {
- var content = $('#sidebar_content'),
+ var content = $("#sidebar_content"),
page = {},
halo, currentNote;
url: url,
type: method,
oauth: true,
- data: {text: $(form.text).val()},
+ data: { text: $(form.text).val() },
success: function () {
OSM.loadSidebarContent(window.location.pathname, page.load);
}
}
page.pushstate = page.popstate = function (path) {
- OSM.loadSidebarContent(path, function() {
- initialize(function() {
- var data = $('.details').data(),
- latLng = L.latLng(data.coordinates.split(','));
- if (!map.getBounds().contains(latLng)) moveToNote();
+ OSM.loadSidebarContent(path, function () {
+ initialize(function () {
+ var data = $(".details").data(),
+ latLng = L.latLng(data.coordinates.split(","));
+ if (!map.getBounds().contains(latLng)) moveToNote();
});
});
};
- page.load = function() {
+ page.load = function () {
initialize(moveToNote);
};
}
});
- content.find("textarea").val('').trigger("input");
+ content.find("textarea").val("").trigger("input");
- var data = $('.details').data(),
- latLng = L.latLng(data.coordinates.split(','));
+ var data = $(".details").data(),
+ latLng = L.latLng(data.coordinates.split(","));
if (!map.hasLayer(halo)) {
halo = L.circleMarker(latLng, {
}
function moveToNote() {
- var data = $('.details').data(),
- latLng = L.latLng(data.coordinates.split(','));
+ var data = $(".details").data(),
+ latLng = L.latLng(data.coordinates.split(","));
if (!window.location.hash || window.location.hash.match(/^#?c[0-9]+$/)) {
OSM.router.withoutMoveListener(function () {
- map.setView(latLng, 15, {reset: true});
+ map.setView(latLng, 15, { reset: true });
});
}
}
}
});
- noteLayer.on('click', function(e) {
+ noteLayer.on("click", function (e) {
if (e.layer.id) {
- OSM.router.route('/note/' + e.layer.id);
+ OSM.router.route("/note/" + e.layer.id);
}
});
return marker;
}
- noteLayer.getLayerId = function(marker) {
+ noteLayer.getLayerId = function (marker) {
return marker.id;
};
//= require jquery.simulate
-OSM.Query = function(map) {
+OSM.Query = function (map) {
var url = OSM.OVERPASS_URL,
queryButton = $(".control-query .control-button"),
- uninterestingTags = ['source', 'source_ref', 'source:ref', 'history', 'attribution', 'created_by', 'tiger:county', 'tiger:tlid', 'tiger:upload_uuid', 'KSJ2:curve_id', 'KSJ2:lat', 'KSJ2:lon', 'KSJ2:coordinate', 'KSJ2:filename', 'note:ja'],
+ uninterestingTags = ["source", "source_ref", "source:ref", "history", "attribution", "created_by", "tiger:county", "tiger:tlid", "tiger:upload_uuid", "KSJ2:curve_id", "KSJ2:lat", "KSJ2:lon", "KSJ2:coordinate", "KSJ2:filename", "note:ja"],
marker;
var featureStyle = {
var geometry = $(this).data("geometry");
if (geometry) map.removeLayer(geometry);
- if (!$(e.target).is('a')) {
+ if (!$(e.target).is("a")) {
$(this).find("a").simulate("click", e);
}
}
url: url,
method: "POST",
data: {
- data: "[timeout:10][out:json];" + query,
+ data: "[timeout:10][out:json];" + query
},
- success: function(results) {
+ success: function (results) {
var elements;
$section.find(".loader").stopTime("loading").hide();
.appendTo($ul);
}
},
- error: function(xhr, status, error) {
+ error: function (xhr, status, error) {
$section.find(".loader").stopTime("loading").hide();
$("<li>")
map.removeLayer(marker);
} else {
marker.setStyle({
- opacity: 1 - i * 0.1,
- fillOpacity: 0.5 - i * 0.05
+ opacity: 1 - (i * 0.1),
+ fillOpacity: 0.5 - (i * 0.05)
});
}
}, 10);
var page = {};
- page.pushstate = page.popstate = function(path) {
+ page.pushstate = page.popstate = function (path) {
OSM.loadSidebarContent(path, function () {
page.load(path, true);
});
};
- page.load = function(path, noCentre) {
- var params = querystring.parse(path.substring(path.indexOf('?') + 1)),
+ page.load = function (path, noCentre) {
+ var params = querystring.parse(path.substring(path.indexOf("?") + 1)),
latlng = L.latLng(params.lat, params.lon);
if (!window.location.hash && !noCentre && !map.getBounds().contains(latlng)) {
queryOverpass(params.lat, params.lon);
};
- page.unload = function(sameController) {
+ page.unload = function (sameController) {
if (!sameController) {
disableQueryMode();
}
//= require jquery.simulate
-OSM.Search = function(map) {
- $(".search_form input[name=query]").on("input", function(e) {
+OSM.Search = function (map) {
+ $(".search_form input[name=query]").on("input", function (e) {
if ($(e.target).val() === "") {
$(".describe_location").fadeIn(100);
} else {
}
});
- $(".search_form a.button.switch_link").on("click", function(e) {
+ $(".search_form a.button.switch_link").on("click", function (e) {
e.preventDefault();
var query = $(e.target).parent().parent().find("input[name=query]").val();
if (query) {
}
});
- $(".search_form").on("submit", function(e) {
+ $(".search_form").on("submit", function (e) {
e.preventDefault();
$("header").addClass("closed");
var query = $(this).find("input[name=query]").val();
}
});
- $(".describe_location").on("click", function(e) {
+ $(".describe_location").on("click", function (e) {
e.preventDefault();
var center = map.getCenter().wrap(),
precision = OSM.zoomPrecision(map.getZoom());
.on("mousedown", "p.search_results_entry:has(a.set_position)", function () {
var moved = false;
$(this).one("click", function (e) {
- if (!moved && !$(e.target).is('a')) {
+ if (!moved && !$(e.target).is("a")) {
$(this).find("a.set_position").simulate("click", e);
}
}).one("mousemove", function () {
});
});
+ var markers = L.layerGroup().addTo(map);
+
function clickSearchMore(e) {
e.preventDefault();
e.stopPropagation();
$(this).hide();
div.find(".loader").show();
- $.get($(this).attr("href"), function(data) {
+ $.get($(this).attr("href"), function (data) {
div.replaceWith(data);
});
}
if (!marker) {
var data = $(this).find("a.set_position").data();
- marker = L.marker([data.lat, data.lon], {icon: OSM.getUserIcon()});
+ marker = L.marker([data.lat, data.lon], { icon: OSM.getUserIcon() });
$(this).data("marker", marker);
}
e.stopPropagation();
}
- var markers = L.layerGroup().addTo(map);
-
var page = {};
- page.pushstate = page.popstate = function(path) {
- var params = querystring.parse(path.substring(path.indexOf('?') + 1));
+ page.pushstate = page.popstate = function (path) {
+ var params = querystring.parse(path.substring(path.indexOf("?") + 1));
$(".search_form input[name=query]").val(params.query);
$(".describe_location").hide();
OSM.loadSidebarContent(path, page.load);
};
- page.load = function() {
- $(".search_results_entry").each(function(index) {
+ page.load = function () {
+ $(".search_results_entry").each(function (index) {
var entry = $(this);
$.ajax({
url: entry.data("href"),
- method: 'GET',
+ method: "GET",
data: {
zoom: map.getZoom(),
minlon: map.getBounds().getWest(),
maxlon: map.getBounds().getEast(),
maxlat: map.getBounds().getNorth()
},
- success: function(html) {
+ success: function (html) {
entry.html(html);
// go to first result of first geocoder
if (index === 0) {
- var firstResult = entry.find('*[data-lat][data-lon]:first').first();
+ var firstResult = entry.find("*[data-lat][data-lon]:first").first();
if (firstResult.length) {
panToSearchResult(firstResult.data());
}
return map.getState();
};
- page.unload = function() {
+ page.unload = function () {
markers.clearLayers();
$(".search_form input[name=query]").val("");
$(".describe_location").fadeIn(100);
var control = L.control(options);
control.onAdd = function (map) {
- var $container = $('<div>')
- .attr('class', 'control-key');
-
- var button = $('<a>')
- .attr('class', 'control-button')
- .attr('href', '#')
- .html('<span class="icon key"></span>')
- .on('click', toggle)
+ var $container = $("<div>")
+ .attr("class", "control-key");
+
+ var button = $("<a>")
+ .attr("class", "control-button")
+ .attr("href", "#")
+ .html("<span class=\"icon key\"></span>")
+ .on("click", toggle)
.appendTo($container);
- var $ui = $('<div>')
- .attr('class', 'key-ui');
+ var $ui = $("<div>")
+ .attr("class", "key-ui");
- $('<div>')
- .attr('class', 'sidebar_heading')
+ $("<div>")
+ .attr("class", "sidebar_heading")
.appendTo($ui)
.append(
- $('<span>')
- .text(I18n.t('javascripts.close'))
- .attr('class', 'icon close')
- .bind('click', toggle))
+ $("<span>")
+ .text(I18n.t("javascripts.close"))
+ .attr("class", "icon close")
+ .bind("click", toggle))
.append(
- $('<h4>')
- .text(I18n.t('javascripts.key.title')));
+ $("<h4>")
+ .text(I18n.t("javascripts.key.title")));
- var $section = $('<div>')
- .attr('class', 'section')
+ var $section = $("<div>")
+ .attr("class", "section")
.appendTo($ui);
options.sidebar.addPane($ui);
$ui
- .on('show', shown)
- .on('hide', hidden);
+ .on("show", shown)
+ .on("hide", hidden);
- map.on('baselayerchange', updateButton);
+ map.on("baselayerchange", updateButton);
updateButton();
function shown() {
- map.on('zoomend baselayerchange', update);
- $section.load('/key', update);
+ map.on("zoomend baselayerchange", update);
+ $section.load("/key", update);
}
function hidden() {
- map.off('zoomend baselayerchange', update);
+ map.off("zoomend baselayerchange", update);
}
function toggle(e) {
e.stopPropagation();
e.preventDefault();
- if (!button.hasClass('disabled')) {
+ if (!button.hasClass("disabled")) {
options.sidebar.togglePane($ui, button);
}
- $('.leaflet-control .control-button').tooltip('hide');
+ $(".leaflet-control .control-button").tooltip("hide");
}
function updateButton() {
- var disabled = ['mapnik', 'cyclemap'].indexOf(map.getMapBaseLayerId()) === -1;
+ var disabled = ["mapnik", "cyclemap"].indexOf(map.getMapBaseLayerId()) === -1;
button
- .toggleClass('disabled', disabled)
- .attr('data-original-title',
+ .toggleClass("disabled", disabled)
+ .attr("data-original-title",
I18n.t(disabled ?
- 'javascripts.key.tooltip_disabled' :
- 'javascripts.key.tooltip'));
+ "javascripts.key.tooltip_disabled" :
+ "javascripts.key.tooltip"));
}
function update() {
var layer = map.getMapBaseLayerId(),
zoom = map.getZoom();
- $('.mapkey-table-entry').each(function () {
+ $(".mapkey-table-entry").each(function () {
var data = $(this).data();
if (layer === data.layer && zoom >= data.zoomMin && zoom <= data.zoomMax) {
$(this).show();
-L.OSM.layers = function(options) {
+L.OSM.layers = function (options) {
var control = L.control(options);
control.onAdd = function (map) {
var layers = options.layers;
- var $container = $('<div>')
- .attr('class', 'control-layers');
+ var $container = $("<div>")
+ .attr("class", "control-layers");
- var button = $('<a>')
- .attr('class', 'control-button')
- .attr('href', '#')
- .attr('title', I18n.t('javascripts.map.layers.title'))
- .html('<span class="icon layers"></span>')
- .on('click', toggle)
+ var button = $("<a>")
+ .attr("class", "control-button")
+ .attr("href", "#")
+ .attr("title", I18n.t("javascripts.map.layers.title"))
+ .html("<span class=\"icon layers\"></span>")
+ .on("click", toggle)
.appendTo($container);
- var $ui = $('<div>')
- .attr('class', 'layers-ui');
+ var $ui = $("<div>")
+ .attr("class", "layers-ui");
- $('<div>')
- .attr('class', 'sidebar_heading')
+ $("<div>")
+ .attr("class", "sidebar_heading")
.appendTo($ui)
.append(
- $('<span>')
- .text(I18n.t('javascripts.close'))
- .attr('class', 'icon close')
- .bind('click', toggle))
+ $("<span>")
+ .text(I18n.t("javascripts.close"))
+ .attr("class", "icon close")
+ .bind("click", toggle))
.append(
- $('<h4>')
- .text(I18n.t('javascripts.map.layers.header')));
+ $("<h4>")
+ .text(I18n.t("javascripts.map.layers.header")));
- var baseSection = $('<div>')
- .attr('class', 'section base-layers')
+ var baseSection = $("<div>")
+ .attr("class", "section base-layers")
.appendTo($ui);
- var baseLayers = $('<ul>')
+ var baseLayers = $("<ul>")
.appendTo(baseSection);
- layers.forEach(function(layer) {
- var item = $('<li>')
+ layers.forEach(function (layer) {
+ var item = $("<li>")
.appendTo(baseLayers);
if (map.hasLayer(layer)) {
- item.addClass('active');
+ item.addClass("active");
}
- var div = $('<div>')
+ var div = $("<div>")
.appendTo(item);
- map.whenReady(function() {
- var miniMap = L.map(div[0], {attributionControl: false, zoomControl: false, keyboard: false})
+ map.whenReady(function () {
+ var miniMap = L.map(div[0], { attributionControl: false, zoomControl: false, keyboard: false })
.addLayer(new layer.constructor({ apikey: layer.options.apikey }));
miniMap.dragging.disable();
miniMap.scrollWheelZoom.disable();
$ui
- .on('show', shown)
- .on('hide', hide);
+ .on("show", shown)
+ .on("hide", hide);
function shown() {
miniMap.invalidateSize();
- setView({animate: false});
- map.on('moveend', moved);
+ setView({ animate: false });
+ map.on("moveend", moved);
}
function hide() {
- map.off('moveend', moved);
+ map.off("moveend", moved);
}
function moved() {
}
});
- var label = $('<label>')
+ var label = $("<label>")
.appendTo(item);
- var input = $('<input>')
- .attr('type', 'radio')
- .prop('checked', map.hasLayer(layer))
+ var input = $("<input>")
+ .attr("type", "radio")
+ .prop("checked", map.hasLayer(layer))
.appendTo(label);
label.append(layer.options.name);
- item.on('click', function() {
- layers.forEach(function(other) {
+ item.on("click", function () {
+ layers.forEach(function (other) {
if (other === layer) {
map.addLayer(other);
} else {
map.removeLayer(other);
}
});
- map.fire('baselayerchange', {layer: layer});
+ map.fire("baselayerchange", { layer: layer });
});
- item.on('dblclick', toggle);
+ item.on("dblclick", toggle);
- map.on('layeradd layerremove', function() {
- item.toggleClass('active', map.hasLayer(layer));
- input.prop('checked', map.hasLayer(layer));
+ map.on("layeradd layerremove", function () {
+ item.toggleClass("active", map.hasLayer(layer));
+ input.prop("checked", map.hasLayer(layer));
});
});
- if (OSM.STATUS !== 'api_offline' && OSM.STATUS !== 'database_offline') {
- var overlaySection = $('<div>')
- .attr('class', 'section overlay-layers')
+ if (OSM.STATUS !== "api_offline" && OSM.STATUS !== "database_offline") {
+ var overlaySection = $("<div>")
+ .attr("class", "section overlay-layers")
.appendTo($ui);
- $('<p>')
- .text(I18n.t('javascripts.map.layers.overlays'))
+ $("<p>")
+ .text(I18n.t("javascripts.map.layers.overlays"))
.attr("class", "deemphasize")
.appendTo(overlaySection);
- var overlays = $('<ul>')
+ var overlays = $("<ul>")
.appendTo(overlaySection);
var addOverlay = function (layer, name, maxArea) {
- var item = $('<li>')
+ var item = $("<li>")
.tooltip({
- placement: 'top'
+ placement: "top"
})
.appendTo(overlays);
- var label = $('<label>')
+ var label = $("<label>")
.appendTo(item);
var checked = map.hasLayer(layer);
- var input = $('<input>')
- .attr('type', 'checkbox')
- .prop('checked', checked)
+ var input = $("<input>")
+ .attr("type", "checkbox")
+ .prop("checked", checked)
.appendTo(label);
- label.append(I18n.t('javascripts.map.layers.' + name));
+ label.append(I18n.t("javascripts.map.layers." + name));
- input.on('change', function() {
- checked = input.is(':checked');
+ input.on("change", function () {
+ checked = input.is(":checked");
if (checked) {
map.addLayer(layer);
} else {
map.removeLayer(layer);
}
- map.fire('overlaylayerchange', {layer: layer});
+ map.fire("overlaylayerchange", { layer: layer });
});
- map.on('layeradd layerremove', function() {
- input.prop('checked', map.hasLayer(layer));
+ map.on("layeradd layerremove", function () {
+ input.prop("checked", map.hasLayer(layer));
});
- map.on('zoomend', function() {
+ map.on("zoomend", function () {
var disabled = map.getBounds().getSize() >= maxArea;
- $(input).prop('disabled', disabled);
+ $(input).prop("disabled", disabled);
- if (disabled && $(input).is(':checked')) {
- $(input).prop('checked', false)
- .trigger('change');
+ if (disabled && $(input).is(":checked")) {
+ $(input).prop("checked", false)
+ .trigger("change");
checked = true;
- } else if (!disabled && !$(input).is(':checked') && checked) {
- $(input).prop('checked', true)
- .trigger('change');
+ } else if (!disabled && !$(input).is(":checked") && checked) {
+ $(input).prop("checked", true)
+ .trigger("change");
}
- $(item).attr('class', disabled ? 'disabled' : '');
- item.attr('data-original-title', disabled ?
- I18n.t('javascripts.site.map_' + name + '_zoom_in_tooltip') : '');
+ $(item).attr("class", disabled ? "disabled" : "");
+ item.attr("data-original-title", disabled ?
+ I18n.t("javascripts.site.map_" + name + "_zoom_in_tooltip") : "");
});
};
- addOverlay(map.noteLayer, 'notes', OSM.MAX_NOTE_REQUEST_AREA);
- addOverlay(map.dataLayer, 'data', OSM.MAX_REQUEST_AREA);
- addOverlay(map.gpsLayer, 'gps', Number.POSITIVE_INFINITY);
+ addOverlay(map.noteLayer, "notes", OSM.MAX_NOTE_REQUEST_AREA);
+ addOverlay(map.dataLayer, "data", OSM.MAX_REQUEST_AREA);
+ addOverlay(map.gpsLayer, "gps", Number.POSITIVE_INFINITY);
}
options.sidebar.addPane($ui);
e.stopPropagation();
e.preventDefault();
options.sidebar.togglePane($ui, button);
- $('.leaflet-control .control-button').tooltip('hide');
+ $(".leaflet-control .control-button").tooltip("hide");
}
return $container[0];
});
L.OSM.Map = L.Map.extend({
- initialize: function(id, options) {
+ initialize: function (id, options) {
L.Map.prototype.initialize.call(this, id, options);
- var copyright = I18n.t('javascripts.map.copyright', {copyright_url: '/copyright'});
- var donate = I18n.t('javascripts.map.donate_link_text', {donate_url: 'https://donate.openstreetmap.org'});
+ var copyright = I18n.t("javascripts.map.copyright", { copyright_url: "/copyright" });
+ var donate = I18n.t("javascripts.map.donate_link_text", { donate_url: "https://donate.openstreetmap.org" });
+ var terms = I18n.t("javascripts.map.terms", { terms_url: "https://wiki.osmfoundation.org/wiki/Terms_of_Use" });
this.baseLayers = [];
this.baseLayers.push(new L.OSM.Mapnik({
- attribution: copyright + " ♥ " + donate,
+ attribution: copyright + " ♥ " + donate + ". " + terms,
code: "M",
keyid: "mapnik",
name: I18n.t("javascripts.map.base.standard")
if (OSM.THUNDERFOREST_KEY) {
this.baseLayers.push(new L.OSM.CycleMap({
- attribution: copyright + ". Tiles courtesy of <a href='https://www.thunderforest.com/' target='_blank'>Andy Allan</a>",
+ attribution: copyright + ". Tiles courtesy of <a href='https://www.thunderforest.com/' target='_blank'>Andy Allan</a>. " + terms,
apikey: OSM.THUNDERFOREST_KEY,
code: "C",
keyid: "cyclemap",
}));
this.baseLayers.push(new L.OSM.TransportMap({
- attribution: copyright + ". Tiles courtesy of <a href='https://www.thunderforest.com/' target='_blank'>Andy Allan</a>",
+ attribution: copyright + ". Tiles courtesy of <a href='https://www.thunderforest.com/' target='_blank'>Andy Allan</a>. " + terms,
apikey: OSM.THUNDERFOREST_KEY,
code: "T",
keyid: "transportmap",
}
this.baseLayers.push(new L.OSM.HOT({
- attribution: copyright + ". Tiles style by <a href='https://www.hotosm.org/' target='_blank'>Humanitarian OpenStreetMap Team</a>" + " hosted by <a href='https://openstreetmap.fr/' target='_blank'>OpenStreetMap France</a>",
+ attribution: copyright + ". Tiles style by <a href='https://www.hotosm.org/' target='_blank'>Humanitarian OpenStreetMap Team</a> hosted by <a href='https://openstreetmap.fr/' target='_blank'>OpenStreetMap France</a>. " + terms,
code: "H",
keyid: "hot",
name: I18n.t("javascripts.map.base.hot")
}));
this.noteLayer = new L.FeatureGroup();
- this.noteLayer.options = {code: 'N'};
+ this.noteLayer.options = { code: "N" };
this.dataLayer = new L.OSM.DataLayer(null);
- this.dataLayer.options.code = 'D';
+ this.dataLayer.options.code = "D";
this.gpsLayer = new L.OSM.GPS({
pane: "overlayPane",
});
},
- updateLayers: function(layerParam) {
+ updateLayers: function (layerParam) {
layerParam = layerParam || "M";
var layersAdded = "";
},
getLayersCode: function () {
- var layerConfig = '';
- for (var i in this._layers) { // TODO: map.eachLayer
- var layer = this._layers[i];
+ var layerConfig = "";
+ this.eachLayer(function (layer) {
if (layer.options && layer.options.code) {
layerConfig += layer.options.code;
}
- }
+ });
return layerConfig;
},
getMapBaseLayerId: function () {
- for (var i in this._layers) { // TODO: map.eachLayer
- var layer = this._layers[i];
- if (layer.options && layer.options.keyid) return layer.options.keyid;
- }
+ var baseLayerId;
+ this.eachLayer(function (layer) {
+ if (layer.options && layer.options.keyid) baseLayerId = layer.options.keyid;
+ });
+ return baseLayerId;
},
- getUrl: function(marker) {
+ getUrl: function (marker) {
var precision = OSM.zoomPrecision(this.getZoom()),
params = {};
params.mlon = latLng.lng.toFixed(precision);
}
- var url = window.location.protocol + '//' + OSM.SERVER_URL + '/',
+ var url = window.location.protocol + "//" + OSM.SERVER_URL + "/",
query = querystring.stringify(params),
hash = OSM.formatHash(this);
- if (query) url += '?' + query;
+ if (query) url += "?" + query;
if (hash) url += hash;
return url;
},
- getShortUrl: function(marker) {
+ getShortUrl: function (marker) {
var zoom = this.getZoom(),
latLng = marker && this.hasLayer(marker) ? marker.getLatLng().wrap() : this.getCenter().wrap(),
str = window.location.hostname.match(/^www\.openstreetmap\.org/i) ?
- window.location.protocol + '//osm.org/go/' :
- window.location.protocol + '//' + window.location.hostname + '/go/',
+ window.location.protocol + "//osm.org/go/" :
+ window.location.protocol + "//" + window.location.hostname + "/go/",
char_array = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_~",
x = Math.round((latLng.lng + 180.0) * ((1 << 30) / 90.0)),
y = Math.round((latLng.lat + 90.0) * ((1 << 30) / 45.0)),
// done in two parts. each of the parts c1/c2 has 30 bits of the total in it
// and drops the last 4 bits of the full 64 bit Morton code.
c1 = interlace(x >>> 17, y >>> 17), c2 = interlace((x >>> 2) & 0x7fff, (y >>> 2) & 0x7fff),
- digit;
+ digit,
+ i;
- for (var i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
- digit = (c1 >> (24 - 6 * i)) & 0x3f;
+ for (i = 0; i < Math.ceil((zoom + 8) / 3.0) && i < 5; ++i) {
+ digit = (c1 >> (24 - (6 * i))) & 0x3f;
str += char_array.charAt(digit);
}
for (i = 5; i < Math.ceil((zoom + 8) / 3.0); ++i) {
- digit = (c2 >> (24 - 6 * (i - 5))) & 0x3f;
+ digit = (c2 >> (24 - (6 * (i - 5)))) & 0x3f;
str += char_array.charAt(digit);
}
for (i = 0; i < ((zoom + 8) % 3); ++i) str += "-";
}
var params = {};
- var layers = this.getLayersCode().replace('M', '');
+ var layers = this.getLayersCode().replace("M", "");
if (layers) {
params.layers = layers;
}
if (marker && this.hasLayer(marker)) {
- params.m = '';
+ params.m = "";
}
if (this._object) {
var query = querystring.stringify(params);
if (query) {
- str += '?' + query;
+ str += "?" + query;
}
return str;
},
- getGeoUri: function(marker) {
+ getGeoUri: function (marker) {
var precision = OSM.zoomPrecision(this.getZoom()),
latLng,
params = {};
params.lon = latLng.lng.toFixed(precision);
params.zoom = this.getZoom();
- return 'geo:' + params.lat + ',' + params.lon + '?z=' + params.zoom;
+ return "geo:" + params.lat + "," + params.lon + "?z=" + params.zoom;
},
- addObject: function(object, callback) {
+ addObject: function (object, callback) {
var objectStyle = {
color: "#FF6200",
weight: 4,
var changesetStyle = {
weight: 4,
- color: '#FF9500',
+ color: "#FF9500",
opacity: 1,
fillOpacity: 0,
interactive: false
if (object.type === "node") {
return true;
} else if (object.type === "relation") {
- for (var i = 0; i < relations.length; i++)
- if (relations[i].members.indexOf(node) !== -1)
- return true;
+ for (var i = 0; i < relations.length; i++) {
+ if (relations[i].members.indexOf(node) !== -1) return true;
+ }
} else {
return false;
}
});
},
- removeObject: function() {
+ removeObject: function () {
this._object = null;
if (this._objectLoader) this._objectLoader.abort();
if (this._objectLayer) this.removeLayer(this._objectLayer);
},
- getState: function() {
+ getState: function () {
return {
center: this.getCenter().wrap(),
zoom: this.getZoom(),
};
},
- setState: function(state, options) {
+ setState: function (state, options) {
if (state.center) this.setView(state.center, state.zoom, options);
if (state.layers) this.updateLayers(state.layers);
},
- setSidebarOverlaid: function(overlaid) {
+ setSidebarOverlaid: function (overlaid) {
if (overlaid && !$("#content").hasClass("overlay-sidebar")) {
$("#content").addClass("overlay-sidebar");
- this.invalidateSize({pan: false})
- .panBy([-350, 0], {animate: false});
+ this.invalidateSize({ pan: false })
+ .panBy([-350, 0], { animate: false });
} else if (!overlaid && $("#content").hasClass("overlay-sidebar")) {
- this.panBy([350, 0], {animate: false});
+ this.panBy([350, 0], { animate: false });
$("#content").removeClass("overlay-sidebar");
- this.invalidateSize({pan: false});
+ this.invalidateSize({ pan: false });
}
return this;
}
L.extend(L.Icon.Default.prototype, {
_oldGetIconUrl: L.Icon.Default.prototype._getIconUrl,
- _getIconUrl: function (name) {
+ _getIconUrl: function (name) {
var url = this._oldGetIconUrl(name);
return L.Icon.Default.imageUrls[url];
}
var control = L.control(options);
control.onAdd = function (map) {
- var $container = $('<div>')
- .attr('class', 'control-note');
+ var $container = $("<div>")
+ .attr("class", "control-note");
- var link = $('<a>')
- .attr('class', 'control-button')
- .attr('href', '#')
- .html('<span class="icon note"></span>')
+ var link = $("<a>")
+ .attr("class", "control-button")
+ .attr("href", "#")
+ .html("<span class=\"icon note\"></span>")
.appendTo($container);
- map.on('zoomend', update);
+ map.on("zoomend", update);
function update() {
var disabled = OSM.STATUS === "database_offline" || map.getZoom() < 12;
link
- .toggleClass('disabled', disabled)
- .attr('data-original-title', I18n.t(disabled ?
- 'javascripts.site.createnote_disabled_tooltip' :
- 'javascripts.site.createnote_tooltip'));
+ .toggleClass("disabled", disabled)
+ .attr("data-original-title", I18n.t(disabled ?
+ "javascripts.site.createnote_disabled_tooltip" :
+ "javascripts.site.createnote_tooltip"));
}
update();
var control = L.control(options);
control.onAdd = function (map) {
- var $container = $('<div>')
- .attr('class', 'control-query');
+ var $container = $("<div>")
+ .attr("class", "control-query");
- var link = $('<a>')
- .attr('class', 'control-button')
- .attr('href', '#')
- .html('<span class="icon query"></span>')
+ var link = $("<a>")
+ .attr("class", "control-button")
+ .attr("href", "#")
+ .html("<span class=\"icon query\"></span>")
.appendTo($container);
- map.on('zoomend', update);
+ map.on("zoomend", update);
update();
function update() {
- var wasDisabled = link.hasClass('disabled'),
+ var wasDisabled = link.hasClass("disabled"),
isDisabled = map.getZoom() < 14;
link
- .toggleClass('disabled', isDisabled)
- .attr('data-original-title', I18n.t(isDisabled ?
- 'javascripts.site.queryfeature_disabled_tooltip' :
- 'javascripts.site.queryfeature_tooltip'));
+ .toggleClass("disabled", isDisabled)
+ .attr("data-original-title", I18n.t(isDisabled ?
+ "javascripts.site.queryfeature_disabled_tooltip" :
+ "javascripts.site.queryfeature_tooltip"));
if (isDisabled && !wasDisabled) {
- link.trigger('disabled');
+ link.trigger("disabled");
} else if (wasDisabled && !isDisabled) {
- link.trigger('enabled');
+ link.trigger("enabled");
}
}
L.OSM.share = function (options) {
var control = L.control(options),
- marker = L.marker([0, 0], {draggable: true}),
+ marker = L.marker([0, 0], { draggable: true }),
locationFilter = new L.LocationFilter({
enableButton: false,
adjustButton: false
});
control.onAdd = function (map) {
- var $container = $('<div>')
- .attr('class', 'control-share');
-
- var button = $('<a>')
- .attr('class', 'control-button')
- .attr('href', '#')
- .attr('title', I18n.t('javascripts.share.title'))
- .html('<span class="icon share"></span>')
- .on('click', toggle)
+ var $container = $("<div>")
+ .attr("class", "control-share");
+
+ var button = $("<a>")
+ .attr("class", "control-button")
+ .attr("href", "#")
+ .attr("title", I18n.t("javascripts.share.title"))
+ .html("<span class=\"icon share\"></span>")
+ .on("click", toggle)
.appendTo($container);
- var $ui = $('<div>')
- .attr('class', 'share-ui');
+ var $ui = $("<div>")
+ .attr("class", "share-ui");
- $('<div>')
- .attr('class', 'sidebar_heading')
+ $("<div>")
+ .attr("class", "sidebar_heading")
.appendTo($ui)
.append(
- $('<span>')
- .text(I18n.t('javascripts.close'))
- .attr('class', 'icon close')
- .bind('click', toggle))
+ $("<span>")
+ .text(I18n.t("javascripts.close"))
+ .attr("class", "icon close")
+ .bind("click", toggle))
.append(
- $('<h4>')
- .text(I18n.t('javascripts.share.title')));
+ $("<h4>")
+ .text(I18n.t("javascripts.share.title")));
// Link / Embed
- var $linkSection = $('<div>')
- .attr('class', 'section share-link')
+ var $linkSection = $("<div>")
+ .attr("class", "section share-link")
.appendTo($ui);
- $('<h4>')
- .text(I18n.t('javascripts.share.link'))
+ $("<h4>")
+ .text(I18n.t("javascripts.share.link"))
.appendTo($linkSection);
- var $form = $('<form>')
- .attr('class', 'standard-form')
+ var $form = $("<form>")
+ .attr("class", "standard-form")
.appendTo($linkSection);
- $('<div>')
- .attr('class', 'form-row')
+ $("<div>")
+ .attr("class", "form-row")
.appendTo($form)
.append(
- $('<label>')
- .attr('for', 'link_marker')
+ $("<label>")
+ .attr("for", "link_marker")
.append(
- $('<input>')
- .attr('id', 'link_marker')
- .attr('type', 'checkbox')
- .bind('change', toggleMarker))
- .append(I18n.t('javascripts.share.include_marker')));
-
- $('<div>')
- .attr('class', 'share-tabs')
+ $("<input>")
+ .attr("id", "link_marker")
+ .attr("type", "checkbox")
+ .bind("change", toggleMarker))
+ .append(I18n.t("javascripts.share.include_marker")));
+
+ $("<div>")
+ .attr("class", "share-tabs")
.appendTo($form)
- .append($('<a>')
- .attr('class', 'active')
- .attr('for', 'long_input')
- .attr('id', 'long_link')
- .text(I18n.t('javascripts.share.long_link')))
- .append($('<a>')
- .attr('for', 'short_input')
- .attr('id', 'short_link')
- .text(I18n.t('javascripts.share.short_link')))
- .append($('<a>')
- .attr('for', 'embed_html')
- .attr('href', '#')
- .text(I18n.t('javascripts.share.embed')))
- .on('click', 'a', function(e) {
+ .append($("<a>")
+ .attr("class", "active")
+ .attr("for", "long_input")
+ .attr("id", "long_link")
+ .text(I18n.t("javascripts.share.long_link")))
+ .append($("<a>")
+ .attr("for", "short_input")
+ .attr("id", "short_link")
+ .text(I18n.t("javascripts.share.short_link")))
+ .append($("<a>")
+ .attr("for", "embed_html")
+ .attr("href", "#")
+ .text(I18n.t("javascripts.share.embed")))
+ .on("click", "a", function (e) {
e.preventDefault();
- var id = '#' + $(this).attr('for');
- $linkSection.find('.share-tabs a')
- .removeClass('active');
- $(this).addClass('active');
- $linkSection.find('.share-tab')
+ var id = "#" + $(this).attr("for");
+ $linkSection.find(".share-tabs a")
+ .removeClass("active");
+ $(this).addClass("active");
+ $linkSection.find(".share-tab")
.hide();
- $linkSection.find('.share-tab:has(' + id + ')')
+ $linkSection.find(".share-tab:has(" + id + ")")
.show()
- .find('input, textarea')
+ .find("input, textarea")
.select();
});
- $('<div>')
- .attr('class', 'form-row share-tab')
- .css('display', 'block')
+ $("<div>")
+ .attr("class", "form-row share-tab")
+ .css("display", "block")
.appendTo($form)
- .append($('<input>')
- .attr('id', 'long_input')
- .attr('type', 'text')
- .on('click', select));
+ .append($("<input>")
+ .attr("id", "long_input")
+ .attr("type", "text")
+ .on("click", select));
- $('<div>')
- .attr('class', 'form-row share-tab')
+ $("<div>")
+ .attr("class", "form-row share-tab")
.appendTo($form)
- .append($('<input>')
- .attr('id', 'short_input')
- .attr('type', 'text')
- .on('click', select));
+ .append($("<input>")
+ .attr("id", "short_input")
+ .attr("type", "text")
+ .on("click", select));
- $('<div>')
- .attr('class', 'form-row share-tab')
+ $("<div>")
+ .attr("class", "form-row share-tab")
.appendTo($form)
.append(
- $('<textarea>')
- .attr('id', 'embed_html')
- .on('click', select))
+ $("<textarea>")
+ .attr("id", "embed_html")
+ .on("click", select))
.append(
- $('<p>')
- .attr('class', 'deemphasize')
- .text(I18n.t('javascripts.share.paste_html'))
+ $("<p>")
+ .attr("class", "deemphasize")
+ .text(I18n.t("javascripts.share.paste_html"))
.appendTo($linkSection));
// Geo URI
- var $geoUriSection = $('<div>')
- .attr('class', 'section share-geo-uri')
+ var $geoUriSection = $("<div>")
+ .attr("class", "section share-geo-uri")
.appendTo($ui);
- $('<h4>')
- .text(I18n.t('javascripts.share.geo_uri'))
+ $("<h4>")
+ .text(I18n.t("javascripts.share.geo_uri"))
.appendTo($geoUriSection);
- $('<div>')
+ $("<div>")
.appendTo($geoUriSection)
- .append($('<a>')
- .attr('id', 'geo_uri'));
+ .append($("<a>")
+ .attr("id", "geo_uri"));
// Image
- var $imageSection = $('<div>')
- .attr('class', 'section share-image')
+ var $imageSection = $("<div>")
+ .attr("class", "section share-image")
.appendTo($ui);
- $('<h4>')
- .text(I18n.t('javascripts.share.image'))
+ $("<h4>")
+ .text(I18n.t("javascripts.share.image"))
.appendTo($imageSection);
- $('<div>')
- .attr('id', 'export-warning')
- .attr('class', 'deemphasize')
- .text(I18n.t('javascripts.share.only_standard_layer'))
+ $("<div>")
+ .attr("id", "export-warning")
+ .attr("class", "deemphasize")
+ .text(I18n.t("javascripts.share.only_standard_layer"))
.appendTo($imageSection);
- $form = $('<form>')
- .attr('id', 'export-image')
- .attr('class', 'standard-form')
- .attr('action', '/export/finish')
- .attr('method', 'post')
+ $form = $("<form>")
+ .attr("id", "export-image")
+ .attr("class", "standard-form")
+ .attr("action", "/export/finish")
+ .attr("method", "post")
.appendTo($imageSection);
- $('<div>')
- .attr('class', 'form-row')
+ $("<div>")
+ .attr("class", "form-row")
.appendTo($form)
.append(
- $('<label>')
- .attr('for', 'image_filter')
+ $("<label>")
+ .attr("for", "image_filter")
.append(
- $('<input>')
- .attr('id', 'image_filter')
- .attr('type', 'checkbox')
- .bind('change', toggleFilter))
- .append(I18n.t('javascripts.share.custom_dimensions')));
-
- $('<div>')
- .attr('class', 'form-row')
+ $("<input>")
+ .attr("id", "image_filter")
+ .attr("type", "checkbox")
+ .bind("change", toggleFilter))
+ .append(I18n.t("javascripts.share.custom_dimensions")));
+
+ $("<div>")
+ .attr("class", "form-row")
.appendTo($form)
.append(
- $('<label>')
- .attr('for', 'mapnik_format')
- .text(I18n.t('javascripts.share.format')))
- .append($('<select>')
- .attr('name', 'mapnik_format')
- .attr('id', 'mapnik_format')
- .append($('<option>').val('png').text('PNG').prop('selected', true))
- .append($('<option>').val('jpeg').text('JPEG'))
- .append($('<option>').val('svg').text('SVG'))
- .append($('<option>').val('pdf').text('PDF')));
-
- $('<div>')
- .attr('class', 'form-row')
+ $("<label>")
+ .attr("for", "mapnik_format")
+ .text(I18n.t("javascripts.share.format")))
+ .append($("<select>")
+ .attr("name", "mapnik_format")
+ .attr("id", "mapnik_format")
+ .append($("<option>").val("png").text("PNG").prop("selected", true))
+ .append($("<option>").val("jpeg").text("JPEG"))
+ .append($("<option>").val("svg").text("SVG"))
+ .append($("<option>").val("pdf").text("PDF")));
+
+ $("<div>")
+ .attr("class", "form-row")
.appendTo($form)
- .append($('<label>')
- .attr('for', 'mapnik_scale')
- .text(I18n.t('javascripts.share.scale')))
- .append('1 : ')
- .append($('<input>')
- .attr('name', 'mapnik_scale')
- .attr('id', 'mapnik_scale')
- .attr('type', 'text')
- .on('change', update));
-
- ['minlon', 'minlat', 'maxlon', 'maxlat'].forEach(function(name) {
- $('<input>')
- .attr('id', 'mapnik_' + name)
- .attr('name', name)
- .attr('type', 'hidden')
+ .append($("<label>")
+ .attr("for", "mapnik_scale")
+ .text(I18n.t("javascripts.share.scale")))
+ .append("1 : ")
+ .append($("<input>")
+ .attr("name", "mapnik_scale")
+ .attr("id", "mapnik_scale")
+ .attr("type", "text")
+ .on("change", update));
+
+ ["minlon", "minlat", "maxlon", "maxlat"].forEach(function (name) {
+ $("<input>")
+ .attr("id", "mapnik_" + name)
+ .attr("name", name)
+ .attr("type", "hidden")
.appendTo($form);
});
- $('<input>')
- .attr('name', 'format')
- .attr('value', 'mapnik')
- .attr('type', 'hidden')
+ $("<input>")
+ .attr("name", "format")
+ .attr("value", "mapnik")
+ .attr("type", "hidden")
.appendTo($form);
var csrf_param = $("meta[name=csrf-param]").attr("content"),
csrf_token = $("meta[name=csrf-token]").attr("content");
- $('<input>')
- .attr('name', csrf_param)
- .attr('value', csrf_token)
- .attr('type', 'hidden')
+ $("<input>")
+ .attr("name", csrf_param)
+ .attr("value", csrf_token)
+ .attr("type", "hidden")
.appendTo($form);
- $('<p>')
- .attr('class', 'deemphasize')
- .html(I18n.t('javascripts.share.image_size') + ' <span id="mapnik_image_width"></span> x <span id="mapnik_image_height"></span>')
+ $("<p>")
+ .attr("class", "deemphasize")
+ .html(I18n.t("javascripts.share.image_size") + " <span id=\"mapnik_image_width\"></span> x <span id=\"mapnik_image_height\"></span>")
.appendTo($form);
- $('<input>')
- .attr('type', 'submit')
- .attr('value', I18n.t('javascripts.share.download'))
+ $("<input>")
+ .attr("type", "submit")
+ .attr("value", I18n.t("javascripts.share.download"))
.appendTo($form);
locationFilter
- .on('change', update)
+ .on("change", update)
.addTo(map);
- marker.on('dragend', movedMarker);
- map.on('move', movedMap);
- map.on('moveend layeradd layerremove', update);
+ marker.on("dragend", movedMarker);
+ map.on("move", movedMap);
+ map.on("moveend layeradd layerremove", update);
options.sidebar.addPane($ui);
$ui
- .on('hide', hidden);
+ .on("hide", hidden);
function hidden() {
map.removeLayer(marker);
e.stopPropagation();
e.preventDefault();
- $('#mapnik_scale').val(getScale());
+ $("#mapnik_scale").val(getScale());
marker.setLatLng(map.getCenter());
update();
options.sidebar.togglePane($ui, button);
- $('.leaflet-control .control-button').tooltip('hide');
+ $(".leaflet-control .control-button").tooltip("hide");
}
function toggleMarker() {
- if ($(this).is(':checked')) {
+ if ($(this).is(":checked")) {
marker.setLatLng(map.getCenter());
map.addLayer(marker);
- map.options.scrollWheelZoom = map.options.doubleClickZoom = 'center';
+ map.options.scrollWheelZoom = map.options.doubleClickZoom = "center";
} else {
map.removeLayer(marker);
map.options.scrollWheelZoom = map.options.doubleClickZoom = true;
}
function toggleFilter() {
- if ($(this).is(':checked')) {
+ if ($(this).is(":checked")) {
locationFilter.setBounds(map.getBounds().pad(-0.2));
locationFilter.enable();
} else {
function movedMarker() {
if (map.hasLayer(marker)) {
- map.off('move', movedMap);
- map.on('moveend', updateOnce);
+ map.off("move", movedMap);
+ map.on("moveend", updateOnce);
map.panTo(marker.getLatLng());
}
}
function updateOnce() {
- map.off('moveend', updateOnce);
- map.on('move', movedMap);
+ map.off("moveend", updateOnce);
+ map.on("move", movedMap);
update();
}
function escapeHTML(string) {
var htmlEscapes = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- "'": '''
+ "&": "&",
+ "<": "<",
+ ">": ">",
+ "\"": """,
+ "'": "'"
};
- return string === null ? '' : (string + '').replace(/[&<>"']/g, function(match) {
+ return string === null ? "" : String(string).replace(/[&<>"']/g, function (match) {
return htmlEscapes[match];
});
}
function update() {
var bounds = map.getBounds();
- $('#link_marker')
- .prop('checked', map.hasLayer(marker));
+ $("#link_marker")
+ .prop("checked", map.hasLayer(marker));
- $('#image_filter')
- .prop('checked', locationFilter.isEnabled());
+ $("#image_filter")
+ .prop("checked", locationFilter.isEnabled());
// Link / Embed
- $('#short_input').val(map.getShortUrl(marker));
- $('#long_input').val(map.getUrl(marker));
- $('#short_link').attr('href', map.getShortUrl(marker));
- $('#long_link').attr('href', map.getUrl(marker));
+ $("#short_input").val(map.getShortUrl(marker));
+ $("#long_input").val(map.getUrl(marker));
+ $("#short_link").attr("href", map.getShortUrl(marker));
+ $("#long_link").attr("href", map.getUrl(marker));
var params = {
bbox: bounds.toBBoxString(),
if (map.hasLayer(marker)) {
var latLng = marker.getLatLng().wrap();
- params.marker = latLng.lat + ',' + latLng.lng;
+ params.marker = latLng.lat + "," + latLng.lng;
}
- $('#embed_html').val(
- '<iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' +
- escapeHTML(OSM.SERVER_PROTOCOL + '://' + OSM.SERVER_URL + '/export/embed.html?' + $.param(params)) +
- '" style="border: 1px solid black"></iframe><br/>' +
- '<small><a href="' + escapeHTML(map.getUrl(marker)) + '">' +
- escapeHTML(I18n.t('javascripts.share.view_larger_map')) + '</a></small>');
+ $("#embed_html").val(
+ "<iframe width=\"425\" height=\"350\" frameborder=\"0\" scrolling=\"no\" marginheight=\"0\" marginwidth=\"0\" src=\"" +
+ escapeHTML(OSM.SERVER_PROTOCOL + "://" + OSM.SERVER_URL + "/export/embed.html?" + $.param(params)) +
+ "\" style=\"border: 1px solid black\"></iframe><br/>" +
+ "<small><a href=\"" + escapeHTML(map.getUrl(marker)) + "\">" +
+ escapeHTML(I18n.t("javascripts.share.view_larger_map")) + "</a></small>");
// Geo URI
- $('#geo_uri')
- .attr('href', map.getGeoUri(marker))
+ $("#geo_uri")
+ .attr("href", map.getGeoUri(marker))
.html(map.getGeoUri(marker));
// Image
L.CRS.EPSG3857.project(bounds.getNorthEast())).getSize(),
maxScale = Math.floor(Math.sqrt(size.x * size.y / 0.3136));
- $('#mapnik_minlon').val(bounds.getWest());
- $('#mapnik_minlat').val(bounds.getSouth());
- $('#mapnik_maxlon').val(bounds.getEast());
- $('#mapnik_maxlat').val(bounds.getNorth());
+ $("#mapnik_minlon").val(bounds.getWest());
+ $("#mapnik_minlat").val(bounds.getSouth());
+ $("#mapnik_maxlon").val(bounds.getEast());
+ $("#mapnik_maxlat").val(bounds.getNorth());
if (scale < maxScale) {
scale = roundScale(maxScale);
$("#mapnik_image_width").text(Math.round(size.x / scale / 0.00028));
$("#mapnik_image_height").text(Math.round(size.y / scale / 0.00028));
- if (map.getMapBaseLayerId() === 'mapnik') {
- $('#export-image').show();
- $('#export-warning').hide();
+ if (map.getMapBaseLayerId() === "mapnik") {
+ $("#export-image").show();
+ $("#export-warning").hide();
} else {
- $('#export-image').hide();
- $('#export-warning').show();
+ $("#export-image").hide();
+ $("#export-warning").show();
}
}
-L.OSM.sidebar = function(selector) {
+L.OSM.sidebar = function (selector) {
var control = {},
sidebar = $(selector),
current = $(),
- currentButton = $(),
+ currentButton = $(),
map;
control.addTo = function (_) {
return control;
};
- control.addPane = function(pane) {
+ control.addPane = function (pane) {
pane
.hide()
.appendTo(sidebar);
};
- control.togglePane = function(pane, button) {
+ control.togglePane = function (pane, button) {
current
.hide()
- .trigger('hide');
+ .trigger("hide");
currentButton
- .removeClass('active');
+ .removeClass("active");
if (current === pane) {
$(sidebar).hide();
currentButton = button || $();
}
- map.invalidateSize({pan: false, animate: false});
+ map.invalidateSize({ pan: false, animate: false });
current
.show()
- .trigger('show');
+ .trigger("show");
currentButton
- .addClass('active');
+ .addClass("active");
};
return control;
L.OSM.Zoom = L.Control.extend({
options: {
- position: 'topright'
+ position: "topright"
},
onAdd: function (map) {
- var zoomName = 'zoom',
- container = L.DomUtil.create('div', zoomName);
+ var zoomName = "zoom",
+ container = L.DomUtil.create("div", zoomName);
this._map = map;
- this._zoomInButton = this._createButton(
- '', I18n.t('javascripts.map.zoom.in'), zoomName + 'in', container, this._zoomIn, this);
+ this._zoomInButton = this._createButton(
+ "", I18n.t("javascripts.map.zoom.in"), zoomName + "in", container, this._zoomIn, this);
this._zoomOutButton = this._createButton(
- '', I18n.t('javascripts.map.zoom.out'), zoomName + 'out', container, this._zoomOut, this);
+ "", I18n.t("javascripts.map.zoom.out"), zoomName + "out", container, this._zoomOut, this);
- map.on('zoomend zoomlevelschange', this._updateDisabled, this);
+ map.on("zoomend zoomlevelschange", this._updateDisabled, this);
return container;
},
onRemove: function (map) {
- map.off('zoomend zoomlevelschange', this._updateDisabled, this);
+ map.off("zoomend zoomlevelschange", this._updateDisabled, this);
},
_zoomIn: function (e) {
},
_createButton: function (html, title, className, container, fn, context) {
- var link = L.DomUtil.create('a', 'control-button ' + className, container);
+ var link = L.DomUtil.create("a", "control-button " + className, container);
link.innerHTML = html;
- link.href = '#';
+ link.href = "#";
link.title = title;
- L.DomUtil.create('span', 'icon ' + className, link);
+ L.DomUtil.create("span", "icon " + className, link);
var stop = L.DomEvent.stopPropagation;
L.DomEvent
- .on(link, 'click', stop)
- .on(link, 'mousedown', stop)
- .on(link, 'dblclick', stop)
- .on(link, 'click', L.DomEvent.preventDefault)
- .on(link, 'click', fn, context);
+ .on(link, "click", stop)
+ .on(link, "mousedown", stop)
+ .on(link, "dblclick", stop)
+ .on(link, "click", L.DomEvent.preventDefault)
+ .on(link, "click", fn, context);
return link;
},
_updateDisabled: function () {
var map = this._map,
- className = 'disabled';
+ className = "disabled";
L.DomUtil.removeClass(this._zoomInButton, className);
L.DomUtil.removeClass(this._zoomOutButton, className);
-$(document).ready(function() {
+$(document).ready(function () {
// Preserve location hash in referer
if (window.location.hash) {
$("#referer").val($("#referer").val() + window.location.hash);
});
// Add click handler to show OpenID field
- $("#openid_open_url").click(function() {
+ $("#openid_open_url").click(function () {
$("#openid_url").val("http://");
$("#login_auth_buttons").hide();
$("#login_openid_url").show();
$("#login_openid_submit").hide();
// Handle OpenID submission by redirecting to omniauth
- $("#openid_login_form").submit(function() {
+ $("#openid_login_form").submit(function () {
var action = $(this).prop("action"),
openid_url = $(this).find("#openid_url").val(),
referer = $(this).find("#openid_referer").val(),
var application_data = $("head").data();
function makeAbsolute(url) {
- var a = document.createElement('a');
+ var a = document.createElement("a");
a.href = url;
return a.href;
}
token_secret: application_data.tokenSecret
});
- $.ajaxPrefilter(function(options, jqxhr) {
+ $.ajaxPrefilter(function (options, jqxhr) {
if (options.oauth) {
options.headers = options.headers || {};
options.headers.Authorization = headerGenerator(options.type, makeAbsolute(options.url), jqxhr.data);
cache: true,
success: function () {
piwikTracker = Piwik.getTracker(base + "piwik.php", OSM.PIWIK.site);
-
+
if (OSM.user) {
piwikTracker.setUserId(OSM.user.toString());
}
piwikTracker.trackPageView();
piwikTracker.enableLinkTracking();
-
+
$("meta[name=piwik-goal]").each(function () {
piwikTracker.trackGoal($(this).attr("content"));
});
/* Hide the preview panes */
$(".richtext_preview").hide();
- /*
+ /*
* When the text in an edit pane is changed, clear the contents of
* the associated preview pne so that it will be regenerated when
* the user next switches to it.
*/
- $(".richtext_content textarea").change(function () {
+ $(".richtext_content textarea").change(function () {
$(this).parents(".richtext_container").find(".richtext_preview").empty();
});
`OSM.router.withoutMoveListener` to run a block of code that may update
move the map without the hash changing.
*/
-OSM.Router = function(map, rts) {
+OSM.Router = function (map, rts) {
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
function Route(path, controller) {
- var regexp = new RegExp('^' +
- path.replace(escapeRegExp, '\\$&')
- .replace(optionalParam, '(?:$1)?')
- .replace(namedParam, function(match, optional){
- return optional ? match : '([^\/]+)';
+ var regexp = new RegExp("^" +
+ path.replace(escapeRegExp, "\\$&")
+ .replace(optionalParam, "(?:$1)?")
+ .replace(namedParam, function (match, optional) {
+ return optional ? match : "([^\/]+)";
})
- .replace(splatParam, '(.*?)') + '(?:\\?.*)?$');
+ .replace(splatParam, "(.*?)") + "(?:\\?.*)?$");
var route = {};
- route.match = function(path) {
+ route.match = function (path) {
return regexp.test(path);
};
- route.run = function(action, path) {
+ route.run = function (action, path) {
var params = [];
if (path) {
- params = regexp.exec(path).map(function(param, i) {
+ params = regexp.exec(path).map(function (param, i) {
return (i > 0 && param) ? decodeURIComponent(param) : param;
});
}
}
var routes = [];
- for (var r in rts)
+ for (var r in rts) {
routes.push(new Route(r, rts[r]));
+ }
- routes.recognize = function(path) {
+ routes.recognize = function (path) {
for (var i = 0; i < this.length; i++) {
if (this[i].match(path)) return this[i];
}
};
- var currentPath = window.location.pathname.replace(/(.)\/$/, '$1') + window.location.search,
+ var currentPath = window.location.pathname.replace(/(.)\/$/, "$1") + window.location.search,
currentRoute = routes.recognize(currentPath),
currentHash = location.hash || OSM.formatHash(map);
var router = {};
if (window.history && window.history.pushState) {
- $(window).on('popstate', function(e) {
+ $(window).on("popstate", function (e) {
if (!e.originalEvent.state) return; // Is it a real popstate event or just a hash change?
var path = window.location.pathname + window.location.search,
route = routes.recognize(path);
if (path === currentPath) return;
- currentRoute.run('unload', null, route === currentRoute);
+ currentRoute.run("unload", null, route === currentRoute);
currentPath = path;
currentRoute = route;
- currentRoute.run('popstate', currentPath);
- map.setState(e.originalEvent.state, {animate: false});
+ currentRoute.run("popstate", currentPath);
+ map.setState(e.originalEvent.state, { animate: false });
});
router.route = function (url) {
- var path = url.replace(/#.*/, ''),
+ var path = url.replace(/#.*/, ""),
route = routes.recognize(path);
if (!route) return false;
- currentRoute.run('unload', null, route === currentRoute);
+ currentRoute.run("unload", null, route === currentRoute);
var state = OSM.parseHash(url);
map.setState(state);
window.history.pushState(state, document.title, url);
currentPath = path;
currentRoute = route;
- currentRoute.run('pushstate', currentPath);
+ currentRoute.run("pushstate", currentPath);
return true;
};
window.history.replaceState(OSM.parseHash(url), document.title, url);
};
- router.stateChange = function(state) {
+ router.stateChange = function (state) {
if (state.center) {
window.history.replaceState(state, document.title, OSM.formatHash(state));
} else {
window.location.assign(url);
};
- router.stateChange = function(state) {
+ router.stateChange = function (state) {
if (state.center) window.location.replace(OSM.formatHash(state));
};
}
- router.updateHash = function() {
+ router.updateHash = function () {
var hash = OSM.formatHash(map);
if (hash === currentHash) return;
currentHash = hash;
router.stateChange(OSM.parseHash(hash));
};
- router.hashUpdated = function() {
+ router.hashUpdated = function () {
var hash = location.hash;
if (hash === currentHash) return;
currentHash = hash;
router.withoutMoveListener = function (callback) {
function disableMoveListener() {
- map.off('moveend', router.updateHash);
- map.once('moveend', function () {
- map.on('moveend', router.updateHash);
+ map.off("moveend", router.updateHash);
+ map.once("moveend", function () {
+ map.on("moveend", router.updateHash);
});
}
- map.once('movestart', disableMoveListener);
+ map.once("movestart", disableMoveListener);
callback();
- map.off('movestart', disableMoveListener);
+ map.off("movestart", disableMoveListener);
};
- router.load = function() {
- var loadState = currentRoute.run('load', currentPath);
+ router.load = function () {
+ var loadState = currentRoute.run("load", currentPath);
router.stateChange(loadState || {});
};
currentRoute = routes.recognize(currentPath);
};
- map.on('moveend baselayerchange overlaylayerchange', router.updateHash);
- $(window).on('hashchange', router.hashUpdated);
+ map.on("moveend baselayerchange overlaylayerchange", router.updateHash);
+ $(window).on("hashchange", router.hashUpdated);
return router;
};
zoomControl: false
}).addLayer(new L.OSM.Mapnik());
- var position = $('html').attr('dir') === 'rtl' ? 'topleft' : 'topright';
+ var position = $("html").attr("dir") === "rtl" ? "topleft" : "topright";
- L.OSM.zoom({position: position})
+ L.OSM.zoom({ position: position })
.addTo(map);
var locate = L.control.locate({
position: position,
- icon: 'icon geolocate',
- iconLoading: 'icon geolocate',
+ icon: "icon geolocate",
+ iconLoading: "icon geolocate",
strings: {
- title: I18n.t('javascripts.map.locate.title'),
- popup: I18n.t('javascripts.map.locate.popup')
+ title: I18n.t("javascripts.map.locate.title"),
+ popup: I18n.t("javascripts.map.locate.popup")
}
}).addTo(map);
var locateContainer = locate.getContainer();
$(locateContainer)
- .removeClass('leaflet-control-locate leaflet-bar')
- .addClass('control-locate')
+ .removeClass("leaflet-control-locate leaflet-bar")
+ .addClass("control-locate")
.children("a")
- .attr('href', '#')
- .removeClass('leaflet-bar-part leaflet-bar-part-single')
- .addClass('control-button');
+ .attr("href", "#")
+ .removeClass("leaflet-bar-part leaflet-bar-part-single")
+ .addClass("control-button");
if (OSM.home) {
map.setView([OSM.home.lat, OSM.home.lon], 12);
}
if ($("#map").hasClass("set_location")) {
- var marker = L.marker([0, 0], {icon: OSM.getUserIcon()});
+ var marker = L.marker([0, 0], { icon: OSM.getUserIcon() });
if (OSM.home) {
marker.setLatLng([OSM.home.lat, OSM.home.lon]);
}
map.on("click", function (e) {
- if ($('#updatehome').is(':checked')) {
+ if ($("#updatehome").is(":checked")) {
var zoom = map.getZoom(),
precision = OSM.zoomPrecision(zoom),
location = e.latlng.wrap();
- $('#homerow').removeClass();
- $('#home_lat').val(location.lat.toFixed(precision));
- $('#home_lon').val(location.lng.toFixed(precision));
+ $("#homerow").removeClass();
+ $("#home_lat").val(location.lat.toFixed(precision));
+ $("#home_lon").val(location.lng.toFixed(precision));
marker.setLatLng(e.latlng);
marker.addTo(map);
});
} else {
$("[data-user]").each(function () {
- var user = $(this).data('user');
+ var user = $(this).data("user");
if (user.lon && user.lat) {
- L.marker([user.lat, user.lon], {icon: OSM.getUserIcon(user.icon)}).addTo(map)
+ L.marker([user.lat, user.lon], { icon: OSM.getUserIcon(user.icon) }).addTo(map)
.bindPopup(user.description);
}
});
$("#contributorTerms").html("<img src='" + OSM.SEARCHING + "' />");
$("#contributorTerms").load(url);
});
+
+ $("#read_ct").on("click", function () {
+ $("#continue").prop("disabled", !($(this).prop("checked") && $("#read_tou").prop("checked")));
+ });
+
+ $("#read_tou").on("click", function () {
+ $("#continue").prop("disabled", !($(this).prop("checked") && $("#read_ct").prop("checked")));
+ });
});
-$(document).ready(function() {
+$(document).ready(function () {
var params = OSM.params();
if (params.lat && params.lon) {
params.lon = parseFloat(params.lon);
params.zoom = params.zoom || 17;
- var url = '/edit';
+ var url = "/edit";
if (params.editor) {
- url += '?editor=' + params.editor;
+ url += "?editor=" + params.editor;
}
url += OSM.formatHash(params);
- $('.start-mapping').attr('href', url);
-
+ $(".start-mapping").attr("href", url);
} else {
var geoSuccess = function (position) {
- window.location = '/edit' + OSM.formatHash({
+ window.location = "/edit" + OSM.formatHash({
zoom: 17,
lat: position.coords.latitude,
lon: position.coords.longitude
});
};
- $('.start-mapping').on('click', function(e) {
+ $(".start-mapping").on("click", function (e) {
e.preventDefault();
- $('.start-mapping').addClass('loading');
+ $(".start-mapping").addClass("loading");
if (navigator.geolocation) {
// handle firefox's weird implementation
}
function manualEdit() {
- window.location = '/?edit_help=1';
+ window.location = "/?edit_help=1";
}
});
.diary_post {
position: relative;
- margin-top: $lineheight/2;
padding-top: $lineheight;
+ padding-bottom: $lineheight/2;
border-top: 1px solid #ccc;
+ &:first-of-type {
+ margin-top: $lineheight/2;
+ }
+
+ &.deemphasize {
+ background-color: #fee;
+ }
+
.post_heading {
margin-bottom: $lineheight;
max-width: 740px;
}
.diary-comment {
- margin-top: $lineheight/2;
border-top: 1px dashed #ccc;
padding-top: $lineheight/2;
+ padding-bottom: $lineheight/2;
&:first-child {
- margin-top: $lineheight;
+ margin-top: $lineheight/2;
padding-top: $lineheight;
border-top: 1px solid #ccc;
}
+ &.deemphasize {
+ background-color: #fee;
+ }
p {
margin-bottom: $lineheight/2;
}
def amf_handle_error(call, rootobj, rootid)
yield
- rescue OSM::APIAlreadyDeletedError => ex
- [-4, ex.object, ex.object_id]
- rescue OSM::APIVersionMismatchError => ex
- [-3, [rootobj, rootid], [ex.type.downcase, ex.id, ex.latest]]
- rescue OSM::APIUserChangesetMismatchError => ex
- [-2, ex.to_s]
- rescue OSM::APIBadBoundingBox => ex
- [-2, "Sorry - I can't get the map for that area. The server said: #{ex}"]
- rescue OSM::APIError => ex
- [-1, ex.to_s]
- rescue StandardError => ex
- [-2, "An unusual error happened (in #{call}). The server said: #{ex}"]
+ rescue OSM::APIAlreadyDeletedError => e
+ [-4, e.object, e.object_id]
+ rescue OSM::APIVersionMismatchError => e
+ [-3, [rootobj, rootid], [e.type.downcase, e.id, e.latest]]
+ rescue OSM::APIUserChangesetMismatchError => e
+ [-2, e.to_s]
+ rescue OSM::APIBadBoundingBox => e
+ [-2, "Sorry - I can't get the map for that area. The server said: #{e}"]
+ rescue OSM::APIError => e
+ [-1, e.to_s]
+ rescue StandardError => e
+ [-2, "An unusual error happened (in #{call}). The server said: #{e}"]
end
def amf_handle_error_with_timeout(call, rootobj, rootid)
end
# stupid Time seems to throw both of these for bad parsing, so
# we have to catch both and ensure the correct code path is taken.
- rescue ArgumentError => ex
- raise OSM::APIBadUserInput, ex.message.to_s
- rescue RuntimeError => ex
- raise OSM::APIBadUserInput, ex.message.to_s
+ rescue ArgumentError => e
+ raise OSM::APIBadUserInput, e.message.to_s
+ rescue RuntimeError => e
+ raise OSM::APIBadUserInput, e.message.to_s
end
##
bbox = BoundingBox.from_bbox_params(params)
bbox.check_boundaries
bbox.check_size
- rescue StandardError => err
- report_error(err.message)
+ rescue StandardError => e
+ report_error(e.message)
return
end
bbox = BoundingBox.from_bbox_params(params)
bbox.check_boundaries
bbox.check_size
- rescue StandardError => err
- report_error(err.message)
+ rescue StandardError => e
+ report_error(e.message)
return
end
authorize_resource
- before_action :check_database_readable, :except => [:api_read, :api_data]
- before_action :check_database_writable, :only => [:api_create, :api_update, :api_delete]
- before_action :check_api_readable, :only => [:api_read, :api_data]
- before_action :check_api_writable, :only => [:api_create, :api_update, :api_delete]
- before_action :offline_redirect, :only => [:api_create, :api_delete, :api_data]
+ before_action :check_database_readable, :except => [:show, :data]
+ before_action :check_database_writable, :only => [:create, :update, :destroy]
+ before_action :check_api_readable, :only => [:show, :data]
+ before_action :check_api_writable, :only => [:create, :update, :destroy]
+ before_action :offline_redirect, :only => [:create, :destroy, :data]
around_action :api_call_handle_error
- def api_read
+ def show
trace = Trace.visible.find(params[:id])
if trace.public? || trace.user == current_user
end
end
- def api_update
+ def update
trace = Trace.visible.find(params[:id])
if trace.user == current_user
end
end
- def api_delete
+ def destroy
trace = Trace.visible.find(params[:id])
if trace.user == current_user
end
end
- def api_data
+ def data
trace = Trace.visible.find(params[:id])
if trace.public? || trace.user == current_user
end
end
- def api_create
+ def create
tags = params[:tags] || ""
description = params[:description] || ""
visibility = params[:visibility]
trace = do_create(params[:file], tags, description, visibility)
if trace.id
- TraceImporterJob.perform_later(@trace) if Settings.trace_use_job_queue
+ TraceImporterJob.perform_later(trace) if Settings.trace_use_job_queue
render :plain => trace.id.to_s
elsif trace.valid?
head :internal_server_error
class UsersController < ApiController
layout "site", :except => [:api_details]
- before_action :disable_terms_redirect, :only => [:api_details]
- before_action :authorize, :only => [:api_details, :api_gpx_files]
+ before_action :disable_terms_redirect, :only => [:details]
+ before_action :authorize, :only => [:details, :gpx_files]
authorize_resource
before_action :check_api_readable
around_action :api_call_handle_error
- before_action :lookup_user_by_id, :only => [:api_read]
+ before_action :lookup_user_by_id, :only => [:show]
- def api_read
+ def show
if @user.visible?
- render :action => :api_read, :content_type => "text/xml"
+ render :action => :show, :content_type => "text/xml"
else
head :gone
end
end
- def api_details
+ def details
@user = current_user
- render :action => :api_read, :content_type => "text/xml"
+ render :action => :show, :content_type => "text/xml"
end
- def api_users
+ def index
raise OSM::APIBadUserInput, "The parameter users is required, and must be of the form users=id[,id[,id...]]" unless params["users"]
ids = params["users"].split(",").collect(&:to_i)
@users = User.visible.find(ids)
- render :action => :api_users, :content_type => "text/xml"
+ render :action => :index, :content_type => "text/xml"
end
- def api_gpx_files
+ def gpx_files
doc = OSM::API.new.get_xml_doc
current_user.traces.reload.each do |trace|
doc.root << trace.to_xml_node
elsif session[:token]
session[:user] = current_user.id if self.current_user = User.authenticate(:token => session[:token])
end
- rescue StandardError => ex
- logger.info("Exception authorizing user: #{ex}")
+ rescue StandardError => e
+ logger.info("Exception authorizing user: #{e}")
reset_session
self.current_user = nil
end
def api_call_handle_error
yield
- rescue ActiveRecord::RecordNotFound => ex
+ rescue ActiveRecord::RecordNotFound => e
head :not_found
- rescue LibXML::XML::Error, ArgumentError => ex
- report_error ex.message, :bad_request
- rescue ActiveRecord::RecordInvalid => ex
- message = "#{ex.record.class} #{ex.record.id}: "
- ex.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{ex.record[attr].inspect})" }
+ rescue LibXML::XML::Error, ArgumentError => e
+ report_error e.message, :bad_request
+ rescue ActiveRecord::RecordInvalid => e
+ message = "#{e.record.class} #{e.record.id}: "
+ e.record.errors.each { |attr, msg| message << "#{attr}: #{msg} (#{e.record[attr].inspect})" }
report_error message, :bad_request
- rescue OSM::APIError => ex
- report_error ex.message, ex.status
- rescue AbstractController::ActionNotFound => ex
+ rescue OSM::APIError => e
+ report_error e.message, e.status
+ rescue AbstractController::ActionNotFound => e
raise
- rescue StandardError => ex
- logger.info("API threw unexpected #{ex.class} exception: #{ex.message}")
- ex.backtrace.each { |l| logger.info(l) }
- report_error "#{ex.class}: #{ex.message}", :internal_server_error
+ rescue StandardError => e
+ logger.info("API threw unexpected #{e.class} exception: #{e.message}")
+ e.backtrace.each { |l| logger.info(l) }
+ report_error "#{e.class}: #{e.message}", :internal_server_error
end
##
OSM::Timer.timeout(Settings.web_timeout, Timeout::Error) do
yield
end
- rescue ActionView::Template::Error => ex
- ex = ex.cause
+ rescue ActionView::Template::Error => e
+ e = e.cause
- if ex.is_a?(Timeout::Error) ||
- (ex.is_a?(ActiveRecord::StatementInvalid) && ex.message =~ /execution expired/)
+ if e.is_a?(Timeout::Error) ||
+ (e.is_a?(ActiveRecord::StatementInvalid) && e.message =~ /execution expired/)
render :action => "timeout"
else
raise
authorize_resource
before_action :lookup_user, :only => [:show, :comments]
- before_action :check_database_writable, :only => [:new, :edit, :comment, :hide, :hidecomment, :subscribe, :unsubscribe]
- before_action :allow_thirdparty_images, :only => [:new, :edit, :index, :show, :comments]
+ before_action :check_database_writable, :only => [:new, :create, :edit, :update, :comment, :hide, :hidecomment, :subscribe, :unsubscribe]
+ before_action :allow_thirdparty_images, :only => [:new, :create, :edit, :update, :index, :show, :comments]
def new
@title = t "diary_entries.new.title"
- if request.post?
- @diary_entry = DiaryEntry.new(entry_params)
- @diary_entry.user = current_user
+ default_lang = current_user.preferences.where(:k => "diary.default_language").first
+ lang_code = default_lang ? default_lang.v : current_user.preferred_language
+ @diary_entry = DiaryEntry.new(entry_params.merge(:language_code => lang_code))
+ set_map_location
+ render :action => "new"
+ end
- if @diary_entry.save
- default_lang = current_user.preferences.where(:k => "diary.default_language").first
- if default_lang
- default_lang.v = @diary_entry.language_code
- default_lang.save!
- else
- current_user.preferences.create(:k => "diary.default_language", :v => @diary_entry.language_code)
- end
+ def create
+ @title = t "diary_entries.new.title"
- # Subscribe user to diary comments
- @diary_entry.subscriptions.create(:user => current_user)
+ @diary_entry = DiaryEntry.new(entry_params)
+ @diary_entry.user = current_user
- redirect_to :action => "index", :display_name => current_user.display_name
+ if @diary_entry.save
+ default_lang = current_user.preferences.where(:k => "diary.default_language").first
+ if default_lang
+ default_lang.v = @diary_entry.language_code
+ default_lang.save!
else
- render :action => "edit"
+ current_user.preferences.create(:k => "diary.default_language", :v => @diary_entry.language_code)
end
+
+ # Subscribe user to diary comments
+ @diary_entry.subscriptions.create(:user => current_user)
+
+ redirect_to :action => "index", :display_name => current_user.display_name
else
- default_lang = current_user.preferences.where(:k => "diary.default_language").first
- lang_code = default_lang ? default_lang.v : current_user.preferred_language
- @diary_entry = DiaryEntry.new(entry_params.merge(:language_code => lang_code))
- set_map_location
- render :action => "edit"
+ render :action => "new"
end
end
@title = t "diary_entries.edit.title"
@diary_entry = DiaryEntry.find(params[:id])
+ redirect_to diary_entry_path(@diary_entry.user, @diary_entry) if current_user != @diary_entry.user
+
+ set_map_location
+ rescue ActiveRecord::RecordNotFound
+ render :action => "no_such_entry", :status => :not_found
+ end
+
+ def update
+ @title = t "diary_entries.edit.title"
+ @diary_entry = DiaryEntry.find(params[:id])
+
if current_user != @diary_entry.user
redirect_to diary_entry_path(@diary_entry.user, @diary_entry)
elsif params[:diary_entry] && @diary_entry.update(entry_params)
redirect_to diary_entry_path(@diary_entry.user, @diary_entry)
+ else
+ set_map_location
+ render :action => "edit"
end
-
- set_map_location
rescue ActiveRecord::RecordNotFound
render :action => "no_such_entry", :status => :not_found
end
def comment
@entry = DiaryEntry.find(params[:id])
+ @comments = @entry.visible_comments
@diary_comment = @entry.comments.build(comment_params)
@diary_comment.user = current_user
if @diary_comment.save
@page = (params[:page] || 1).to_i
@page_size = 20
- @entries = @entries.visible
+ @entries = @entries.visible unless current_user&.administrator?
@entries = @entries.order("created_at DESC")
@entries = @entries.offset((@page - 1) * @page_size)
@entries = @entries.limit(@page_size)
else
@entries = DiaryEntry.joins(:user).where(:users => { :status => %w[active confirmed] })
+ # Items can't be flagged as deleted in the RSS format.
+ # For the general feeds, allow a delay before publishing, to help spam fighting
+ @entries = @entries.where("created_at < :time", :time => Settings.diary_feed_delay.hours.ago)
+
if params[:language]
@entries = @entries.where(:language_code => params[:language])
@title = t("diary_entries.feed.language.title", :language_name => Language.find(params[:language]).english_name)
@link = url_for :action => "index", :host => Settings.server_url, :protocol => Settings.server_protocol
end
end
-
@entries = @entries.visible.includes(:user).order("created_at DESC").limit(20)
end
@entry = @user.diary_entries.visible.where(:id => params[:id]).first
if @entry
@title = t "diary_entries.show.title", :user => params[:display_name], :title => @entry.title
+ @comments = current_user&.administrator? ? @entry.comments : @entry.visible_comments
else
@title = t "diary_entries.no_such_entry.title", :id => params[:id]
render :action => "no_such_entry", :status => :not_found
redirect_to :action => "index", :display_name => entry.user.display_name
end
+ def unhide
+ entry = DiaryEntry.find(params[:id])
+ entry.update(:visible => true)
+ redirect_to :action => "index", :display_name => entry.user.display_name
+ end
+
def hidecomment
comment = DiaryComment.find(params[:comment])
comment.update(:visible => false)
redirect_to diary_entry_path(comment.diary_entry.user, comment.diary_entry)
end
+ def unhidecomment
+ comment = DiaryComment.find(params[:comment])
+ comment.update(:visible => true)
+ redirect_to diary_entry_path(comment.diary_entry.user, comment.diary_entry)
+ end
+
def comments
@comment_pages, @comments = paginate(:diary_comments,
:conditions => {
end
render :action => "results"
- rescue StandardError => ex
- @error = "Error contacting geocoder.ca: #{ex}"
+ rescue StandardError => e
+ @error = "Error contacting geocoder.ca: #{e}"
render :action => "error"
end
end
render :action => "results"
- rescue StandardError => ex
- @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
+ rescue StandardError => e
+ @error = "Error contacting nominatim.openstreetmap.org: #{e}"
render :action => "error"
end
end
render :action => "results"
- rescue StandardError => ex
- @error = "Error contacting api.geonames.org: #{ex}"
+ rescue StandardError => e
+ @error = "Error contacting api.geonames.org: #{e}"
render :action => "error"
end
end
render :action => "results"
- rescue StandardError => ex
- @error = "Error contacting nominatim.openstreetmap.org: #{ex}"
+ rescue StandardError => e
+ @error = "Error contacting nominatim.openstreetmap.org: #{e}"
render :action => "error"
end
end
render :action => "results"
- rescue StandardError => ex
- @error = "Error contacting api.geonames.org: #{ex}"
+ rescue StandardError => e
+ @error = "Error contacting api.geonames.org: #{e}"
render :action => "error"
end
begin
@trace = do_create(params[:trace][:gpx_file], params[:trace][:tagstring],
params[:trace][:description], params[:trace][:visibility])
- rescue StandardError => ex
- logger.debug ex
+ rescue StandardError => e
+ logger.debug e
end
if @trace.id
def save
@title = t "users.new.title"
- if params[:decline]
+ if params[:decline] || !(params[:read_tou] && params[:read_ct])
if current_user
current_user.terms_seen = true
else
redirect_to :action => :account, :display_name => current_user.display_name
end
- else
+ elsif params[:decline]
redirect_to t("users.terms.declined")
+ else
+ redirect_to :action => :terms
end
elsif current_user
unless current_user.terms_agreed?
current_user.consider_pd = params[:user][:consider_pd]
+ current_user.tou_agreed = Time.now.getutc
current_user.terms_agreed = Time.now.getutc
current_user.terms_seen = true
current_user.creation_ip = request.remote_ip
current_user.languages = http_accept_language.user_preferred_languages
current_user.terms_agreed = Time.now.getutc
+ current_user.tou_agreed = Time.now.getutc
current_user.terms_seen = true
if current_user.auth_uid.blank?
I18n.t("user_blocks.helper.time_past", :time => friendly_date(last_time)).html_safe
end
end
+
+ def block_duration_in_words(duration)
+ parts = ActiveSupport::Duration.build(duration).parts
+ if duration < 1.day
+ I18n.t("user_blocks.helper.block_duration.hours", :count => parts[:hours])
+ elsif duration < 1.week
+ I18n.t("user_blocks.helper.block_duration.days", :count => parts[:days])
+ elsif duration < 1.month
+ I18n.t("user_blocks.helper.block_duration.weeks", :count => parts[:weeks])
+ elsif duration < 1.year
+ I18n.t("user_blocks.helper.block_duration.months", :count => parts[:months])
+ else
+ I18n.t("user_blocks.helper.block_duration.years", :count => parts[:years])
+ end
+ end
end
Notifier.gpx_failure(trace, "0 points parsed ok. Do they all have lat,lng,alt,timestamp?").deliver_later
trace.destroy
end
- rescue StandardError => ex
- logger.info ex.to_s
- ex.backtrace.each { |l| logger.info l }
- Notifier.gpx_failure(trace, ex.to_s + "\n" + ex.backtrace.join("\n")).deliver_later
+ rescue StandardError => e
+ logger.info e.to_s
+ e.backtrace.each { |l| logger.info l }
+ Notifier.gpx_failure(trace, e.to_s + "\n" + e.backtrace.join("\n")).deliver_later
trace.destroy
end
end
#
# Table name: acls
#
-# id :integer not null, primary key
+# id :bigint(8) not null, primary key
# address :inet
# k :string not null
# v :string
#
# Indexes
#
-# acls_k_idx (k)
+# acls_k_idx (k)
+# index_acls_on_address (address) USING gist
+# index_acls_on_domain (domain)
#
class Acl < ActiveRecord::Base
#
# Table name: changesets
#
-# id :integer not null, primary key
-# user_id :integer not null
+# id :bigint(8) not null, primary key
+# user_id :bigint(8) not null
# created_at :datetime not null
# min_lat :integer
# max_lat :integer
#
# Indexes
#
-# changesets_bbox_idx (min_lat,max_lat,min_lon,max_lon)
+# changesets_bbox_idx (min_lat,max_lat,min_lon,max_lon) USING gist
# changesets_closed_at_idx (closed_at)
# changesets_created_at_idx (created_at)
# changesets_user_id_created_at_idx (user_id,created_at)
return Changeset.from_xml_node(pt, create)
end
raise OSM::APIBadXMLError.new("changeset", xml, "XML doesn't contain an osm/changeset element.")
- rescue LibXML::XML::Error, ArgumentError => ex
- raise OSM::APIBadXMLError.new("changeset", xml, ex.message)
+ rescue LibXML::XML::Error, ArgumentError => e
+ raise OSM::APIBadXMLError.new("changeset", xml, e.message)
end
def self.from_xml_node(pt, create = false)
# Table name: changeset_comments
#
# id :integer not null, primary key
-# changeset_id :integer not null
-# author_id :integer not null
+# changeset_id :bigint(8) not null
+# author_id :bigint(8) not null
# body :text not null
# created_at :datetime not null
# visible :boolean not null
#
# Table name: changeset_tags
#
-# changeset_id :integer not null, primary key
+# changeset_id :bigint(8) not null, primary key
# k :string default(""), not null, primary key
# v :string default(""), not null
#
#
# Table name: diary_comments
#
-# id :integer not null, primary key
-# diary_entry_id :integer not null
-# user_id :integer not null
+# id :bigint(8) not null, primary key
+# diary_entry_id :bigint(8) not null
+# user_id :bigint(8) not null
# body :text not null
# created_at :datetime not null
# updated_at :datetime not null
#
# Table name: diary_entries
#
-# id :integer not null, primary key
-# user_id :integer not null
+# id :bigint(8) not null, primary key
+# user_id :bigint(8) not null
# title :string not null
# body :text not null
# created_at :datetime not null
#
# Table name: diary_entry_subscriptions
#
-# user_id :integer not null, primary key
-# diary_entry_id :integer not null, primary key
+# user_id :bigint(8) not null, primary key
+# diary_entry_id :bigint(8) not null, primary key
#
# Indexes
#
#
# Table name: friends
#
-# id :integer not null, primary key
-# user_id :integer not null
-# friend_user_id :integer not null
+# id :bigint(8) not null, primary key
+# user_id :bigint(8) not null
+# friend_user_id :bigint(8) not null
#
# Indexes
#
#
# Table name: messages
#
-# id :integer not null, primary key
-# from_user_id :integer not null
+# id :bigint(8) not null, primary key
+# from_user_id :bigint(8) not null
# title :string not null
# body :text not null
# sent_on :datetime not null
# message_read :boolean default(FALSE), not null
-# to_user_id :integer not null
+# to_user_id :bigint(8) not null
# to_user_visible :boolean default(TRUE), not null
# from_user_visible :boolean default(TRUE), not null
# body_format :enum default("markdown"), not null
#
# Table name: current_nodes
#
-# id :integer not null, primary key
+# id :bigint(8) not null, primary key
# latitude :integer not null
# longitude :integer not null
-# changeset_id :integer not null
+# changeset_id :bigint(8) not null
# visible :boolean not null
# timestamp :datetime not null
-# tile :integer not null
-# version :integer not null
+# tile :bigint(8) not null
+# version :bigint(8) not null
#
# Indexes
#
return Node.from_xml_node(pt, create)
end
raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/node element.")
- rescue LibXML::XML::Error, ArgumentError => ex
- raise OSM::APIBadXMLError.new("node", xml, ex.message)
+ rescue LibXML::XML::Error, ArgumentError => e
+ raise OSM::APIBadXMLError.new("node", xml, e.message)
end
def self.from_xml_node(pt, create = false)
#
# Table name: current_node_tags
#
-# node_id :integer not null, primary key
+# node_id :bigint(8) not null, primary key
# k :string default(""), not null, primary key
# v :string default(""), not null
#
#
# Table name: notes
#
-# id :integer not null, primary key
+# id :bigint(8) not null, primary key
# latitude :integer not null
# longitude :integer not null
-# tile :integer not null
+# tile :bigint(8) not null
# updated_at :datetime not null
# created_at :datetime not null
# status :enum not null
#
# Table name: note_comments
#
-# id :integer not null, primary key
-# note_id :integer not null
+# id :bigint(8) not null, primary key
+# note_id :bigint(8) not null
# visible :boolean not null
# created_at :datetime not null
# author_ip :inet
-# author_id :integer
+# author_id :bigint(8)
# body :text
# event :enum
#
# Indexes
#
-# index_note_comments_on_body (to_tsvector('english'::regconfig, body))
+# index_note_comments_on_body (to_tsvector('english'::regconfig, body)) USING gin
# index_note_comments_on_created_at (created_at)
# note_comments_note_id_idx (note_id)
#
#
# Table name: nodes
#
-# node_id :integer not null, primary key
+# node_id :bigint(8) not null, primary key
# latitude :integer not null
# longitude :integer not null
-# changeset_id :integer not null
+# changeset_id :bigint(8) not null
# visible :boolean not null
# timestamp :datetime not null
-# tile :integer not null
-# version :integer not null, primary key
+# tile :bigint(8) not null
+# version :bigint(8) not null, primary key
# redaction_id :integer
#
# Indexes
#
# Table name: node_tags
#
-# node_id :integer not null, primary key
-# version :integer not null, primary key
+# node_id :bigint(8) not null, primary key
+# version :bigint(8) not null, primary key
# k :string default(""), not null, primary key
# v :string default(""), not null
#
#
# Table name: relations
#
-# relation_id :integer default(0), not null, primary key
-# changeset_id :integer not null
+# relation_id :bigint(8) default(0), not null, primary key
+# changeset_id :bigint(8) not null
# timestamp :datetime not null
-# version :integer not null, primary key
+# version :bigint(8) not null, primary key
# visible :boolean default(TRUE), not null
# redaction_id :integer
#
#
# Table name: relation_members
#
-# relation_id :integer default(0), not null, primary key
+# relation_id :bigint(8) default(0), not null, primary key
# member_type :enum not null
-# member_id :integer not null
+# member_id :bigint(8) not null
# member_role :string not null
-# version :integer default(0), not null, primary key
+# version :bigint(8) default(0), not null, primary key
# sequence_id :integer default(0), not null, primary key
#
# Indexes
#
# Table name: relation_tags
#
-# relation_id :integer default(0), not null, primary key
+# relation_id :bigint(8) default(0), not null, primary key
# k :string default(""), not null, primary key
# v :string default(""), not null
-# version :integer not null, primary key
+# version :bigint(8) not null, primary key
#
# Foreign Keys
#
#
# Table name: ways
#
-# way_id :integer default(0), not null, primary key
-# changeset_id :integer not null
+# way_id :bigint(8) default(0), not null, primary key
+# changeset_id :bigint(8) not null
# timestamp :datetime not null
-# version :integer not null, primary key
+# version :bigint(8) not null, primary key
# visible :boolean default(TRUE), not null
# redaction_id :integer
#
#
# Table name: way_nodes
#
-# way_id :integer not null, primary key
-# node_id :integer not null
-# version :integer not null, primary key
-# sequence_id :integer not null, primary key
+# way_id :bigint(8) not null, primary key
+# node_id :bigint(8) not null
+# version :bigint(8) not null, primary key
+# sequence_id :bigint(8) not null, primary key
#
# Indexes
#
#
# Table name: way_tags
#
-# way_id :integer default(0), not null, primary key
+# way_id :bigint(8) default(0), not null, primary key
# k :string not null, primary key
# v :string not null
-# version :integer not null, primary key
+# version :bigint(8) not null, primary key
#
# Foreign Keys
#
# description :text
# created_at :datetime
# updated_at :datetime
-# user_id :integer not null
+# user_id :bigint(8) not null
# description_format :enum default("markdown"), not null
#
# Foreign Keys
#
# Table name: current_relations
#
-# id :integer not null, primary key
-# changeset_id :integer not null
+# id :bigint(8) not null, primary key
+# changeset_id :bigint(8) not null
# timestamp :datetime not null
# visible :boolean not null
-# version :integer not null
+# version :bigint(8) not null
#
# Indexes
#
return Relation.from_xml_node(pt, create)
end
raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/relation element.")
- rescue LibXML::XML::Error, ArgumentError => ex
- raise OSM::APIBadXMLError.new("relation", xml, ex.message)
+ rescue LibXML::XML::Error, ArgumentError => e
+ raise OSM::APIBadXMLError.new("relation", xml, e.message)
end
def self.from_xml_node(pt, create = false)
#
# Table name: current_relation_members
#
-# relation_id :integer not null, primary key
+# relation_id :bigint(8) not null, primary key
# member_type :enum not null
-# member_id :integer not null
+# member_id :bigint(8) not null
# member_role :string not null
# sequence_id :integer default(0), not null, primary key
#
#
# Table name: current_relation_tags
#
-# relation_id :integer not null, primary key
+# relation_id :bigint(8) not null, primary key
# k :string default(""), not null, primary key
# v :string default(""), not null
#
#
# Table name: gpx_files
#
-# id :integer not null, primary key
-# user_id :integer not null
+# id :bigint(8) not null, primary key
+# user_id :bigint(8) not null
# visible :boolean default(TRUE), not null
# name :string default(""), not null
-# size :integer
+# size :bigint(8)
# latitude :float
# longitude :float
# timestamp :datetime not null
validates :timestamp, :presence => true
validates :visibility, :inclusion => %w[private public trackable identifiable]
- def destroy
- super
- FileUtils.rm_f(trace_name)
- FileUtils.rm_f(icon_picture_name)
- FileUtils.rm_f(large_picture_name)
- end
+ after_destroy :remove_files
def tagstring
tags.collect(&:tag).join(", ")
end
raise OSM::APIBadXMLError.new("trace", xml, "XML doesn't contain an osm/gpx_file element.")
- rescue LibXML::XML::Error, ArgumentError => ex
- raise OSM::APIBadXMLError.new("trace", xml, ex.message)
+ rescue LibXML::XML::Error, ArgumentError => e
+ raise OSM::APIBadXMLError.new("trace", xml, e.message)
end
def update_from_xml_node(pt, create = false)
gpx
end
+
+ private
+
+ def remove_files
+ FileUtils.rm_f(trace_name)
+ FileUtils.rm_f(icon_picture_name)
+ FileUtils.rm_f(large_picture_name)
+ end
end
# trackid :integer not null
# latitude :integer not null
# longitude :integer not null
-# gpx_id :integer not null
+# gpx_id :bigint(8) not null
# timestamp :datetime
-# tile :integer
+# tile :bigint(8)
#
# Indexes
#
#
# Table name: gpx_file_tags
#
-# gpx_id :integer default(0), not null
+# gpx_id :bigint(8) default(0), not null
# tag :string not null
-# id :integer not null, primary key
+# id :bigint(8) not null, primary key
#
# Indexes
#
# Table name: users
#
# email :string not null
-# id :integer not null, primary key
+# id :bigint(8) not null, primary key
# pass_crypt :string not null
# creation_time :datetime not null
# display_name :string default(""), not null
# image_use_gravatar :boolean default(FALSE), not null
# image_content_type :string
# auth_provider :string
-# home_tile :integer
+# home_tile :bigint(8)
+# tou_agreed :datetime
#
# Indexes
#
# Table name: user_blocks
#
# id :integer not null, primary key
-# user_id :integer not null
-# creator_id :integer not null
+# user_id :bigint(8) not null
+# creator_id :bigint(8) not null
# reason :text not null
# ends_at :datetime not null
# needs_view :boolean default(FALSE), not null
-# revoker_id :integer
+# revoker_id :bigint(8)
# created_at :datetime
# updated_at :datetime
# reason_format :enum default("markdown"), not null
#
# Table name: user_preferences
#
-# user_id :integer not null, primary key
+# user_id :bigint(8) not null, primary key
# k :string not null, primary key
# v :string not null
#
# Table name: user_roles
#
# id :integer not null, primary key
-# user_id :integer not null
+# user_id :bigint(8) not null
# role :enum not null
# created_at :datetime
# updated_at :datetime
-# granter_id :integer not null
+# granter_id :bigint(8) not null
#
# Indexes
#
#
# Table name: user_tokens
#
-# id :integer not null, primary key
-# user_id :integer not null
+# id :bigint(8) not null, primary key
+# user_id :bigint(8) not null
# token :string not null
# expiry :datetime not null
# referer :text
#
# Table name: current_ways
#
-# id :integer not null, primary key
-# changeset_id :integer not null
+# id :bigint(8) not null, primary key
+# changeset_id :bigint(8) not null
# timestamp :datetime not null
# visible :boolean not null
-# version :integer not null
+# version :bigint(8) not null
#
# Indexes
#
return Way.from_xml_node(pt, create)
end
raise OSM::APIBadXMLError.new("node", xml, "XML doesn't contain an osm/way element.")
- rescue LibXML::XML::Error, ArgumentError => ex
- raise OSM::APIBadXMLError.new("way", xml, ex.message)
+ rescue LibXML::XML::Error, ArgumentError => e
+ raise OSM::APIBadXMLError.new("way", xml, e.message)
end
def self.from_xml_node(pt, create = false)
#
# Table name: current_way_nodes
#
-# way_id :integer not null, primary key
-# node_id :integer not null
-# sequence_id :integer not null, primary key
+# way_id :bigint(8) not null, primary key
+# node_id :bigint(8) not null
+# sequence_id :bigint(8) not null, primary key
#