forked from codeforamerica/citygram
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathscripts.js
373 lines (305 loc) · 11.2 KB
/
scripts.js
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
$(document).ready(function() {
app.hookupMap();
app.hookupSteps();
app.hideSteps();
});
var app = app || {};
app.state = {
channel: 'sms',
geom: undefined,
publisher_id: undefined,
};
app.eventMarkers = new L.FeatureGroup();
app.hookupMap = function() {
document.getElementById('locatormap').innerHTML = "<div id='map'><div class='map-key-panel js-dot-legend'><span class='map-event-dot'></span>Click to see notification</div></div>";
var center = JSON.parse($('meta[name=mapCenter]').attr('content'));
var options = {
zoom: 13,
center: center,
tileLayer: { detectRetina: true },
scrollWheelZoom: false,
};
var mapId = $('meta[name=mapId]').attr('content');
var map = app.map = L.mapbox.map('map', mapId, options);
var locality = document.getElementById('user-selected-locality');
if ( locality != null ) {
locality.onclick = function(e) {
e.preventDefault();
$('.menu-ui a.selected').removeClass('selected');
$(e.target).addClass('selected');
var address = $('#geolocate').val();
if (! address) { //if address is not avail, center map on region when clicked.
var pos = e.target.getAttribute('data-position');
if (pos) {
var loc = pos.split(',');
app.map.setView(loc, 13);
};
} else {
app.geolocate(e);
}
}
}
};
app.hideSteps = function(){
app.hideStep2();
app.hideStep3();
}
app.showStep2 = function(){
$('#step2').removeClass('hide');
}
app.showStep3 = function(){
$('#step3').removeClass('hide');
}
app.hideStep2 = function(){
$('#step2').addClass('hide');
}
app.hideStep3 = function(){
$('#step3').addClass('hide');
}
app.hookupSteps = function() {
$('.startButton').on('click', function() {
app.scrollToElement($('#step1'));
});
$('.publisher:not(.soon)').on('mouseover', function(event) {
$('.publisher').removeClass('is-active');
var $publisher = $(event.currentTarget);
$publisher.addClass('is-active');
});
$('.publisher:not(.soon)').on('mouseout', function(event) {
$('.publisher').removeClass('is-active');
});
$('.publisher:not(.soon)').on('click', function(event) {
$('.publisher').removeClass('selected');
var $publisher = $(this);
$publisher.addClass('selected');
app.setPublisher($publisher);
// Remove disabled state styling from subscribe buttons
$('.smsButton, .emailButton').removeClass('disabledButton');
// Hide disabled subscribe message
$('.disabledInfo').hide();
// update events for the new publisher
app.updateEvents(app.map.getBounds());
app.scrollToElement($('#step2'));
});
app.handleChannelClick = function(channel, channelBtn) {
if (channelBtn.hasClass('disabledButton')) {
$('.disabledInfo').slideDown();
} else {
app.setChannel(channel, channelBtn);
};
}
app.setChannel = function(channel, channelBtn) {
$('.channelButtons .selected').removeClass('selected');
channelBtn.addClass('selected');
$('.channel-inputs :visible').hide();
$('.channel-inputs .js-channel-' + channel).show();
app.state.channel = channel;
$('.extraInfo').slideDown();
$('.js-confirm-channel').hide();
$('.js-confirm-' + channel).show();
}
$('.smsButton').on('click', function(event) {
app.handleChannelClick('sms', $(event.target));
});
$('.emailButton').on('click', function(event) {
app.handleChannelClick('email', $(event.target));
});
var finishSubscribe = function(e) {
// TODO: animate the done checkmark at the same time
e.preventDefault();
// TODO: handle email and webhooks also
app.state.phone_number = $('.phoneNumber').val();
app.state.email_address = $('.emailAddress').val();
app.submitSubscription(function(subscription) {
$('#confirmation').slideDown();
app.scrollToElement($('#confirmation'));
$('#view-subscription').attr('href', '/digests/'+subscription.id+'/events')
});
};
$('.subscribeButton').on('click', finishSubscribe);
$('#subscribeForm').on('submit', finishSubscribe);
$('.resetButton').on('click', function(event) {
app.resetState();
app.scrollToElement($('#step1'));
// Hide after we've scrolled up.
setTimeout(function() {
$('#confirmation').hide();
}, 800);
});
var prevMarker, prevCircle;
app.geolocate = function(e) {
e && e.preventDefault();
var address = $('#geolocate').val();
if (! address) { return }
var city = undefined;
var state = undefined;
// if within a geography that has localities, e.g. Triangle
// that consideration is primary.
var usesLocality = $("#user-selected-locality");
if (usesLocality && usesLocality.length == 0){
var publisherSelection = $('.publisher.selected');
city = publisherSelection.data('publisher-city');
state = publisherSelection.data('publisher-state');
} else {
// locality cannot activate without selection
var localitySelection = $("#user-selected-locality a.selected");
if (! localitySelection) { return }
city = localitySelection.data('city');
state = localitySelection.data('state');
}
var radiusMiles = parseFloat($('#user-selected-radius').val());
var radiusKm =radiusMiles * 1.60934
var radiusMeters = radiusKm * 1000;
var oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
app.geocode(address, city, state, function(latlng) {
// Set the new app state
var center = new LatLon(latlng[0], latlng[1]);
var bboxDistance = radiusKm;
var bbox = center.boundingBox(bboxDistance);
app.state.geom = JSON.stringify({
type: 'Polygon',
coordinates: [bbox],
});
// Remove old layers
if (prevMarker) app.map.removeLayer(prevMarker);
if (prevCircle) app.map.removeLayer(prevCircle);
// Preserve references to new layers
prevMarker = L.marker(latlng).addTo(app.map);
prevCircle = L.circle(latlng, radiusMeters, { color:'#0B377F' }).addTo(app.map);
if (app.eventsArePolygons) {
app.updateEventsForGeometry(app.state.geom, function(events) {
app.copyEventTitleToMarker(events, prevMarker);
});
}
// fit bounds
app.map.fitBounds(prevCircle.getBounds());
// Frequency estimate
app.getEventsCount(app.state.publisher_id, app.state.geom, oneWeekAgo, function(response) {
$('#freqRadius').html(radiusMiles + ' mi');
$('#freqAddress').html(address + ' ' + city + ', ' + state);
$('#freqNum').html(response.events_count + ' citygrams');
});
app.showStep3();
});
};
app.map.on('zoomend', function() {
app.updateEvents(app.map.getBounds());
});
$('.publisher:not(.soon)').on('click', function(e) {
if ($('#geolocate').val().trim() !== '') app.geolocate();
});
$('#user-selected-radius').on('change', app.geolocate);
$('#geolocate').on('change', app.geolocate);
$('#geolocateForm').on('submit', function(){ return false });
};
app.copyEventTitleToMarker = function(events, marker) {
var surroundingEvent;
var markerGeoJSON = marker.toGeoJSON();
events.forEach(function(event) {
var polygon = {"type": "Feature", geometry: JSON.parse(event.geom)};
if (turf.inside(markerGeoJSON, polygon)) {
surroundingEvent = event;
}
});
if (surroundingEvent) {
marker.bindPopup("<p>"+app.hyperlink(surroundingEvent.title)+"</p>").openPopup();
}
}
app.setPublisher = function($publisher) {
app.state.publisher_id = $publisher.data('publisher-id');
app.eventsArePolygons = $publisher.data('publisher-events-are-polygons');
if ($publisher.data('publisher-event-display-endpoint')) {
app.eventDisplayEndpoint = $publisher.data('publisher-event-display-endpoint');
} else {
app.eventDisplayEndpoint = '/publishers/'+app.state.publisher_id+'/events';
}
$('.js-dot-legend').css('visibility', app.eventsArePolygons ? 'hidden' : 'visible');
$('.confirmationType').html($publisher.data('publisher-title'));
app.showStep2();
}
app.hyperlink = Autolinker.link;
// Populate events
app.updateEvents = function(bounds) {
var mapGeometry = {
type: 'Polygon',
coordinates: [[
[bounds._southWest.lng, bounds._northEast.lat],
[bounds._northEast.lng, bounds._northEast.lat],
[bounds._northEast.lng, bounds._southWest.lat],
[bounds._southWest.lng, bounds._southWest.lat],
[bounds._southWest.lng, bounds._northEast.lat]
]]
}
app.updateEventsForGeometry(JSON.stringify(mapGeometry), function(events) {
app.eventMarkers.eachLayer(function(layer) {
app.map.removeLayer(layer);
});
// tiny radius mimics an address point inside event polygon
if (app.eventsArePolygons) { app.selectTinyRadius(); }
events.forEach(function(event, index) {
var marker = app.displayEventMarker(event);
if (index == 0 && ! app.eventsArePolygons) {
marker.openPopup();
}
});
});
};
app.selectTinyRadius = function() {
var tinyRadius = '.001'
var $select = $('#user-selected-radius');
if ($select.find('option[value="' + tinyRadius + '"]').length === 0) {
$select.prepend('<option value="' + tinyRadius + '">Within 1/100 mile (only the address)</option>');
}
$select.val(tinyRadius);
app.geolocate();
}
app.displayEventMarker = function(event) {
var geometry = JSON.parse(event.geom);
var marker;
var html = "<p>"+app.hyperlink(event.title)+"</p>"
if (app.eventsArePolygons) {
marker = L.geoJson({"type": "Feature", "geometry": geometry});
} else {
marker = L.circleMarker([geometry.coordinates[1], geometry.coordinates[0]], { radius: 6, color: '#FC442A' })
}
marker.addTo(app.map).bindPopup(html);
app.eventMarkers.addLayer(marker);
return marker;
}
app.updateEventsForGeometry = function(geometry, callback){
if (!app.state.publisher_id) return;
$.getJSON(app.eventDisplayEndpoint, { geometry: geometry }, callback);
};
app.getEventsCount = function(publisherId, geometry, since, callback){
if (!publisherId) return;
$.getJSON('/publishers/'+publisherId+'/events_count', { geometry: geometry, since: since }, callback);
};
app.scrollToElement = function(el) {
$('html,body').animate({
scrollTop: el.offset().top
}, 800);
};
app.geocode = function(address, city, state, callback, context) {
var url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address);
url += '&components=locality:' + encodeURIComponent(city);
url += '|administrative_area:' + encodeURIComponent(state);
$.getJSON(url, function(response) {
if (response.error || response.results.length === 0) {
console.log('Unable to geocode city. Womp Womp.', response.error);
}
// Get the coordinates for the center of the city
var location = response.results[0].geometry.location;
var latlng = [location.lat, location.lng];
callback.call(context || this, latlng);
});
};
app.resetState = function() {
app.state.publisher_id = undefined;
app.eventDisplayEndpoint = undefined;
$('.publisher').removeClass('selected');
// Let's leave the location and phone number in place, for easy re-subscribe
};
app.submitSubscription = function(callback) {
$.post('/subscriptions', { subscription: app.state }, callback);
};