-
Notifications
You must be signed in to change notification settings - Fork 15
/
map_display.js.coffee.erb
281 lines (247 loc) · 11 KB
/
map_display.js.coffee.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
require('leaflet-search/dist/leaflet-search.src.js')
require('leaflet-draw')
jQuery ->
class LeafletMap
@OpenCycle: 'https://{s}.tile.cyclestreets.net/opencyclemap/{z}/{x}/{y}@2x.png'
@OSStreet: 'https://{s}.tile.cyclestreets.net/osopendata/{z}/{x}/{y}.png'
@Mapnik: 'https://{s}.tile.cyclestreets.net/mapnik/{z}/{x}/{y}.png'
@CyclestreetsKey: "<%= Geocoder::API_KEY %>"
@CyclestreetsGeoUrl: "<%= Geocoder::GEO_URL %>"
@CyclestreetsCollisionUrl: "<%= Geocoder::COLLISIONS_URL %>"
@CyclestreetsPhotoUrl: "<%= Geocoder::PHOTO_URL %>"
@default_marker_path: "<%= image_path('map-icons/m-misc.png') %>"
@default_marker_anchor: [30 / 2, 42]
constructor: (center, opts) ->
@domId = opts.domid || 'map'
@map = L.map(@domId, maxZoom: 18)
@map.attributionControl.setPrefix('')
@setCenter(center)
@geoInput = $("##{opts.geoinput}_loc_json")
@buildCollistionLayer() if opts.collisions?
@buildPhotoLayer() if opts.photos?
@remoteJSONLayer = {}
@buildRemoteLayer(url, name) for own name, url of opts.remote
@addLayers(opts.hidelayers)
@addSearch() if opts.search?
if opts.draw?
@addDraw(opts.feature)
else if opts.feature?
@addStaticFeature(opts.feature)
@map.removeControl(@map.zoomControl) if opts.hidezoom?
featurePointToLayer: (feature, latlng) =>
return L.marker(latlng).addTo @map unless feature.properties.thumbnail
icon = new L.Icon(iconUrl: feature.properties.thumbnail, iconAnchor: feature.properties.anchor)
L.marker(latlng, {icon: icon}).addTo @map
addStaticFeature: (collection) ->
L.geoJson(collection, {
style: {color: 'black'}, pointToLayer: @featurePointToLayer
}).addTo @map
return
buildRemoteLayer: (url, name) ->
remoteLayer = L.geoJson(null, {
pointToLayer: @featurePointToLayer.bind(@)
fillOpacity: 0.1
fillColor: 'white'
onEachFeature: (feature, layer) ->
img = if feature.properties.image_url
"<img src='#{feature.properties.image_url}' width='37' height='37'>"
else
''
layer.bindPopup( "#{img}
<h3><a href='#{feature.properties.url}'> #{feature.properties.title} </a></h3>
<p>created by <a href='#{feature.properties.created_by_url}'> #{feature.properties.created_by} </p>"
)
}).addTo(@map)
@remoteJSONLayer[name] = new L.LayerJSON({
url: "#{url}?bbox={lon1},{lat1},{lon2},{lat2}"
propertyItems: 'features'
propertyLoc: 'geometry.coordinates'
updateOutBounds: false
hashGenerator: (data) ->
data.id
dataToMarker: remoteLayer.addData.bind(remoteLayer)
}).addTo(@map)
setCenter: (center) ->
@map.fitBounds(center.fitBounds) if center.fitBounds?
@map.setView(center.latLon, center.zoom) if center.latLon
return
addLayers: (hidelayers) ->
openCycle = L.tileLayer(@constructor.OpenCycle, opacity: 0.8)
openCycle.addTo(@map)
baseLayers = {
"OpenCycleMap": openCycle,
"OS StreetView": L.tileLayer(@constructor.OSStreet, opacity: 0.8),
"OpenStreetMap": L.tileLayer(@constructor.Mapnik, opacity: 0.8),
}
additionalLayers = @remoteJSONLayer
additionalLayers['Collisions'] = @collisionLayer if @collisionLayer
additionalLayers['Photos'] = @photoLayer if @photoLayer
L.control.layers(baseLayers, additionalLayers).addTo(@map) unless hidelayers
buildPhotoLayer: =>
params = [
{name: 'key', value: @constructor.CyclestreetsKey},
{name: 'fields', value: 'id,name,hasPhoto,categoryId,categoryPlural,metacategoryName,iconProperties,thumbnailUrl'},
{name: 'thumbnailsize', value: 250},
{name: 'datetime', value: 'friendly'},
]
@photoLayer = new L.LayerJSON({
url: "#{@constructor.CyclestreetsPhotoUrl}?#{$.param(params)}&bbox={lon1},{lat1},{lon2},{lat2}"
propertyItems: 'features'
propertyLoc: 'geometry.coordinates',
locAsGeoJSON: true,
dataToMarker: (feature, latlng) =>
marker = new L.CircleMarker(latlng).addTo @photoLayer
# Declarations
id = feature.properties.id
hasPhoto = feature.properties.hasPhoto
thumbnailUrl = feature.properties.thumbnailUrl
latitude = feature.geometry.coordinates[1]
longitude = feature.geometry.coordinates[0]
peekImgEl = if thumbnailUrl then '<img src="' + thumbnailUrl + '" alt="Image loading …"/>' else ''
# Wrap image in a link
peekImgEl = "<a title=\"Click for a bigger image and copyright details\" href=\"https://www.cyclestreets.net/location/#{id}/\" target=\"_blank\">#{peekImgEl}</a>"
# Get caption
caption = "<p class=\"caption\">#{feature.properties.caption}</p>"
# Headline
headline = '<p></p>'
if feature.properties.hasOwnProperty('categoryPlural') and feature.properties.hasOwnProperty('metacategoryName')
headline += "<p class=\"categorisationnote small\">Categorisation: #{feature.properties.categoryPlural} (#{feature.properties.metacategoryName.toLowerCase()})</p>"
# The main bit of the content
mainContent = if hasPhoto then '<p class="peekimage">' + peekImgEl + '</p>' else '<p class="placeholdernote faded">Placeholder (no photo)</p>' + caption
marker.bindPopup('<div class="' + (if hasPhoto then 'photo' else 'placeholder') + 'bubble' + '">' + headline + mainContent + caption + '</div>')
})
buildCollistionLayer: =>
lookup = {
fatal: { color: '#aa0000', fillColor: '#ff0000', radius: 10 },
serious: { color: '#e44500', fillColor: '#ff8814', radius: 8 },
slight: { color: '#a7932f', fillColor: '#fcff00', radius: 6 }
}
params = [
{name: 'key', value: @constructor.CyclestreetsKey}
{name: 'fields', value: 'id,latitude,longitude,datetime,severity,url'},
{name: 'datetime', value: 'friendly'},
]
@collisionLayer = new L.LayerJSON({
url: "#{@constructor.CyclestreetsCollisionUrl}?#{$.param(params)}&bbox={lon1},{lat1},{lon2},{lat2}"
propertyItems: 'features'
propertyLoc: ['properties.latitude','properties.longitude'],
dataToMarker: (feature, latlng) =>
props = lookup[feature.properties.severity]
marker = new L.CircleMarker(latlng, props).addTo @collisionLayer
marker.bindPopup(
"<h3><a href=\"#{feature.properties.url}\">Collision #{feature.properties.id}</a></h3>
<p>Date and time: #{feature.properties.datetime} </p>
<p>Severity: #{feature.properties.severity} </p>
<p><a href=\"#{feature.properties.url}\">View on CycleStreets</a></p>"
)
})
addSearch: =>
formatJSON = (rawjson) ->
json = {}
featureName = (props) ->
"#{props.name} (#{props.near})"
for feature in rawjson.features
geoJson = L.geoJson(type: "FeatureCollection", features: [feature])
latlng = geoJson.getBounds().getCenter()
latlng.layer = geoJson.getLayers()[0] # add the layer (for getting zoom later)
json[featureName(feature.properties)] = latlng
json
search = (text, callback) =>
bbox = @map.getBounds().toBBoxString()
params = [
{name: 'q', value: text}
{name: 'key', value: @constructor.CyclestreetsKey}
{name: 'bbox', value: bbox},
{name: 'geometries', value: 1}
]
jsonpTransportRequired = ->
navigator.appVersion.indexOf('MSIE') != -1 &&
parseFloat(navigator.appVersion.split('MSIE')[1]) <= 9
$.ajax(
url: @constructor.CyclestreetsGeoUrl
data: params
dataType: 'jsonp' if jsonpTransportRequired()
timeout: 10000
success: callback
)
@map.addControl(
new (L.Control.Search)(
autoCollapse: true
sourceData: search
formatData: formatJSON
moveToLocation: (latlng, _title, map) ->
if latlng.layer.getBounds
zoom = map.getBoundsZoom(latlng.layer.getBounds())
map.setView(latlng, zoom)
autoType: false
minLength: 2)
)
addDraw: (feature) =>
hideNewToolbars = ->
$('.tabs').children('li.area, li.route, li.point').css(opacity: 0.3).prop('disabled', true)
showNewToolbars = ->
$('.tabs').children('li.area, li.route, li.point').css(opacity: 1).prop('disabled', false)
layerCreated = (layer) =>
drawnItems.addLayer layer
@geoInput.val JSON.stringify(layer.toGeoJSON())
hideNewToolbars()
$('.leaflet-draw-edit-edit')[0].click()
$('.icon-save').toggle()
drawnItems = new L.FeatureGroup()
@map.addLayer drawnItems
drawControl = new L.Control.Draw {
position: 'topright'
edit: {
featureGroup: drawnItems
}
draw: {
circle: false
rectangle: false
marker: {
icon: new L.Icon {
iconUrl: @constructor.default_marker_path,
iconAnchor: @constructor.default_marker_anchor
}
}
}
}
@map.addControl drawControl
@map.on 'draw:created', (e) ->
layerCreated(e.layer)
@map.on 'draw:edited draw:editvertex draw:drawvertex draw:editmove', (e) ->
layerCreated(drawnItems.getLayers()[0])
if feature
layerCreated(L.geoJson(feature).getLayers()[0])
else
# enable area / polygon draw as standard
$(".leaflet-draw-draw-polygon")[0].click()
$('.icon-undo').css(opacity: 0.3)
# Bind our icons to the Leaflet draw icons
lDrawMapping = {
area: "draw-polygon"
route: "draw-polyline"
point: "draw-marker"
}
for own localN,lDrawName of lDrawMapping
$("li.#{localN} a").click (evt) ->
target = evt.target
unless $(target).parent().parent().prop('disabled')
$(".leaflet-draw-#{lDrawMapping[target.className]}")[0].click()
# When drawing clear cancels the drawing
# Otherwise clear wipes any shapes on the map
$('.edit-clear').click =>
drawnItems.clearLayers()
$('ul.leaflet-draw-actions a[title^="Cancel"]')[0]?.click()
$('.tabs').children('li.area, li.route, li.point').css(opacity: 1).prop('disabled', false)
@geoInput.val(null)
$('.icon-undo').css(opacity: 0.3)
activeTab = $('.tabs').parent().tabs('option', 'active')
$('.tabs a span')[activeTab].click() # Re-activate drawing the current shape
# When drawing undo deletes the last point
# Otherwise undo edits the layer
@map.on 'draw:drawstart', (e) ->
$('.icon-undo').css(opacity: 1)
$('.edit-undo').click ->
$('ul.leaflet-draw-actions a[title^="Delete"]')[0].click()
for domMap in $('.map-data')
new LeafletMap($(domMap).data('center'), $(domMap).data('opts'))