From 7a9fed71ab77a503cdd4a9d050483adc2d0f6591 Mon Sep 17 00:00:00 2001 From: Atalya Alon Date: Sun, 30 Sep 2018 01:51:19 +0300 Subject: [PATCH] cbs - modify tables and add dictionary tables --- ..._cbs_modify_tables_and_add_dictionaries.py | 540 +++++++++++++++ anyway/accidents_around_schools.py | 2 +- anyway/field_names.py | 4 +- anyway/localization.py | 11 +- anyway/models.py | 354 ++++++++-- anyway/parsers/cbs.py | 244 ++++++- anyway/parsers/rsa.py | 4 +- anyway/parsers/united.py | 6 +- anyway/scripts/accidents_around_location.py | 4 +- anyway/simple_import.py | 2 +- .../view_lamas_markers_by_city_and_date.sql | 8 +- main.py | 11 +- static/js/app.js | 620 ++++++++++-------- static/js/constants.js | 10 +- static/js/marker.js | 18 +- static/js/sidebar.js | 22 +- static/js/statPanel.js | 91 ++- templates/index.html | 18 +- 18 files changed, 1551 insertions(+), 418 deletions(-) create mode 100644 alembic/versions/1c7c31b1c31d_cbs_modify_tables_and_add_dictionaries.py diff --git a/alembic/versions/1c7c31b1c31d_cbs_modify_tables_and_add_dictionaries.py b/alembic/versions/1c7c31b1c31d_cbs_modify_tables_and_add_dictionaries.py new file mode 100644 index 000000000..dfe009729 --- /dev/null +++ b/alembic/versions/1c7c31b1c31d_cbs_modify_tables_and_add_dictionaries.py @@ -0,0 +1,540 @@ +"""cbs_modify_tables_and_add_dictionaries + +Revision ID: 1c7c31b1c31d +Revises: 56b95d5826c +Create Date: 2018-09-30 01:10:18.193297 + +""" + +# revision identifiers, used by Alembic. +revision = '1c7c31b1c31d' +down_revision = '56b95d5826c' +branch_labels = None +depends_on = None + +from alembic import op +import sqlalchemy as sa + + +def upgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_table('accident_hour_raw', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('accident_hour_raw_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_accident_hour_raw_id'), 'accident_hour_raw', ['id'], unique=False) + op.create_table('accident_month', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('accident_month_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_accident_month_id'), 'accident_month', ['id'], unique=False) + op.create_table('accident_severity', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('accident_severity_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_accident_severity_id'), 'accident_severity', ['id'], unique=False) + op.create_table('accident_type', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('accident_type_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_accident_type_id'), 'accident_type', ['id'], unique=False) + op.create_table('age_group', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('age_group_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_age_group_id'), 'age_group', ['id'], unique=False) + op.create_table('columns_description', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('column_description', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_columns_description_id'), 'columns_description', ['id'], unique=False) + op.create_table('cross_direction', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('cross_direction_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_cross_direction_id'), 'cross_direction', ['id'], unique=False) + op.create_table('cross_location', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('cross_location_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_cross_location_id'), 'cross_location', ['id'], unique=False) + op.create_table('cross_mode', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('cross_mode_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_cross_mode_id'), 'cross_mode', ['id'], unique=False) + op.create_table('day_in_week', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('day_in_week_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_day_in_week_id'), 'day_in_week', ['id'], unique=False) + op.create_table('day_night', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('day_night_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_day_night_id'), 'day_night', ['id'], unique=False) + op.create_table('day_type', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('day_type_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_day_type_id'), 'day_type', ['id'], unique=False) + op.create_table('didnt_cross', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('didnt_cross_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_didnt_cross_id'), 'didnt_cross', ['id'], unique=False) + op.create_table('district', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('district_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_district_id'), 'district', ['id'], unique=False) + op.create_table('driving_directions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('driving_directions_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_driving_directions_id'), 'driving_directions', ['id'], unique=False) + op.create_table('engine_volume', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('engine_volume_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_engine_volume_id'), 'engine_volume', ['id'], unique=False) + op.create_table('geo_area', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('geo_area_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_geo_area_id'), 'geo_area', ['id'], unique=False) + op.create_table('hospital_time', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('hospital_time_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_hospital_time_id'), 'hospital_time', ['id'], unique=False) + op.create_table('injured_position', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('injured_position_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_injured_position_id'), 'injured_position', ['id'], unique=False) + op.create_table('injured_type', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('injured_type_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_injured_type_id'), 'injured_type', ['id'], unique=False) + op.create_table('injury_severity', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('injury_severity_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_injury_severity_id'), 'injury_severity', ['id'], unique=False) + op.create_table('involved_type', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('involved_type_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_involved_type_id'), 'involved_type', ['id'], unique=False) + op.create_table('late_deceased', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('late_deceased_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_late_deceased_id'), 'late_deceased', ['id'], unique=False) + op.create_table('location_accuracy', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('location_accuracy_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_location_accuracy_id'), 'location_accuracy', ['id'], unique=False) + op.create_table('medical_type', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('medical_type_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_medical_type_id'), 'medical_type', ['id'], unique=False) + op.create_table('minizipali_status', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('minizipali_status_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_minizipali_status_id'), 'minizipali_status', ['id'], unique=False) + op.create_table('multi_lane', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('multi_lane_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_multi_lane_id'), 'multi_lane', ['id'], unique=False) + op.create_table('natural_area', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('natural_area_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_natural_area_id'), 'natural_area', ['id'], unique=False) + op.create_table('object_distance', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('object_distance_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_object_distance_id'), 'object_distance', ['id'], unique=False) + op.create_table('one_lane', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('one_lane_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_one_lane_id'), 'one_lane', ['id'], unique=False) + op.create_table('police_unit', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('police_unit_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_police_unit_id'), 'police_unit', ['id'], unique=False) + op.create_table('population_type', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('population_type_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_population_type_id'), 'population_type', ['id'], unique=False) + op.create_table('provider_code', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('provider_code_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_provider_code_id'), 'provider_code', ['id'], unique=False) + op.create_table('region', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('region_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_region_id'), 'region', ['id'], unique=False) + op.create_table('release_dest', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('release_dest_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_release_dest_id'), 'release_dest', ['id'], unique=False) + op.create_table('road_control', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('road_control_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_road_control_id'), 'road_control', ['id'], unique=False) + op.create_table('road_intactness', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('road_intactness_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_road_intactness_id'), 'road_intactness', ['id'], unique=False) + op.create_table('road_light', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('road_light_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_road_light_id'), 'road_light', ['id'], unique=False) + op.create_table('road_object', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('road_object_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_road_object_id'), 'road_object', ['id'], unique=False) + op.create_table('road_shape', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('road_shape_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_road_shape_id'), 'road_shape', ['id'], unique=False) + op.create_table('road_sign', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('road_sign_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_road_sign_id'), 'road_sign', ['id'], unique=False) + op.create_table('road_surface', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('road_surface_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_road_surface_id'), 'road_surface', ['id'], unique=False) + op.create_table('road_type', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('road_type_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_road_type_id'), 'road_type', ['id'], unique=False) + op.create_table('road_width', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('road_width_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_road_width_id'), 'road_width', ['id'], unique=False) + op.create_table('safety_measures', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('safety_measures_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_safety_measures_id'), 'safety_measures', ['id'], unique=False) + op.create_table('safety_measures_use', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('safety_measures_use_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_safety_measures_use_id'), 'safety_measures_use', ['id'], unique=False) + op.create_table('sex', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('sex_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_sex_id'), 'sex', ['id'], unique=False) + op.create_table('speed_limit', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('speed_limit_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_speed_limit_id'), 'speed_limit', ['id'], unique=False) + op.create_table('total_weight', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('total_weight_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_total_weight_id'), 'total_weight', ['id'], unique=False) + op.create_table('traffic_light', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('traffic_light_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_traffic_light_id'), 'traffic_light', ['id'], unique=False) + op.create_table('vehicle_attribution', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('vehicle_attribution_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_vehicle_attribution_id'), 'vehicle_attribution', ['id'], unique=False) + op.create_table('vehicle_status', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('vehicle_status_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_vehicle_status_id'), 'vehicle_status', ['id'], unique=False) + op.create_table('vehicle_type', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('vehicle_type_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_vehicle_type_id'), 'vehicle_type', ['id'], unique=False) + op.create_table('weather', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('weather_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_weather_id'), 'weather', ['id'], unique=False) + op.create_table('yishuv_shape', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('yishuv_shape_hebrew', sa.Text(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_yishuv_shape_id'), 'yishuv_shape', ['id'], unique=False) + op.add_column(u'markers', sa.Column('accident_severity', sa.Integer(), nullable=True)) + op.add_column(u'markers', sa.Column('accident_type', sa.Integer(), nullable=True)) + op.add_column(u'markers', sa.Column('day_type', sa.Integer(), nullable=True)) + op.add_column(u'markers', sa.Column('location_accuracy', sa.Integer(), nullable=True)) + op.add_column(u'markers', sa.Column('non_urban_intersection_hebrew', sa.Text(), nullable=True)) + op.add_column(u'markers', sa.Column('police_unit', sa.Integer(), nullable=True)) + op.add_column(u'markers', sa.Column('road_intactness', sa.Integer(), nullable=True)) + op.add_column(u'markers', sa.Column('road_shape', sa.Integer(), nullable=True)) + op.add_column(u'markers', sa.Column('road_type', sa.Integer(), nullable=True)) + op.add_column(u'markers', sa.Column('street1_hebrew', sa.Text(), nullable=True)) + op.add_column(u'markers', sa.Column('street2_hebrew', sa.Text(), nullable=True)) + op.add_column(u'markers', sa.Column('yishuv_name', sa.Text(), nullable=True)) + op.drop_column(u'markers', 'roadShape') + op.drop_column(u'markers', 'severity') + op.drop_column(u'markers', 'intactness') + op.drop_column(u'markers', 'subtype') + op.drop_column(u'markers', 'roadType') + op.drop_column(u'markers', 'dayType') + op.drop_column(u'markers', 'locationAccuracy') + op.drop_column(u'markers', 'unit') + op.add_column(u'markers_no_location', sa.Column('accident_severity', sa.Integer(), nullable=True)) + op.add_column(u'markers_no_location', sa.Column('accident_type', sa.Integer(), nullable=True)) + op.add_column(u'markers_no_location', sa.Column('day_type', sa.Integer(), nullable=True)) + op.add_column(u'markers_no_location', sa.Column('location_accuracy', sa.Integer(), nullable=True)) + op.add_column(u'markers_no_location', sa.Column('police_unit', sa.Integer(), nullable=True)) + op.add_column(u'markers_no_location', sa.Column('road_intactness', sa.Integer(), nullable=True)) + op.add_column(u'markers_no_location', sa.Column('road_shape', sa.Integer(), nullable=True)) + op.add_column(u'markers_no_location', sa.Column('road_type', sa.Integer(), nullable=True)) + op.drop_column(u'markers_no_location', 'roadShape') + op.drop_column(u'markers_no_location', 'severity') + op.drop_column(u'markers_no_location', 'intactness') + op.drop_column(u'markers_no_location', 'subtype') + op.drop_column(u'markers_no_location', 'roadType') + op.drop_column(u'markers_no_location', 'dayType') + op.drop_column(u'markers_no_location', 'locationAccuracy') + op.drop_column(u'markers_no_location', 'unit') + op.drop_index('idx_schools_geom', table_name='schools') + ### end Alembic commands ### + + +def downgrade(): + ### commands auto generated by Alembic - please adjust! ### + op.create_index('idx_schools_geom', 'schools', ['geom'], unique=False) + op.add_column(u'markers_no_location', sa.Column('unit', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers_no_location', sa.Column('locationAccuracy', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers_no_location', sa.Column('dayType', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers_no_location', sa.Column('roadType', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers_no_location', sa.Column('subtype', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers_no_location', sa.Column('intactness', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers_no_location', sa.Column('severity', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers_no_location', sa.Column('roadShape', sa.INTEGER(), autoincrement=False, nullable=True)) + op.drop_column(u'markers_no_location', 'road_type') + op.drop_column(u'markers_no_location', 'road_shape') + op.drop_column(u'markers_no_location', 'road_intactness') + op.drop_column(u'markers_no_location', 'police_unit') + op.drop_column(u'markers_no_location', 'location_accuracy') + op.drop_column(u'markers_no_location', 'day_type') + op.drop_column(u'markers_no_location', 'accident_type') + op.drop_column(u'markers_no_location', 'accident_severity') + op.add_column(u'markers', sa.Column('unit', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers', sa.Column('locationAccuracy', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers', sa.Column('dayType', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers', sa.Column('roadType', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers', sa.Column('subtype', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers', sa.Column('intactness', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers', sa.Column('severity', sa.INTEGER(), autoincrement=False, nullable=True)) + op.add_column(u'markers', sa.Column('roadShape', sa.INTEGER(), autoincrement=False, nullable=True)) + op.drop_column(u'markers', 'yishuv_name') + op.drop_column(u'markers', 'street2_hebrew') + op.drop_column(u'markers', 'street1_hebrew') + op.drop_column(u'markers', 'road_type') + op.drop_column(u'markers', 'road_shape') + op.drop_column(u'markers', 'road_intactness') + op.drop_column(u'markers', 'police_unit') + op.drop_column(u'markers', 'non_urban_intersection_hebrew') + op.drop_column(u'markers', 'location_accuracy') + op.drop_column(u'markers', 'day_type') + op.drop_column(u'markers', 'accident_type') + op.drop_column(u'markers', 'accident_severity') + op.drop_index(op.f('ix_yishuv_shape_id'), table_name='yishuv_shape') + op.drop_table('yishuv_shape') + op.drop_index(op.f('ix_weather_id'), table_name='weather') + op.drop_table('weather') + op.drop_index(op.f('ix_vehicle_type_id'), table_name='vehicle_type') + op.drop_table('vehicle_type') + op.drop_index(op.f('ix_vehicle_status_id'), table_name='vehicle_status') + op.drop_table('vehicle_status') + op.drop_index(op.f('ix_vehicle_attribution_id'), table_name='vehicle_attribution') + op.drop_table('vehicle_attribution') + op.drop_index(op.f('ix_traffic_light_id'), table_name='traffic_light') + op.drop_table('traffic_light') + op.drop_index(op.f('ix_total_weight_id'), table_name='total_weight') + op.drop_table('total_weight') + op.drop_index(op.f('ix_speed_limit_id'), table_name='speed_limit') + op.drop_table('speed_limit') + op.drop_index(op.f('ix_sex_id'), table_name='sex') + op.drop_table('sex') + op.drop_index(op.f('ix_safety_measures_use_id'), table_name='safety_measures_use') + op.drop_table('safety_measures_use') + op.drop_index(op.f('ix_safety_measures_id'), table_name='safety_measures') + op.drop_table('safety_measures') + op.drop_index(op.f('ix_road_width_id'), table_name='road_width') + op.drop_table('road_width') + op.drop_index(op.f('ix_road_type_id'), table_name='road_type') + op.drop_table('road_type') + op.drop_index(op.f('ix_road_surface_id'), table_name='road_surface') + op.drop_table('road_surface') + op.drop_index(op.f('ix_road_sign_id'), table_name='road_sign') + op.drop_table('road_sign') + op.drop_index(op.f('ix_road_shape_id'), table_name='road_shape') + op.drop_table('road_shape') + op.drop_index(op.f('ix_road_object_id'), table_name='road_object') + op.drop_table('road_object') + op.drop_index(op.f('ix_road_light_id'), table_name='road_light') + op.drop_table('road_light') + op.drop_index(op.f('ix_road_intactness_id'), table_name='road_intactness') + op.drop_table('road_intactness') + op.drop_index(op.f('ix_road_control_id'), table_name='road_control') + op.drop_table('road_control') + op.drop_index(op.f('ix_release_dest_id'), table_name='release_dest') + op.drop_table('release_dest') + op.drop_index(op.f('ix_region_id'), table_name='region') + op.drop_table('region') + op.drop_index(op.f('ix_provider_code_id'), table_name='provider_code') + op.drop_table('provider_code') + op.drop_index(op.f('ix_population_type_id'), table_name='population_type') + op.drop_table('population_type') + op.drop_index(op.f('ix_police_unit_id'), table_name='police_unit') + op.drop_table('police_unit') + op.drop_index(op.f('ix_one_lane_id'), table_name='one_lane') + op.drop_table('one_lane') + op.drop_index(op.f('ix_object_distance_id'), table_name='object_distance') + op.drop_table('object_distance') + op.drop_index(op.f('ix_natural_area_id'), table_name='natural_area') + op.drop_table('natural_area') + op.drop_index(op.f('ix_multi_lane_id'), table_name='multi_lane') + op.drop_table('multi_lane') + op.drop_index(op.f('ix_minizipali_status_id'), table_name='minizipali_status') + op.drop_table('minizipali_status') + op.drop_index(op.f('ix_medical_type_id'), table_name='medical_type') + op.drop_table('medical_type') + op.drop_index(op.f('ix_location_accuracy_id'), table_name='location_accuracy') + op.drop_table('location_accuracy') + op.drop_index(op.f('ix_late_deceased_id'), table_name='late_deceased') + op.drop_table('late_deceased') + op.drop_index(op.f('ix_involved_type_id'), table_name='involved_type') + op.drop_table('involved_type') + op.drop_index(op.f('ix_injury_severity_id'), table_name='injury_severity') + op.drop_table('injury_severity') + op.drop_index(op.f('ix_injured_type_id'), table_name='injured_type') + op.drop_table('injured_type') + op.drop_index(op.f('ix_injured_position_id'), table_name='injured_position') + op.drop_table('injured_position') + op.drop_index(op.f('ix_hospital_time_id'), table_name='hospital_time') + op.drop_table('hospital_time') + op.drop_index(op.f('ix_geo_area_id'), table_name='geo_area') + op.drop_table('geo_area') + op.drop_index(op.f('ix_engine_volume_id'), table_name='engine_volume') + op.drop_table('engine_volume') + op.drop_index(op.f('ix_driving_directions_id'), table_name='driving_directions') + op.drop_table('driving_directions') + op.drop_index(op.f('ix_district_id'), table_name='district') + op.drop_table('district') + op.drop_index(op.f('ix_didnt_cross_id'), table_name='didnt_cross') + op.drop_table('didnt_cross') + op.drop_index(op.f('ix_day_type_id'), table_name='day_type') + op.drop_table('day_type') + op.drop_index(op.f('ix_day_night_id'), table_name='day_night') + op.drop_table('day_night') + op.drop_index(op.f('ix_day_in_week_id'), table_name='day_in_week') + op.drop_table('day_in_week') + op.drop_index(op.f('ix_cross_mode_id'), table_name='cross_mode') + op.drop_table('cross_mode') + op.drop_index(op.f('ix_cross_location_id'), table_name='cross_location') + op.drop_table('cross_location') + op.drop_index(op.f('ix_cross_direction_id'), table_name='cross_direction') + op.drop_table('cross_direction') + op.drop_index(op.f('ix_columns_description_id'), table_name='columns_description') + op.drop_table('columns_description') + op.drop_index(op.f('ix_age_group_id'), table_name='age_group') + op.drop_table('age_group') + op.drop_index(op.f('ix_accident_type_id'), table_name='accident_type') + op.drop_table('accident_type') + op.drop_index(op.f('ix_accident_severity_id'), table_name='accident_severity') + op.drop_table('accident_severity') + op.drop_index(op.f('ix_accident_month_id'), table_name='accident_month') + op.drop_table('accident_month') + op.drop_index(op.f('ix_accident_hour_raw_id'), table_name='accident_hour_raw') + op.drop_table('accident_hour_raw') + ### end Alembic commands ### diff --git a/anyway/accidents_around_schools.py b/anyway/accidents_around_schools.py index 93c5de3e8..f8d7fb9e6 100644 --- a/anyway/accidents_around_schools.py +++ b/anyway/accidents_around_schools.py @@ -72,7 +72,7 @@ def acc_inv_query(longitude, latitude, distance, start_date, end_date, school): .filter(or_((AccidentMarker.provider_code == CONST.CBS_ACCIDENT_TYPE_1_CODE), (AccidentMarker.provider_code == CONST.CBS_ACCIDENT_TYPE_3_CODE))) \ .filter(AccidentMarker.created >= start_date) \ .filter(AccidentMarker.created < end_date) \ - .filter(AccidentMarker.locationAccuracy == LOCATION_ACCURACY_PRECISE_INT) \ + .filter(AccidentMarker.location_accuracy == LOCATION_ACCURACY_PRECISE_INT) \ .filter(AccidentMarker.yishuv_symbol != YISHUV_SYMBOL_NOT_EXIST) \ .filter(Involved.age_group.in_([1,2,3,4])) #ages 0-19 diff --git a/anyway/field_names.py b/anyway/field_names.py index f9ab380e1..ce539ccfc 100644 --- a/anyway/field_names.py +++ b/anyway/field_names.py @@ -27,11 +27,11 @@ road_type="SUG_DEREH" # part of the desciption day_type="SUG_YOM" # part of the desciption road_shape="ZURAT_DEREH" # part of the desciption -unit="YEHIDA" # part of the desciption +police_unit="YEHIDA" # part of the desciption one_lane = "HAD_MASLUL" multi_lane = "RAV_MASLUL" speed_limit = "MEHIRUT_MUTERET" -intactness = "TKINUT" +road_intactness = "TKINUT" road_width = "ROHAV" road_sign = "SIMUN_TIMRUR" road_light = "TEURA" diff --git a/anyway/localization.py b/anyway/localization.py index 5d92daa79..061df1f20 100644 --- a/anyway/localization.py +++ b/anyway/localization.py @@ -1,6 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- import csv +import pandas as pd import os from . import field_names from .utilities import decode_hebrew @@ -248,9 +249,7 @@ with _open_hebrew_textfile(os.path.join("static/data/cities.csv"), "r") as f: - _cities = list(csv.DictReader(f)) - -_cities_names = {int(x[field_names.sign]): decode_hebrew(x[field_names.name]) for x in _cities} + _cities = pd.read_csv(f, index_col=field_names.sign) def get_field(field, value=None): @@ -266,4 +265,8 @@ def get_supported_tables(): def get_city_name(symbol_id): - return _cities_names.get(symbol_id, None) + try: + city = _cities_names.loc[symbol_id,field_names.name] + return city + except: + return None diff --git a/anyway/models.py b/anyway/models.py index 3c5f3369e..ee7664044 100755 --- a/anyway/models.py +++ b/anyway/models.py @@ -198,21 +198,21 @@ class AccidentMarker(MarkerMixin, Base): provider_and_id = Column(BigInteger()) provider_code = Column(Integer(), primary_key=True) description = Column(Text()) - subtype = Column(Integer()) - severity = Column(Integer()) + accident_type = Column(Integer()) + accident_severity = Column(Integer()) address = Column(Text()) - locationAccuracy = Column(Integer()) - roadType = Column(Integer()) - roadShape = Column(Integer()) - dayType = Column(Integer()) - unit = Column(Integer()) + location_accuracy = Column(Integer()) + road_type = Column(Integer()) + road_shape = Column(Integer()) + day_type = Column(Integer()) + police_unit = Column(Integer()) mainStreet = Column(Text()) secondaryStreet = Column(Text()) junction = Column(Text()) one_lane = Column(Integer()) multi_lane = Column(Integer()) speed_limit = Column(Integer()) - intactness = Column(Integer()) + road_intactness = Column(Integer()) road_width = Column(Integer()) road_sign = Column(Integer()) road_light = Column(Integer()) @@ -232,6 +232,7 @@ class AccidentMarker(MarkerMixin, Base): road2 = Column(Integer()) km = Column(Float) yishuv_symbol = Column(Integer()) + yishuv_name = Column(Text()) geo_area = Column(Integer()) day_night = Column(Integer()) day_in_week = Column(Integer()) @@ -242,10 +243,13 @@ class AccidentMarker(MarkerMixin, Base): minizipali_status = Column(Integer()) yishuv_shape = Column(Integer()) street1 = Column(Integer()) + street1_hebrew = Column(Text()) street2 = Column(Integer()) + street2_hebrew = Column(Text()) home = Column(Integer()) urban_intersection = Column(Integer()) non_urban_intersection = Column(Integer()) + non_urban_intersection_hebrew = Column(Text()) accident_year = Column(Integer()) accident_month = Column(Integer()) accident_day = Column(Integer()) @@ -265,8 +269,8 @@ def serialize(self, is_thin=False): "provider_code": self.provider_code, "latitude": self.latitude, "longitude": self.longitude, - "severity": self.severity, - "locationAccuracy": self.locationAccuracy, + "accident_severity": self.accident_severity, + "location_accuracy": self.location_accuracy, "created": self.created.isoformat(), } if not is_thin: @@ -274,11 +278,11 @@ def serialize(self, is_thin=False): "title": self.title, "address": self.address, "type": self.type, - "subtype": self.subtype, - "roadType": self.roadType, - "roadShape": self.roadShape, - "dayType": self.dayType, - "unit": self.unit, + "accident_type": self.accident_type, + "road_type": self.road_type, + "road_shape": self.road_shape, + "day_type": self.day_type, + "police_unit": self.police_unit, "mainStreet": self.mainStreet, "secondaryStreet": self.secondaryStreet, "junction": self.junction, @@ -293,7 +297,7 @@ def serialize(self, is_thin=False): "one_lane": self.one_lane, "multi_lane": self.multi_lane, "speed_limit": self.speed_limit, - "intactness": self.intactness, + "road_intactness": self.road_intactness, "road_width": self.road_width, "road_sign": self.road_sign, "road_light": self.road_light, @@ -361,29 +365,29 @@ def bounding_box_query(is_thin=False, yield_per=None, involved_and_vehicles=Fals if yield_per: markers = markers.yield_per(yield_per) if accurate and not approx: - markers = markers.filter(AccidentMarker.locationAccuracy == 1) + markers = markers.filter(AccidentMarker.location_accuracy == 1) elif approx and not accurate: - markers = markers.filter(AccidentMarker.locationAccuracy != 1) + markers = markers.filter(AccidentMarker.location_accuracy != 1) elif not accurate and not approx: return MarkerResult(markers=db.session.query(AccidentMarker).filter(sql.false()), total_records=0) if not kwargs.get('show_fatal', True): - markers = markers.filter(AccidentMarker.severity != 1) + markers = markers.filter(AccidentMarker.accident_severity != 1) if not kwargs.get('show_severe', True): - markers = markers.filter(AccidentMarker.severity != 2) + markers = markers.filter(AccidentMarker.accident_severity != 2) if not kwargs.get('show_light', True): - markers = markers.filter(AccidentMarker.severity != 3) + markers = markers.filter(AccidentMarker.accident_severity != 3) if kwargs.get('show_urban', 3) != 3: if kwargs['show_urban'] == 2: - markers = markers.filter(AccidentMarker.roadType >= 1).filter(AccidentMarker.roadType <= 2) + markers = markers.filter(AccidentMarker.road_type >= 1).filter(AccidentMarker.roadType <= 2) elif kwargs['show_urban'] == 1: - markers = markers.filter(AccidentMarker.roadType >= 3).filter(AccidentMarker.roadType <= 4) + markers = markers.filter(AccidentMarker.road_type >= 3).filter(AccidentMarker.roadType <= 4) else: return MarkerResult(markers=db.session.query(AccidentMarker).filter(sql.false()), total_records=0) if kwargs.get('show_intersection', 3) != 3: if kwargs['show_intersection'] == 2: - markers = markers.filter(AccidentMarker.roadType != 2).filter(AccidentMarker.roadType != 4) + markers = markers.filter(AccidentMarker.road_type != 2).filter(AccidentMarker.roadType != 4) elif kwargs['show_intersection'] == 1: - markers = markers.filter(AccidentMarker.roadType != 1).filter(AccidentMarker.roadType != 3) + markers = markers.filter(AccidentMarker.road_type != 1).filter(AccidentMarker.roadType != 3) else: return MarkerResult(markers=db.session.query(AccidentMarker).filter(sql.false()), total_records=0) if kwargs.get('show_lane', 3) != 3: @@ -397,7 +401,7 @@ def bounding_box_query(is_thin=False, yield_per=None, involved_and_vehicles=Fals if kwargs.get('show_day', 7) != 7: markers = markers.filter(func.extract("dow", AccidentMarker.created) == kwargs['show_day']) if kwargs.get('show_holiday', 0) != 0: - markers = markers.filter(AccidentMarker.dayType == kwargs['show_holiday']) + markers = markers.filter(AccidentMarker.day_type == kwargs['show_holiday']) if kwargs.get('show_time', 24) != 24: if kwargs['show_time'] == 25: # Daylight (6-18) @@ -415,20 +419,20 @@ def bounding_box_query(is_thin=False, yield_per=None, involved_and_vehicles=Fals if kwargs.get('weather', 0) != 0: markers = markers.filter(AccidentMarker.weather == kwargs['weather']) if kwargs.get('road', 0) != 0: - markers = markers.filter(AccidentMarker.roadShape == kwargs['road']) + markers = markers.filter(AccidentMarker.road_shape == kwargs['road']) if kwargs.get('separation', 0) != 0: markers = markers.filter(AccidentMarker.multi_lane == kwargs['separation']) if kwargs.get('surface', 0) != 0: markers = markers.filter(AccidentMarker.road_surface == kwargs['surface']) if kwargs.get('acctype', 0) != 0: if kwargs['acctype'] <= 20: - markers = markers.filter(AccidentMarker.subtype == kwargs['acctype']) + markers = markers.filter(AccidentMarker.accident_type == kwargs['acctype']) elif kwargs['acctype'] == CONST.BIKE_ACCIDENTS: markers = markers.filter(AccidentMarker.vehicles.any(Vehicle.vehicle_type == CONST.VEHICLE_TYPE_BIKE)) if kwargs.get('controlmeasure', 0) != 0: markers = markers.filter(AccidentMarker.road_control == kwargs['controlmeasure']) if kwargs.get('district', 0) != 0: - markers = markers.filter(AccidentMarker.unit == kwargs['district']) + markers = markers.filter(AccidentMarker.police_unit == kwargs['district']) if kwargs.get('case_type', 0) != 0: markers = markers.filter(AccidentMarker.provider_code == kwargs['case_type']) @@ -798,21 +802,21 @@ class AccidentsNoLocation(Base, MarkerMixin): provider_and_id = Column(BigInteger()) provider_code = Column(Integer(), primary_key=True) description = Column(Text()) - subtype = Column(Integer()) - severity = Column(Integer()) + accident_type = Column(Integer()) + accident_severity = Column(Integer()) address = Column(Text()) - locationAccuracy = Column(Integer()) - roadType = Column(Integer()) - roadShape = Column(Integer()) - dayType = Column(Integer()) - unit = Column(Integer()) + location_accuracy = Column(Integer()) + road_type = Column(Integer()) + road_shape = Column(Integer()) + day_type = Column(Integer()) + police_unit = Column(Integer()) mainStreet = Column(Text()) secondaryStreet = Column(Text()) junction = Column(Text()) one_lane = Column(Integer()) multi_lane = Column(Integer()) speed_limit = Column(Integer()) - intactness = Column(Integer()) + road_intactness = Column(Integer()) road_width = Column(Integer()) road_sign = Column(Integer()) road_light = Column(Integer()) @@ -936,3 +940,279 @@ class School(Base): class ST_MakeEnvelope(geoalchemy_functions.GenericFunction): name = 'ST_MakeEnvelope' type = Geometry + +class ColumnsDescription(Base): + __tablename__ = "columns_description" + id = Column(Integer(), primary_key=True, index=True) + column_description = Column(Text(), nullable=True) + +class PoliceUnit(Base): + __tablename__ = "police_unit" + id = Column(Integer(), primary_key=True, index=True) + police_unit_hebrew = Column(Text(), nullable=True) + +class RoadType(Base): + __tablename__ = "road_type" + id = Column(Integer(), primary_key=True, index=True) + road_type_hebrew = Column(Text(), nullable=True) + +class AccidentSeverity(Base): + __tablename__ = "accident_severity" + id = Column(Integer(), primary_key=True, index=True) + accident_severity_hebrew = Column(Text(), nullable=True) + +class AccidentType(Base): + __tablename__ = "accident_type" + id = Column(Integer(), primary_key=True, index=True) + accident_type_hebrew = Column(Text(), nullable=True) + +class RoadShape(Base): + __tablename__ = "road_shape" + id = Column(Integer(), primary_key=True, index=True) + road_shape_hebrew = Column(Text(), nullable=True) + +class OneLane(Base): + __tablename__ = "one_lane" + id = Column(Integer(), primary_key=True, index=True) + one_lane_hebrew = Column(Text(), nullable=True) + +class MultiLane(Base): + __tablename__ = "multi_lane" + id = Column(Integer(), primary_key=True, index=True) + multi_lane_hebrew = Column(Text(), nullable=True) + +class SpeedLimit(Base): + __tablename__ = "speed_limit" + id = Column(Integer(), primary_key=True, index=True) + speed_limit_hebrew = Column(Text(), nullable=True) + +class RoadIntactness(Base): + __tablename__ = "road_intactness" + id = Column(Integer(), primary_key=True, index=True) + road_intactness_hebrew = Column(Text(), nullable=True) + +class RoadWidth(Base): + __tablename__ = "road_width" + id = Column(Integer(), primary_key=True, index=True) + road_width_hebrew = Column(Text(), nullable=True) + +class RoadSign(Base): + __tablename__ = "road_sign" + id = Column(Integer(), primary_key=True, index=True) + road_sign_hebrew = Column(Text(), nullable=True) + +class RoadLight(Base): + __tablename__ = "road_light" + id = Column(Integer(), primary_key=True, index=True) + road_light_hebrew = Column(Text(), nullable=True) + +class RoadControl(Base): + __tablename__ = "road_control" + id = Column(Integer(), primary_key=True, index=True) + road_control_hebrew = Column(Text(), nullable=True) + +class Weather(Base): + __tablename__ = "weather" + id = Column(Integer(), primary_key=True, index=True) + weather_hebrew = Column(Text(), nullable=True) + +class RoadSurface(Base): + __tablename__ = "road_surface" + id = Column(Integer(), primary_key=True, index=True) + road_surface_hebrew = Column(Text(), nullable=True) + +class RoadObjecte(Base): + __tablename__ = "road_object" + id = Column(Integer(), primary_key=True, index=True) + road_object_hebrew = Column(Text(), nullable=True) + +class ObjectDistance(Base): + __tablename__ = "object_distance" + id = Column(Integer(), primary_key=True, index=True) + object_distance_hebrew = Column(Text(), nullable=True) + +class DidntCross(Base): + __tablename__ = "didnt_cross" + id = Column(Integer(), primary_key=True, index=True) + didnt_cross_hebrew = Column(Text(), nullable=True) + +class CrossMode(Base): + __tablename__ = "cross_mode" + id = Column(Integer(), primary_key=True, index=True) + cross_mode_hebrew = Column(Text(), nullable=True) + +class CrossLocation(Base): + __tablename__ = "cross_location" + id = Column(Integer(), primary_key=True, index=True) + cross_location_hebrew = Column(Text(), nullable=True) + +class CrossDirection(Base): + __tablename__ = "cross_direction" + id = Column(Integer(), primary_key=True, index=True) + cross_direction_hebrew = Column(Text(), nullable=True) + +class DrivingDirections(Base): + __tablename__ = "driving_directions" + id = Column(Integer(), primary_key=True, index=True) + driving_directions_hebrew = Column(Text(), nullable=True) + +class VehicleStatus(Base): + __tablename__ = "vehicle_status" + id = Column(Integer(), primary_key=True, index=True) + vehicle_status_hebrew = Column(Text(), nullable=True) + +class InvolvedType(Base): + __tablename__ = "involved_type" + id = Column(Integer(), primary_key=True, index=True) + involved_type_hebrew = Column(Text(), nullable=True) + +class SafetyMeasures(Base): + __tablename__ = "safety_measures" + id = Column(Integer(), primary_key=True, index=True) + safety_measures_hebrew = Column(Text(), nullable=True) + +class InjurySeverity(Base): + __tablename__ = "injury_severity" + id = Column(Integer(), primary_key=True, index=True) + injury_severity_hebrew = Column(Text(), nullable=True) + +class DayType(Base): + __tablename__ = "day_type" + id = Column(Integer(), primary_key=True, index=True) + day_type_hebrew = Column(Text(), nullable=True) + +class DayNight(Base): + __tablename__ = "day_night" + id = Column(Integer(), primary_key=True, index=True) + day_night_hebrew = Column(Text(), nullable=True) + +class DayInWeek(Base): + __tablename__ = "day_in_week" + id = Column(Integer(), primary_key=True, index=True) + day_in_week_hebrew = Column(Text(), nullable=True) + +class TrafficLight(Base): + __tablename__ = "traffic_light" + id = Column(Integer(), primary_key=True, index=True) + traffic_light_hebrew = Column(Text(), nullable=True) + +class VehicleAttribution(Base): + __tablename__ = "vehicle_attribution" + id = Column(Integer(), primary_key=True, index=True) + vehicle_attribution_hebrew = Column(Text(), nullable=True) + +class VehicleType(Base): + __tablename__ = "vehicle_type" + id = Column(Integer(), primary_key=True, index=True) + vehicle_type_hebrew = Column(Text(), nullable=True) + +class InjuredType(Base): + __tablename__ = "injured_type" + id = Column(Integer(), primary_key=True, index=True) + injured_type_hebrew = Column(Text(), nullable=True) + +class InjuredPosition(Base): + __tablename__ = "injured_position" + id = Column(Integer(), primary_key=True, index=True) + injured_position_hebrew = Column(Text(), nullable=True) + +class AccidentMonth(Base): + __tablename__ = "accident_month" + id = Column(Integer(), primary_key=True, index=True) + accident_month_hebrew = Column(Text(), nullable=True) + + +class PopulationType(Base): + __tablename__ = "population_type" + id = Column(Integer(), primary_key=True, index=True) + population_type_hebrew = Column(Text(), nullable=True) + +class Sex(Base): + __tablename__ = "sex" + id = Column(Integer(), primary_key=True, index=True) + sex_hebrew = Column(Text(), nullable=True) + +class GeoArea(Base): + __tablename__ = "geo_area" + id = Column(Integer(), primary_key=True, index=True) + geo_area_hebrew = Column(Text(), nullable=True) + +class Region(Base): + __tablename__ = "region" + id = Column(Integer(), primary_key=True, index=True) + region_hebrew = Column(Text(), nullable=True) + +class MinizipaliStatus(Base): + __tablename__ = "minizipali_status" + id = Column(Integer(), primary_key=True, index=True) + minizipali_status_hebrew = Column(Text(), nullable=True) + +class District(Base): + __tablename__ = "district" + id = Column(Integer(), primary_key=True, index=True) + district_hebrew = Column(Text(), nullable=True) + +class NaturalArea(Base): + __tablename__ = "natural_area" + id = Column(Integer(), primary_key=True, index=True) + natural_area_hebrew = Column(Text(), nullable=True) + +class YishuvShape(Base): + __tablename__ = "yishuv_shape" + id = Column(Integer(), primary_key=True, index=True) + yishuv_shape_hebrew = Column(Text(), nullable=True) + +class AgeGroup(Base): + __tablename__ = "age_group" + id = Column(Integer(), primary_key=True, index=True) + age_group_hebrew = Column(Text(), nullable=True) + +class AccidentHourRaw(Base): + __tablename__ = "accident_hour_raw" + id = Column(Integer(), primary_key=True, index=True) + accident_hour_raw_hebrew = Column(Text(), nullable=True) + +class EngineVolume(Base): + __tablename__ = "engine_volume" + id = Column(Integer(), primary_key=True, index=True) + engine_volume_hebrew = Column(Text(), nullable=True) + +class TotalWeight(Base): + __tablename__ = "total_weight" + id = Column(Integer(), primary_key=True, index=True) + total_weight_hebrew = Column(Text(), nullable=True) + +class HospitalTime(Base): + __tablename__ = "hospital_time" + id = Column(Integer(), primary_key=True, index=True) + hospital_time_hebrew = Column(Text(), nullable=True) + +class MedicalType(Base): + __tablename__ = "medical_type" + id = Column(Integer(), primary_key=True, index=True) + medical_type_hebrew = Column(Text(), nullable=True) + +class ReleaseDest(Base): + __tablename__ = "release_dest" + id = Column(Integer(), primary_key=True, index=True) + release_dest_hebrew = Column(Text(), nullable=True) + +class SafetyMeasuresUse(Base): + __tablename__ = "safety_measures_use" + id = Column(Integer(), primary_key=True, index=True) + safety_measures_use_hebrew = Column(Text(), nullable=True) + +class LateDeceased(Base): + __tablename__ = "late_deceased" + id = Column(Integer(), primary_key=True, index=True) + late_deceased_hebrew = Column(Text(), nullable=True) + +class LocationAccuracy(Base): + __tablename__ = "location_accuracy" + id = Column(Integer(), primary_key=True, index=True) + location_accuracy_hebrew = Column(Text(), nullable=True) + +class ProviderCode(Base): + __tablename__ = "provider_code" + id = Column(Integer(), primary_key=True, index=True) + provider_code_hebrew = Column(Text(), nullable=True) diff --git a/anyway/parsers/cbs.py b/anyway/parsers/cbs.py index ad35754ac..d18ebee61 100755 --- a/anyway/parsers/cbs.py +++ b/anyway/parsers/cbs.py @@ -2,7 +2,7 @@ import glob import os import json -from collections import OrderedDict +from collections import OrderedDict, defaultdict import itertools import re from datetime import datetime @@ -12,7 +12,67 @@ from sqlalchemy import or_ from .. import field_names, localization -from ..models import AccidentMarker, Involved, Vehicle, AccidentsNoLocation, InvolvedNoLocation, VehicleNoLocation +from ..models import (AccidentMarker, + Involved, + Vehicle, + AccidentsNoLocation, + InvolvedNoLocation, + VehicleNoLocation, + ColumnsDescription, + PoliceUnit, + RoadType, + AccidentSeverity, + AccidentType, + RoadShape, + OneLane, + MultiLane, + SpeedLimit, + RoadIntactness, + RoadWidth, + RoadSign, + RoadLight, + RoadControl, + Weather, + RoadSurface, + RoadObjecte, + ObjectDistance, + DidntCross, + CrossMode, + CrossLocation, + CrossDirection, + DrivingDirections, + VehicleStatus, + InvolvedType, + SafetyMeasures, + InjurySeverity, + DayType, + DayNight, + DayInWeek, + TrafficLight, + VehicleAttribution, + VehicleType, + InjuredType, + InjuredPosition, + AccidentMonth, + PopulationType, + Sex, + GeoArea, + Region, + MinizipaliStatus, + District, + NaturalArea, + YishuvShape, + AgeGroup, + AccidentHourRaw, + EngineVolume, + TotalWeight, + HospitalTime, + MedicalType, + ReleaseDest, + SafetyMeasuresUse, + LateDeceased, + LocationAccuracy) + from .. import models from ..constants import CONST from ..utilities import ItmToWGS84, init_flask, CsvReader, time_delta, decode_hebrew,ImporterUI,truncate_tables,chunks @@ -44,6 +104,122 @@ VEHICLES: "VehData.csv" } +DICTCOLUMN1 = "MS_TAVLA" +DICTCOLUMN2 = "KOD" +DICTCOLUMN3 = "TEUR" + +CLASSES_DICT = {0: ColumnsDescription, + 1: PoliceUnit, + 2: RoadType, + 4: AccidentSeverity, + 5: AccidentType, + 9: RoadShape, + 10: OneLane, + 11: MultiLane, + 12: SpeedLimit, + 13: RoadIntactness, + 14: RoadWidth, + 15: RoadSign, + 16: RoadLight, + 17: RoadControl, + 18: Weather, + 19: RoadSurface, + 21: RoadObjecte, + 22: ObjectDistance, + 23: DidntCross, + 24: CrossMode, + 25: CrossLocation, + 26: CrossDirection, + 28: DrivingDirections, + 30: VehicleStatus, + 31: InvolvedType, + 34: SafetyMeasures, + 35: InjurySeverity, + 37: DayType, + 38: DayNight, + 39: DayInWeek, + 40: TrafficLight, + 43: VehicleAttribution, + 45: VehicleType, + 50: InjuredType, + 52: InjuredPosition, + 60: AccidentMonth, + 66: PopulationType, + 67: Sex, + 68: GeoArea, + 77: Region, + 78: MinizipaliStatus, + 79: District, + 80: NaturalArea, + 81: YishuvShape, + 92: AgeGroup, + 93: AccidentHourRaw, + 111: EngineVolume, + 112: TotalWeight, + 200: HospitalTime, + 201: MedicalType, + 202: ReleaseDest, + 203: SafetyMeasuresUse, + 204: LateDeceased, + 205: LocationAccuracy, +} + +TABLES_DICT = {0: 'columns_description', + 1: 'police_unit', + 2: 'road_type', + 4: 'accident_severity', + 5: 'accident_type', + 9: 'road_shape', + 10: 'one_lane', + 11: 'multi_lane', + 12: 'speed_limit', + 13: 'road_intactness', + 14: 'road_width', + 15: 'road_sign', + 16: 'road_light', + 17: 'road_control', + 18: 'weather', + 19: 'road_surface', + 21: 'road_object', + 22: 'object_distance', + 23: 'didnt_cross', + 24: 'cross_mode', + 25: 'cross_location', + 26: 'cross_direction', + 28: 'driving_directions', + 30: 'vehicle_status', + 31: 'involved_type', + 34: 'safety_measures', + 35: 'injury_severity', + 37: 'day_type', + 38: 'day_night', + 39: 'day_in_week', + 40: 'traffic_light', + 43: 'vehicle_attribution', + 45: 'vehicle_type', + 50: 'injured_type', + 52: 'injured_position', + 60: 'accident_month', + 66: 'population_type', + 67: 'sex', + 68: 'geo_area', + 77: 'region', + 78: 'minizipali_status', + 79: 'district', + 80: 'natural_area', + 81: 'yishuv_shape', + 92: 'age_group', + 93: 'accident_hour_raw', + 111: 'engine_volume', + 112: 'total_weight', + 200: 'hospital_time', + 201: 'medical_type', + 202: 'release_dest', + 203: 'safety_measures_use', + 204: 'late_deceased', + 205: 'location_accuracy', +} + coordinates_converter = ItmToWGS84() app = init_flask() db = SQLAlchemy(app) @@ -97,6 +273,15 @@ def get_streets(accident, streets): secondary_street = get_street(accident[field_names.settlement_sign], accident[field_names.street2], streets) return main_street, secondary_street +def get_non_urban_intersection(accident, roads): + """ + extracts the non-urban-intersection from an accident + """ + if accident[field_names.non_urban_intersection] is not None: + key = accident[field_names.road1], accident[field_names.road2], accident[field_names.km] + junction = roads.get(key, None) + return decode_hebrew(junction) if junction else u"" + return u"" def get_junction(accident, roads): """ @@ -133,7 +318,7 @@ def get_junction(accident, roads): return u"" elif accident[field_names.non_urban_intersection] is not None: - key = accident[field_names.road1], accident[field_names.road2], accident["KM"] + key = accident[field_names.road1], accident[field_names.road2], accident[field_names.km] junction = roads.get(key, None) return decode_hebrew(junction) if junction else u"" else: @@ -224,21 +409,21 @@ def import_accidents(provider_code, accidents, streets, roads, **kwargs): "address": get_address(accident, streets), "latitude": lat, "longitude": lng, - "subtype": int(accident[field_names.accident_type]), - "severity": int(accident[field_names.accident_severity]), + "accident_type": int(accident[field_names.accident_type]), + "accident_severity": int(accident[field_names.accident_severity]), "created": accident_datetime, - "locationAccuracy": int(accident[field_names.igun]), - "roadType": int(accident[field_names.road_type]), - "roadShape": int(accident[field_names.road_shape]), - "dayType": int(accident[field_names.day_type]), - "unit": int(accident[field_names.unit]), + "location_accuracy": int(accident[field_names.igun]), + "road_type": int(accident[field_names.road_type]), + "road_shape": int(accident[field_names.road_shape]), + "day_type": int(accident[field_names.day_type]), + "police_unit": int(accident[field_names.police_unit]), "mainStreet": main_street, "secondaryStreet": secondary_street, "junction": get_junction(accident, roads), "one_lane": get_data_value(accident[field_names.one_lane]), "multi_lane": get_data_value(accident[field_names.multi_lane]), "speed_limit": get_data_value(accident[field_names.speed_limit]), - "intactness": get_data_value(accident[field_names.intactness]), + "road_intactness": get_data_value(accident[field_names.road_intactness]), "road_width": get_data_value(accident[field_names.road_width]), "road_sign": get_data_value(accident[field_names.road_sign]), "road_light": get_data_value(accident[field_names.road_light]), @@ -255,6 +440,7 @@ def import_accidents(provider_code, accidents, streets, roads, **kwargs): "road2": get_data_value(accident[field_names.road2]), "km": float(accident[field_names.km]) if accident[field_names.km] else None, "yishuv_symbol": get_data_value(accident[field_names.yishuv_symbol]), + "yishuv_name": localization.get_city_name(accident[field_names.settlement_sign]), "geo_area": get_data_value(accident[field_names.geo_area]), "day_night": get_data_value(accident[field_names.day_night]), "day_in_week": get_data_value(accident[field_names.day_in_week]), @@ -265,10 +451,13 @@ def import_accidents(provider_code, accidents, streets, roads, **kwargs): "minizipali_status": get_data_value(accident[field_names.minizipali_status]), "yishuv_shape": get_data_value(accident[field_names.yishuv_shape]), "street1": get_data_value(accident[field_names.street1]), + "street1_hebrew": get_street(accident[field_names.settlement_sign], accident[field_names.street1], streets), "street2": get_data_value(accident[field_names.street2]), + "street2_hebrew": get_street(accident[field_names.settlement_sign], accident[field_names.street2], streets), "home": get_data_value(accident[field_names.home]), "urban_intersection": get_data_value(accident[field_names.urban_intersection]), "non_urban_intersection": get_data_value(accident[field_names.non_urban_intersection]), + "non_urban_intersection_hebrew": get_non_urban_intersection(accident, roads), "accident_year": get_data_value(accident[field_names.accident_year]), "accident_month": get_data_value(accident[field_names.accident_month]), "accident_day": get_data_value(accident[field_names.accident_day]), @@ -526,6 +715,7 @@ def delete_cbs_entries(start_date, batch_size): q.delete(synchronize_session=False) db.session.commit() + def fill_db_geo_data(): """ Fills empty geometry object according to coordinates in database @@ -547,7 +737,37 @@ def get_provider_code(directory_name=None): return int(ans) -def main(specific_folder, delete_all, path, batch_size, delete_start_date): +def read_dictionary(dictionary_file): + cbs_dictionary = defaultdict(dict) + dictionary = CsvReader(dictionary_file, encoding=CONTENT_ENCODING) + for dic in dictionary: + if type(dic[DICTCOLUMN3]) is str: + cbs_dictionary[int(dic[DICTCOLUMN1])][int(dic[DICTCOLUMN2])] = decode_hebrew(dic[DICTCOLUMN3], + encoding=CONTENT_ENCODING) + else: + cbs_dictionary[int(dic[DICTCOLUMN1])][int(dic[DICTCOLUMN2])] = int(dic[DICTCOLUMN3]) + return cbs_dictionary + +def create_dictionary_tables(dictionary_file): + cbs_dictionary = read_dictionary(dictionary_file) + for k,v in cbs_dictionary.iteritems(): + if k == 97: + continue + curr_table = TABLES_DICT[k] + curr_class = CLASSES_DICT[k] + table_entries = db.session.query(curr_class) + table_entries.delete() + for inner_k,inner_v in v.iteritems(): + sql_insert = 'INSERT INTO ' + curr_table + ' VALUES (' + str(inner_k) + ',' + "'" + inner_v.replace("'",'') + "'" + ')' + db.session.execute(sql_insert) + db.session.commit() + + +def main(specific_folder, delete_all, path, batch_size, delete_start_date, dictionary_file): + + if dictionary_file is not None: + create_dictionary_tables(dictionary_file) + import_ui = ImporterUI(path, specific_folder, delete_all) dir_name = import_ui.source_path() diff --git a/anyway/parsers/rsa.py b/anyway/parsers/rsa.py index 8062fb5c2..87d1beae0 100644 --- a/anyway/parsers/rsa.py +++ b/anyway/parsers/rsa.py @@ -46,10 +46,10 @@ def _iter_rows(filename): 'longitude': longitude, 'created': timestamp, 'provider_code': CONST.RSA_PROVIDER_CODE, - 'severity': 0, + 'accident_severity': 0, 'title': 'שומרי הדרך', 'description': json.dumps(description), - 'locationAccuracy': 1, + 'location_accuracy': 1, 'type': CONST.MARKER_TYPE_ACCIDENT, 'video_link': video_link} diff --git a/anyway/parsers/united.py b/anyway/parsers/united.py index 87693c4e5..5deb3af93 100644 --- a/anyway/parsers/united.py +++ b/anyway/parsers/united.py @@ -289,14 +289,14 @@ def create_accidents(collection, file_location): 'longitude': accident[csvmap["long"]], 'created': created, 'provider_code': PROVIDER_CODE, 'title': decode_hebrew(accident[csvmap["type"]], encoding="utf-8")[:100], 'address': decode_hebrew((accident[csvmap["street"]] + ' ' + accident[csvmap["city"]]), encoding="utf-8"), - 'severity': 2 if u"קשה" in decode_hebrew(accident[csvmap["type"]], encoding="utf-8") else 3, - 'locationAccuracy': 1, 'subtype': 21, 'type': CONST.MARKER_TYPE_ACCIDENT, + 'accident_severity': 2 if u"קשה" in decode_hebrew(accident[csvmap["type"]], encoding="utf-8") else 3, + 'location_accuracy': 1, 'accident_type': 21, 'type': CONST.MARKER_TYPE_ACCIDENT, 'description': decode_hebrew(accident[csvmap["comment"]], encoding="utf-8"), 'weather': process_weather_data(collection, accident[csvmap["lat"]], accident[csvmap["long"]])} if format_version == 0: casualties = accident[csvmap["casualties"]] - marker['intactness'] = casualties if casualties.isdigit() else 0 + marker['road_intactness'] = casualties if casualties.isdigit() else 0 yield marker diff --git a/anyway/scripts/accidents_around_location.py b/anyway/scripts/accidents_around_location.py index 93053ad8d..b55752754 100644 --- a/anyway/scripts/accidents_around_location.py +++ b/anyway/scripts/accidents_around_location.py @@ -68,7 +68,7 @@ def calc_markers(markers): DEADLY_WEIGHT = 7 HARD_WEIGHT = 5 LIGHT_WEIGHT = 1 - severities = [x.get("severity", 1) for x in markers] + severities = [x.get("accident_severity", 1) for x in markers] light_count = severities.count(3) hard_count = severities.count(2) deadly_count = severities.count(1) @@ -109,7 +109,7 @@ def get_accidents_around(city, name, lat, lon, start_date, end_date, distance, p except Exception as e: print 'failed to parse:', markers_res.text raise e - markers = [x for x in markers if x['locationAccuracy'] not in (2, 9)] + markers = [x for x in markers if x['location_accuracy'] not in (2, 9)] markers_data = calc_markers(markers) accidents_details = dict() diff --git a/anyway/simple_import.py b/anyway/simple_import.py index 898b28320..b359ca2ed 100644 --- a/anyway/simple_import.py +++ b/anyway/simple_import.py @@ -23,7 +23,7 @@ latitude = "00.33", longitude = "00.22", type = CONST.MARKER_TYPE_ACCIDENT, - subtype = "", + accident_type = "", created = datetime.datetime.now(), ) session.add(marker) diff --git a/custom_queries/view_lamas_markers_by_city_and_date.sql b/custom_queries/view_lamas_markers_by_city_and_date.sql index 140f29e2d..a2fff4f28 100644 --- a/custom_queries/view_lamas_markers_by_city_and_date.sql +++ b/custom_queries/view_lamas_markers_by_city_and_date.sql @@ -3,7 +3,7 @@ lamas_markers_by_city_and_date AS SELECT id, trim(both '* ' FROM (regexp_split_to_array(address, ',\s*'))[2]) AS city, - severity, + accident_severity, CAST(date_part('year', created) AS INTEGER) AS year, CAST(date_part('month', created) AS INTEGER) AS month, CAST(date_part('dow', created) AS INTEGER) AS day_of_week @@ -27,8 +27,8 @@ $$ LANGUAGE plpgsql IMMUTABLE; CREATE OR REPLACE VIEW lamas_marker_counts_by_city_year_and_severity AS - SELECT city ,year, severity, + SELECT city ,year, accident_severity, COUNT(DISTINCT id) AS count, - severity_to_weight(severity) * COUNT(DISTINCT id) AS weighted_count + severity_to_weight(accident_severity) * COUNT(DISTINCT id) AS weighted_count FROM lamas_markers_by_city_and_date - GROUP BY city, year, severity; + GROUP BY city, year, accident_severity; diff --git a/main.py b/main.py index 07bd32561..aafbb6b43 100755 --- a/main.py +++ b/main.py @@ -48,12 +48,17 @@ def process(): @click.option('--path', type=str, default="static/data/cbs") @click.option('--batch_size', type=int, default=5000) @click.option('--delete_start_date', type=str, default=None) +@click.option('--dictionary_file', type=str, default=None) -def cbs(specific_folder, delete_all, path, batch_size, delete_start_date): +def cbs(specific_folder, delete_all, path, batch_size, delete_start_date, dictionary_file): from anyway.parsers.cbs import main - return main(specific_folder=specific_folder, delete_all=delete_all, path=path, - batch_size=batch_size, delete_start_date=delete_start_date) + return main(specific_folder=specific_folder, + delete_all=delete_all, + path=path, + batch_size=batch_size, + delete_start_date=delete_start_date, + dictionary_file=dictionary_file) @process.command() @click.option('--specific_folder', is_flag=True, default=False) diff --git a/static/js/app.js b/static/js/app.js index 1ac40e909..e742bc621 100644 --- a/static/js/app.js +++ b/static/js/app.js @@ -1,4 +1,4 @@ -$(function () { +$(function() { var GESTURE_HANDLING = (MAP_ONLY ? "cooperative" : "greedy"); var AppRouter = Backbone.Router.extend({ @@ -17,7 +17,7 @@ $(function () { // app.map.setZoom(parseInt(zoom)); // app.map.setCenter(new google.maps.LatLng(lat, lon)); //}, - navigateEmpty: function () { + navigateEmpty: function() { app.model.set("currentMarker", null); } }); @@ -31,11 +31,11 @@ $(function () { pageSize: ENTRIES_PER_PAGE }, - parseRecords: function (response) { + parseRecords: function(response) { return response.markers; }, - parseState: function (response) { + parseState: function(response) { return response.pagination; } }); @@ -43,16 +43,15 @@ $(function () { window.ClusterCollection = Backbone.Collection.extend({ url: "/clusters", - parse: function (response, options) { + parse: function(response, options) { return response.clusters; } }); window.AppView = Backbone.View.extend({ - el : $("#app"), - events : { - }, - initialize : function() { + el: $("#app"), + events: {}, + initialize: function() { var url_params = new URLSearchParams(window.location.search); this.markers = new MarkerCollection(); @@ -93,7 +92,7 @@ $(function () { this.dateRanges = [new Date($('#sdateInit').val()), new Date($('#edateInit').val())]; - setTimeout(function(){ + setTimeout(function() { this.firstLoadDelay = false; }.bind(this), 2200); @@ -115,15 +114,15 @@ $(function () { this.model .bind("change:user", this.updateUser, this) .bind("change:showFatal", - _.bind(this.reloadMarkersIfNeeded, this, "showFatal")) + _.bind(this.reloadMarkersIfNeeded, this, "showFatal")) .bind("change:showSevere", - _.bind(this.reloadMarkersIfNeeded, this, "showSevere")) + _.bind(this.reloadMarkersIfNeeded, this, "showSevere")) .bind("change:showLight", - _.bind(this.reloadMarkersIfNeeded, this, "showLight")) + _.bind(this.reloadMarkersIfNeeded, this, "showLight")) .bind("change:showRSA", - _.bind(this.reloadMarkersIfNeeded, this, "showRSA")) + _.bind(this.reloadMarkersIfNeeded, this, "showRSA")) .bind("change:showInaccurateMarkers", - _.bind(this.reloadMarkersIfNeeded, this, "showInaccurateMarkers")) + _.bind(this.reloadMarkersIfNeeded, this, "showInaccurateMarkers")) .bind("change:dateRange", this.reloadMarkers, this); }, reloadMarkersIfNeeded: function(attr) { @@ -134,12 +133,12 @@ $(function () { this.loadMarkers(); } }, - updateUrl: function (url) { + updateUrl: function(url) { if (typeof url == 'undefined') { if (app.infoWindow || app.discussionShown) return; //url = "/?" + this.getCurrentUrlParams(); url = ""; - }else{ + } else { var questionMarkPlace = url.indexOf('?'); if (questionMarkPlace != -1) { url = url.substring(0, questionMarkPlace); @@ -153,25 +152,25 @@ $(function () { url = url.substring(0, googleCallbackPattern); } } - Backbone.history.navigate(Backbone.history.fragment, false); - // Backbone.history.navigate(url, true); - window.history.pushState('','','/'); + Backbone.history.navigate(Backbone.history.fragment, false); + // Backbone.history.navigate(url, true); + window.history.pushState('', '', '/'); }, - clusterMode: function () { + clusterMode: function() { return this.map.zoom < MINIMAL_ZOOM; }, - zoomChanged: function () { + zoomChanged: function() { this.resetOnMouseUp = true; this.fetchMarkers(); }, - reloadMarkers: function () { - if (!this.firstLoadDelay){ + reloadMarkers: function() { + if (!this.firstLoadDelay) { this.oms.unspiderfy(); this.clearMarkersFromMap(); this.fetchMarkers(); } }, - fetchMarkers: function () { + fetchMarkers: function() { if (!this.isReady) return; var params = this.buildMarkersParams(); @@ -228,40 +227,40 @@ $(function () { }); } }, - reloadSidebar: function () { + reloadSidebar: function() { // HeatMap action is here because we're waiting for the markers/clusters to fetch from the server (AJAX request) and reloadSidebar() is being called on success. if (this.clusterMode()) { this.sidebar.emptyMarkerList(); - if (this.heatMapMode){ + if (this.heatMapMode) { this.heatmap.setMap(null); // Drawing HeatMap for clusters this.buildHeatMap("clusters"); } } else { // close enough - if (this.heatMapMode){ + if (this.heatMapMode) { this.heatmap.setMap(null); // Drawing HeatMap for markers this.buildHeatMap("markers"); - }else{ + } else { this.setMultipleMarkersIcon(); } this.sidebar.reloadMarkerList(this.markerList); } - if (jsPanelInst!=null){ + if (jsPanelInst != null) { startJSPanelWithChart(jsPanelInst, $("#statPanel").width(), $("#statPanel").height(), - $("#statPanel").width() - 30, $("#statPanel").height() - 80); + $("#statPanel").width() - 30, $("#statPanel").height() - 80); } this.updateFilterString(); this.chooseMarker(); - if(this.iconTypeChanged == true){ + if (this.iconTypeChanged == true) { this.$el.find(".current-view").toggleClass("sidebar-pin"); this.$el.find(".current-view").toggleClass("sidebar-dot"); this.iconTypeChanged = false; } }, - buildMarkersParams: function (isForUrl) { + buildMarkersParams: function(isForUrl) { var bounds = this.map.getBounds(); if (!bounds) return null; var zoom = this.map.zoom; @@ -278,7 +277,7 @@ $(function () { // Pass start and end dates as unix time (in seconds) params["start_date"] = this.dateRanges[0].getTime() / 1000; params["end_date"] = this.dateRanges[1].getTime() / 1000; - }else{ + } else { var center = app.map.getCenter(); params["zoom"] = zoom; params["start_date"] = moment(this.dateRanges[0]).format("YYYY-MM-DD"); @@ -314,46 +313,50 @@ $(function () { params["age_groups"] = this.age_groups; return params; }, - setMultipleMarkersIcon: function () { + setMultipleMarkersIcon: function() { var groupID = 1; var groupsData = []; - _.each(this.oms.markersNearAnyOtherMarker(), function (marker) { + _.each(this.oms.markersNearAnyOtherMarker(), function(marker) { marker.view.model.unset("groupID"); }); //make single icons for those who are no longer in a group - _.each(this.markerList, function(markerView){ + _.each(this.markerList, function(markerView) { var marker = markerView.marker; - if(this.map.getBounds().contains(marker.getPosition())){ - if(!this.oms.markersNearMarker(marker,true).length){ + if (this.map.getBounds().contains(marker.getPosition())) { + if (!this.oms.markersNearMarker(marker, true).length) { marker.setTitle(markerView.getTitle("single")); } } - },this); + }, this); //goes over all overlapping markers - _.each(this.oms.markersNearAnyOtherMarker(), function (marker) { + _.each(this.oms.markersNearAnyOtherMarker(), function(marker) { var firstMember = marker.view.model; var firstMemberGroupId = firstMember.get("groupID"); - var firstMemberIndex = firstMemberGroupId -1; + var firstMemberIndex = firstMemberGroupId - 1; if (!firstMemberGroupId) { firstMemberGroupId = groupID; - firstMemberIndex = firstMemberGroupId -1; + firstMemberIndex = firstMemberGroupId - 1; firstMember.set("groupID", firstMemberGroupId); - var groupSeverity = firstMember.get('severity'); + var groupSeverity = firstMember.get('accident_severity'); var firstMemberOpacity = firstMember.get("locationAccuracy") == 1 ? 'opaque' : 1; - groupsData.push({severity: groupSeverity, opacity: firstMemberOpacity, quantity: 1}); + groupsData.push({ + accident_severity: groupSeverity, + opacity: firstMemberOpacity, + quantity: 1 + }); - //goes over all markers which overlapping 'firstMember', and get the 'max' severity - _.each(this.oms.markersNearMarker(marker), function (markerNear) { + //goes over all markers which overlapping 'firstMember', and get the 'max' accident_severity + _.each(this.oms.markersNearMarker(marker), function(markerNear) { var markerNearModel = markerNear.view.model; markerNearModel.set("groupID", firstMemberGroupId); - var currentMarkerNearSeverity = markerNearModel.get('severity'); - // severity is an enum, when it's lower then it's more severe + var currentMarkerNearSeverity = markerNearModel.get('accident_severity'); + // accident_severity is an enum, when it's lower then it's more severe if (currentMarkerNearSeverity < groupSeverity) { if (currentMarkerNearSeverity != SEVERITY_IRRELEVANT_RSA) { - groupsData[firstMemberIndex].severity = currentMarkerNearSeverity; + groupsData[firstMemberIndex].accident_severity = currentMarkerNearSeverity; groupSeverity = currentMarkerNearSeverity; } } @@ -368,26 +371,26 @@ $(function () { }); groupID++; } - if(marker.view.model.get("currentlySpiderfied")){ + if (marker.view.model.get("currentlySpiderfied")) { marker.setTitle(marker.view.getTitle("single")); - }else{ + } else { groupMarkersCount = groupsData[firstMemberIndex].quantity; - groupSeverityString = SEVERITY_MAP[groupsData[firstMemberIndex].severity]; - marker.setTitle( groupMarkersCount + " " + marker.view.getTitle("multiple") + " חומרה מירבית: " + groupSeverityString); + groupSeverityString = SEVERITY_MAP[groupsData[firstMemberIndex].accident_severity]; + marker.setTitle(groupMarkersCount + " " + marker.view.getTitle("multiple") + " חומרה מירבית: " + groupSeverityString); } - },this); + }, this); this.groupsData = groupsData; - // agam - if(tourLocation == 5) { - var myLatlng = new google.maps.LatLng(32.09170,34.86435); + // agam + if (tourLocation == 5) { + var myLatlng = new google.maps.LatLng(32.09170, 34.86435); var location1 = new google.maps.Marker({ position: myLatlng, map: this.map, icon: app.retinaIconsResize(MULTIPLE_ICONS[SEVERITY_VARIOUS]) }); - tourLocation = 6 ; - console.log("inside the group id "+tourLocation+"new2"); + tourLocation = 6; + console.log("inside the group id " + tourLocation + "new2"); contentString = '

בנקודה זו התרחשו מספר תאונות, לחיצה על האייקון תציג אותן בנפרד ותאפשר בחירה
בתאונה בודדת.

'; titleString = 'אייקון של מספר תאונות באותו מקום'; defInfoWindows(); @@ -399,7 +402,7 @@ $(function () { tourStyle(infowindow); } }, - downloadCsv: function () { + downloadCsv: function() { if (this.markers.length > 0) { params = this.buildMarkersParams(); params["format"] = "csv"; @@ -409,20 +412,20 @@ $(function () { $('#empty-csv-dialog').modal('show'); } }, - linkMap: function () { + linkMap: function() { $('#embed').modal('show'); }, openReportsModal: function() { $('#reports-modal').modal('show'); }, - fullScreen: function () { + fullScreen: function() { var body = document.body; if ( document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || - document.msFullscreenElement){ + document.msFullscreenElement) { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.webkitExitFullscreen) { @@ -432,7 +435,7 @@ $(function () { } else if (document.msExitFullscreen) { document.msExitFullscreen(); } - }else{ + } else { if (body.requestFullscreen) { body.requestFullscreen(); } else if (body.webkitRequestFullscreen) { @@ -444,7 +447,7 @@ $(function () { } } }, - render: function () { + render: function() { this.isReady = false; this.defaultLocation = new google.maps.LatLng(INIT_LAT, INIT_LON); @@ -470,31 +473,31 @@ $(function () { var resetMapDiv = document.createElement('div'); resetMapDiv.className = "map-button reset-map-control"; resetMapDiv.innerHTML = $("#reset-map-control").html(); - google.maps.event.addDomListener(resetMapDiv, 'click', function () { + google.maps.event.addDomListener(resetMapDiv, 'click', function() { this.goToMyLocation(); }.bind(this)); var downloadCsvDiv = document.createElement('div'); downloadCsvDiv.className = "map-button download-csv-control"; downloadCsvDiv.innerHTML = $("#download-csv-control").html(); - google.maps.event.addDomListener(downloadCsvDiv, 'click', function () { + google.maps.event.addDomListener(downloadCsvDiv, 'click', function() { this.downloadCsv(); }.bind(this)); var linkMapDiv = document.createElement('div'); linkMapDiv.className = 'map-button link-map-control'; linkMapDiv.innerHTML = $("#link-map-control").html(); - google.maps.event.addDomListener(linkMapDiv, 'click', function () { + google.maps.event.addDomListener(linkMapDiv, 'click', function() { var url = document.URL + "?" + this.getCurrentUrlParams(); $map_link = $("#map_link"), - $iframe_link = $("#iframe_link"), - $embed_link = $("#js-embed-link"); + $iframe_link = $("#iframe_link"), + $embed_link = $("#js-embed-link"); //if (url.indexOf('?') != -1) { // url = url.substring(0, url.indexOf('?')); //} $map_link.val(url); $iframe_link.html(''); - $(".js-btn-copytoclipboard").on("click", function(){ + $(".js-btn-copytoclipboard").on("click", function() { $("#" + $(this).data("copy")).select(); }); this.linkMap(); @@ -503,28 +506,28 @@ $(function () { var tourDiv = document.createElement('div'); tourDiv.className = "map-button tour-control blink"; tourDiv.innerHTML = $("#tour-control").html(); - google.maps.event.addDomListener(tourDiv, 'click', function () { + google.maps.event.addDomListener(tourDiv, 'click', function() { tourClick(); }.bind(this)); var statDiv = document.createElement('div'); statDiv.className = "map-button statistics-control"; statDiv.innerHTML = $("#statistics-control").html(); - google.maps.event.addDomListener(statDiv, 'click', function () { - statPanelClick(700,400,700,350); + google.maps.event.addDomListener(statDiv, 'click', function() { + statPanelClick(700, 400, 700, 350); }.bind(this)); var fullScreenDiv = document.createElement('div'); fullScreenDiv.className = "map-button full-screen-control"; fullScreenDiv.innerHTML = $("#full-screen-control").html(); - google.maps.event.addDomListener(fullScreenDiv, 'click', function () { + google.maps.event.addDomListener(fullScreenDiv, 'click', function() { this.fullScreen(); }.bind(this)); var heatMapDiv = document.createElement('div'); heatMapDiv.className = "map-button heat-map-control"; heatMapDiv.innerHTML = $("#heat-map-control").html(); - google.maps.event.addDomListener(heatMapDiv, 'click', function () { + google.maps.event.addDomListener(heatMapDiv, 'click', function() { this.heatMapMode = !this.heatMapMode; this.toggleHeatmap(); }.bind(this)); @@ -532,7 +535,7 @@ $(function () { var reportsDiv = document.createElement('div'); reportsDiv.className = "map-button reports-control"; reportsDiv.innerHTML = $("#reports-control").html(); - google.maps.event.addDomListener(reportsDiv, 'click', function () { + google.maps.event.addDomListener(reportsDiv, 'click', function() { this.openReportsModal(); }.bind(this)); @@ -591,9 +594,9 @@ $(function () { } else { this.goToMyLocation(); } - setTimeout(function(){ + setTimeout(function() { this.fetchMarkers(); - }.bind(this),2000); + }.bind(this), 2000); // search box: // Create the search box and link it to the UI element. var input = document.getElementById('pac-input'); @@ -611,8 +614,8 @@ $(function () { if (MAP_ONLY) toggleDiv.style = "display:none"; toggleDiv.title = 'שנה תצוגת אייקונים'; - google.maps.event.addDomListener(toggleBGDiv, 'click', function () { - if(! ( this.heatMapMode || this.clusterMode() ) ) { + google.maps.event.addDomListener(toggleBGDiv, 'click', function() { + if (!(this.heatMapMode || this.clusterMode())) { $(toggleDiv).toggleClass('pin'); $(toggleDiv).toggleClass('dot'); this.iconTypeChanged = true; @@ -629,7 +632,7 @@ $(function () { this.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(toggleBGDiv); - google.maps.event.addListener(this.searchBox, 'places_changed', function () { + google.maps.event.addListener(this.searchBox, 'places_changed', function() { this.handleSearchBox(); }.bind(this)); @@ -638,48 +641,49 @@ $(function () { markersWontHide: true, keepSpiderfied: true }); - this.oms.addListener("click", function (marker, event) { + this.oms.addListener("click", function(marker, event) { marker.view.clickMarker(); this.clickedMarker = true; }.bind(this)); - this.oms.addListener("spiderfy", function (markers) { + this.oms.addListener("spiderfy", function(markers) { this.closeInfoWindow(); - _.each(markers, function (marker) { + _.each(markers, function(marker) { marker.setTitle(marker.view.getTitle('single')); marker.view.model.set("currentlySpiderfied", true); }); this.clickedMarker = true; }.bind(this)); - this.oms.addListener("unspiderfy", function(markers){ - _.each(markers, function(marker){ + this.oms.addListener("unspiderfy", function(markers) { + _.each(markers, function(marker) { marker.view.model.unset("currentlySpiderfied"); }); }.bind(this)); this.oms.addListener("unspiderfy", this.setMultipleMarkersIcon.bind(this)); console.log('Loaded OverlappingMarkerSpiderfier'); - var clusterStyle = [ - { - size: 42, - width: 5 - }, - { - size: 52, - width: 10 - }, - { - size: 62, - width: 15 - }, - { - size: 72, - width: 20 - } - ]; - var mcOptions = {maxZoom: MINIMAL_ZOOM - 1, minimumClusterSize: 1, styles: clusterStyle}; + var clusterStyle = [{ + size: 42, + width: 5 + }, { + size: 52, + width: 10 + }, { + size: 62, + width: 15 + }, { + size: 72, + width: 20 + }]; + var mcOptions = { + maxZoom: MINIMAL_ZOOM - 1, + minimumClusterSize: 1, + styles: clusterStyle + }; this.clusterer = new MarkerClusterer(this.map, [], mcOptions); console.log('Loaded MarkerClusterer'); - this.sidebar = new SidebarView({map: this.map}).render(); + this.sidebar = new SidebarView({ + map: this.map + }).render(); this.$el.find(".sidebar-container").append(this.sidebar.$el); console.log('Loaded SidebarView'); @@ -688,10 +692,12 @@ $(function () { this.previousZoom = this.map.zoom; this.router = new AppRouter(); - Backbone.history.start({pushState: true}); + Backbone.history.start({ + pushState: true + }); console.log('Loaded AppRouter'); - $('#toggle-sidebar').click(function () { + $('#toggle-sidebar').click(function() { $('.main').toggleClass('main-open').toggleClass('main-close'); $('.sidebar-container').toggleClass('sidebar-container-open').toggleClass('sidebar-container-close'); @@ -701,25 +707,25 @@ $(function () { }.bind(this)); this.isReady = true; - google.maps.event.addListener(this.map, "rightclick", _.bind(this.contextMenuMap, this) ); + google.maps.event.addListener(this.map, "rightclick", _.bind(this.contextMenuMap, this)); - google.maps.event.addListener(this.map, "idle", function(){ - if (!this.firstLoadDelay){ + google.maps.event.addListener(this.map, "idle", function() { + if (!this.firstLoadDelay) { this.fetchMarkers(); } - }.bind(this) ); - google.maps.event.addListener(this.map, "zoom_changed", function(){ + }.bind(this)); + google.maps.event.addListener(this.map, "zoom_changed", function() { this.indicatingAvailabilityOfIconsDotsSwitch(); }.bind(this)); - google.maps.event.addListener(this.map, "click", _.bind(this.clickMap, this) ); + google.maps.event.addListener(this.map, "click", _.bind(this.clickMap, this)); this.sidebar.setResponsively(); return this; }, - goToMyLocation: function () { + goToMyLocation: function() { if (typeof this.myLocation !== 'undefined') { this.setCenterWithMarker(this.myLocation); } else if (navigator.geolocation) { - navigator.geolocation.getCurrentPosition(function (position) { + navigator.geolocation.getCurrentPosition(function(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; this.myLocation = new google.maps.LatLng(latitude, longitude); @@ -732,33 +738,33 @@ $(function () { } this.map.setZoom(INIT_ZOOM); }, - closeInfoWindow: function () { + closeInfoWindow: function() { if (app.infoWindow) { this.selectedMarker = null; app.infoWindow.close(); app.infoWindow = null; this.updateUrl(); - $(document).off('keydown',app.ESCinfoWindow); + $(document).off('keydown', app.ESCinfoWindow); } app.map.gestureHandling = GESTURE_HANDLING; }, - clickMap: function (e) { + clickMap: function(e) { this.closeInfoWindow(); }, - trackDrag: function () { - google.maps.event.addListener(this.map, "mousemove", function () { + trackDrag: function() { + google.maps.event.addListener(this.map, "mousemove", function() { this.resetOnMouseUp = true; }); }, - initLayers: function (severity) { + initLayers: function(accident_severity) { var severities = [SEVERITY_IRRELEVANT_RSA, SEVERITY_FATAL, SEVERITY_SEVERE, SEVERITY_LIGHT]; var self = this; - severities.forEach(function (severity) { - var attr = SEVERITY_ATTRIBUTES[severity]; + severities.forEach(function(accident_severity) { + var attr = SEVERITY_ATTRIBUTES[accident_severity]; var layer = self.model.get(attr); if (!layer) { - self.model.set(attr, LAYERS[severity]); - layer = LAYERS[severity]; + self.model.set(attr, LAYERS[accident_severity]); + layer = LAYERS[accident_severity]; } }); }, @@ -774,12 +780,12 @@ $(function () { for (var i = 0; i < this.markerList.length; i++) { if (this.markerList[i].model.get("type") == model.get("type") && this.markerList[i].model.attributes.id == model.attributes.id) { - return i; + return i; } } return -1; }, - removeMarker: function (model) { + removeMarker: function(model) { var markerIndex = this.getMarkerIndex(model); if (markerIndex >= 0) { var marker = this.markerList[markerIndex]; @@ -788,59 +794,66 @@ $(function () { model.set("markerView", this.markerList.length); } }, - loadMarker: function (model) { + loadMarker: function(model) { var markerIndex = this.getMarkerIndex(model); if (markerIndex >= 0) { return; // avoid adding duplicates } // markers are loaded immediately as they are fetched - if (!this.fitsFilters(model)){ + if (!this.fitsFilters(model)) { console.log(model + " doesn't fit"); } if (this.clusterMode() || this.fitsFilters(model) || !this.clusterMode() && model.get("type") == MARKER_TYPE_DISCUSSION) { - var markerView = new MarkerView({model: model, map: this.map, markerIconType: this.markerIconType}).render(); + var markerView = new MarkerView({ + model: model, + map: this.map, + markerIconType: this.markerIconType + }).render(); model.set("markerView", this.markerList.length); this.markerList.push(markerView); } }, - loadCluster: function (model) { - var clusterExists = _.any(this.clusterList, function (cluster) { - return cluster.model.attributes.longitude === model.attributes.longitude - && cluster.model.attributes.latitude === model.attributes.latitude; + loadCluster: function(model) { + var clusterExists = _.any(this.clusterList, function(cluster) { + return cluster.model.attributes.longitude === model.attributes.longitude && + cluster.model.attributes.latitude === model.attributes.latitude; }); if (!clusterExists) { - var clusterView = new ClusterView({model: model, map: this.map}); - if (!this.heatMapMode){ + var clusterView = new ClusterView({ + model: model, + map: this.map + }); + if (!this.heatMapMode) { clusterView.render(); } this.clusterList.push(clusterView); } }, - loadClusters: function (model) { + loadClusters: function(model) { this.oms.unspiderfy(); this.clearClustersFromMap(); this.clusters.each(_.bind(this.loadCluster, this)); }, - fitsFilters: function (model) { - var layer = this.model.get(SEVERITY_ATTRIBUTES[model.get("severity")]); + fitsFilters: function(model) { + var layer = this.model.get(SEVERITY_ATTRIBUTES[model.get("accident_severity")]); if (!layer) { return false; } return true; }, - loadMarkers: function () { + loadMarkers: function() { this.oms.unspiderfy(); this.clearMarkersFromMap(); this.clearClustersFromMap(); this.markers.each(_.bind(this.loadMarker, this)); }, - clearMarkersFromMap: function () { + clearMarkersFromMap: function() { if (this.markerList) { - _(this.markerList).each(_.bind(function (marker) { + _(this.markerList).each(_.bind(function(marker) { marker.marker.setMap(null); }, this)); } @@ -848,19 +861,19 @@ $(function () { this.clusterer.clearMarkersFromMap(); this.clearClustersFromMap(); }, - clearClustersFromMap: function () { + clearClustersFromMap: function() { this.clusterer.removeClusters(); this.clusterList = []; }, - resetMarkers: function () { + resetMarkers: function() { this.clearMarkersFromMap(); this.markers.reset(); }, - resetClusters: function () { + resetClusters: function() { this.clearClustersFromMap(); this.clusters.reset(); }, - chooseMarker: function () { + chooseMarker: function() { if (!this.markerList.length) { return; } @@ -879,7 +892,7 @@ $(function () { markerView.choose(); this.model.set("currentMarker", null); }, - contextMenuMap : function(e) { + contextMenuMap: function(e) { this.clickLocation = e.latLng; @@ -888,23 +901,20 @@ $(function () { } this.menu = new ContextMenuView({ - items: [ - { - icon : "plus-sign", - text : ADD_DISCUSSION, - callback : _.bind(this.showDiscussion, this) - }, - { - icon : "plus-sign", - text : GET_LOCATION_UPDATES, - callback : _.bind(this.LocationSubscriptionDialog, this) - } - ], + items: [{ + icon: "plus-sign", + text: ADD_DISCUSSION, + callback: _.bind(this.showDiscussion, this) + }, { + icon: "plus-sign", + text: GET_LOCATION_UPDATES, + callback: _.bind(this.LocationSubscriptionDialog, this) + }], map: this.map, e: e - }); + }); }, - addDiscussionMarker : function() { // called once a comment is posted + addDiscussionMarker: function() { // called once a comment is posted var identifier = this.newDiscussionIdentifier; if (typeof identifier == 'undefined') return true; // marker already exists this.updateUrl(this.getDiscussionUrl(identifier)); @@ -914,16 +924,19 @@ $(function () { longitude: this.clickLocation.lng(), type: MARKER_TYPE_DISCUSSION }); - var view = new MarkerView({model: model, map: this.map}).render(); + var view = new MarkerView({ + model: model, + map: this.map + }).render(); $.post("discussion", JSON.stringify({ - "latitude" : model.get("latitude"), - "longitude" : model.get("longitude"), - "identifier": identifier, - "title" : identifier - })); + "latitude": model.get("latitude"), + "longitude": model.get("longitude"), + "identifier": identifier, + "title": identifier + })); return true; }, - showDiscussion : function(identifier) { // called when clicking add, or on marker + showDiscussion: function(identifier) { // called when clicking add, or on marker if (typeof identifier == 'undefined') { // new discussion from context menu identifier = this.clickLocation.toString(); // (lat, lon) this.newDiscussionIdentifier = identifier; @@ -937,28 +950,28 @@ $(function () { this.discussionShown = null; }.bind(this)); var url = window.location.protocol + "//" + window.location.host + - "/discussion?identifier=" + identifier; + "/discussion?identifier=" + identifier; DISQUS.reset({ reload: true, - config: function () { + config: function() { this.page.identifier = identifier; this.page.url = url; this.page.title = identifier; } }); }, - getDiscussionUrl: function (identifier) { + getDiscussionUrl: function(identifier) { return "/?discussion=" + identifier + "&" + app.getCurrentUrlParams(); }, - loginDialogLoad: function(){ + loginDialogLoad: function() { if (this.createDialog) this.createDialog.close(); this.createDialog = new LoginDialog().render(); }, - preferencesDialogLoad: function () { + preferencesDialogLoad: function() { if (this.createDialog) this.createDialog.close(); this.createDialog = new PreferencesDialog().render(); }, - featuresSubscriptionDialog : function(type, event) { + featuresSubscriptionDialog: function(type, event) { if (this.createDialog) this.createDialog.close(); this.createDialog = new FeatureDialog({ type: type, @@ -974,22 +987,22 @@ $(function () { markers: this.markers }).render(); }, - handleSearchBox: function () { + handleSearchBox: function() { var places = this.searchBox.getPlaces(); if (places && places.length > 0) { - var place = places[0]; - this.createHighlightPoint(place.geometry.location.lat(), place.geometry.location.lng(), HIGHLIGHT_TYPE_USER_SEARCH); - this.setCenterWithMarker(place.geometry.location); - this.map.setZoom(INIT_ZOOM); + var place = places[0]; + this.createHighlightPoint(place.geometry.location.lat(), place.geometry.location.lng(), HIGHLIGHT_TYPE_USER_SEARCH); + this.setCenterWithMarker(place.geometry.location); + this.map.setZoom(INIT_ZOOM); } }, - createHighlightPoint : function(lat, lng, highlightPointType) { + createHighlightPoint: function(lat, lng, highlightPointType) { if (isNaN(lat) || isNaN(lng) || isNaN(highlightPointType)) return; $.post("highlightpoints", JSON.stringify({ - "latitude": lat, - "longitude": lng, - "type": highlightPointType - })); + "latitude": lat, + "longitude": lng, + "type": highlightPointType + })); }, setCenterWithMarker: function(loc) { this.closeInfoWindow(); @@ -1000,19 +1013,18 @@ $(function () { } this.locationMarker = new google.maps.Marker({ - position: loc, - map: this.map, - icon: { + position: loc, + map: this.map, + icon: { path: google.maps.SymbolPath.CIRCLE, scale: 0, fillColor: 'black' - }, - title: 'מיקום נוכחי' + }, + title: 'מיקום נוכחי' }); - // agam add- tour find location for step 2 - if (tourLocation == 2) - { + // agam add- tour find location for step 2 + if (tourLocation == 2) { tourLocation = 3; var location = this.locationMarker; contentString = '

המיקום שחיפשתם יסומן באיקון הזה.
מסביבו תוכלו לראות אייקונים שמייצגים תאונות עם נפגעים.

'; @@ -1026,22 +1038,22 @@ $(function () { tourStyle(infowindow); } }, - getCurrentUrlParams: function () { + getCurrentUrlParams: function() { var params = this.buildMarkersParams(true); var returnParams = []; $.each(params, function(attr, attr_value) { returnParams.push(attr + "=" + attr_value); }); return returnParams.join("&"); - }, + }, ESCinfoWindow: function(event) { if (event.keyCode == 27) { app.closeInfoWindow(); console.log('ESC pressed'); } }, - retinaIconsResize : function(image_url){ - if (isRetina){ + retinaIconsResize: function(image_url) { + if (isRetina) { image_url = { url: image_url, scaledSize: new google.maps.Size(30, 50) @@ -1049,7 +1061,7 @@ $(function () { } return image_url; }, - toggleMarkerIconType: function(){ + toggleMarkerIconType: function() { this.markerIconType = !this.markerIconType; this.resetMarkers(); this.fetchMarkers(); @@ -1059,25 +1071,34 @@ $(function () { if ($("#checkbox-00-04").is(":checked")) { age_groups.push(1); - } if ($("#checkbox-05-09").is(":checked")) { + } + if ($("#checkbox-05-09").is(":checked")) { age_groups.push(2); - } if ($("#checkbox-10-14").is(":checked")) { + } + if ($("#checkbox-10-14").is(":checked")) { age_groups.push(3); - } if ($("#checkbox-15-19").is(":checked")) { + } + if ($("#checkbox-15-19").is(":checked")) { age_groups.push(4); - } if ($("#checkbox-20-24").is(":checked")) { + } + if ($("#checkbox-20-24").is(":checked")) { age_groups.push(5); - } if ($("#checkbox-25-69").is(":checked")) { - for (var i = 6; i <=14; ++i) { + } + if ($("#checkbox-25-69").is(":checked")) { + for (var i = 6; i <= 14; ++i) { age_groups.push(i); } - } if ($("#checkbox-70-74").is(":checked")) { + } + if ($("#checkbox-70-74").is(":checked")) { age_groups.push(15); - } if ($("#checkbox-75-79").is(":checked")) { + } + if ($("#checkbox-75-79").is(":checked")) { age_groups.push(16); - } if ($("#checkbox-80-84").is(":checked")) { + } + if ($("#checkbox-80-84").is(":checked")) { age_groups.push(17); - } if ($("#checkbox-85-plus").is(":checked")) { + } + if ($("#checkbox-85-plus").is(":checked")) { age_groups.push(18); } @@ -1093,14 +1114,48 @@ $(function () { }, loadFilter: function(eventAction, eventLabel) { ga('send', 'event', 'filters', eventAction, eventLabel); - if ($("#checkbox-discussions").is(":checked")) { this.show_discussions='1'; } else { this.show_discussions=''; } - if ($("#checkbox-accidents").is(":checked")) { this.show_markers='1'; this.show_accidents='1'; } else { this.show_accidents=''; } - if ($("#checkbox-rsa").is(":checked")) { this.show_markers='1'; this.show_rsa='1'; } else { this.show_rsa=''; } - if ($("#checkbox-accurate").is(":checked")) { this.accurate='1'; } else { this.accurate=''; } - if ($("#checkbox-approx").is(":checked")) { this.approx='1'; } else { this.approx=''; } - if ($("#checkbox-fatal").is(":checked")) { this.show_fatal='1'; } else { this.show_fatal=''; } - if ($("#checkbox-severe").is(":checked")) { this.show_severe='1'; } else { this.show_severe=''; } - if ($("#checkbox-light").is(":checked")) { this.show_light='1'; } else { this.show_light=''; } + if ($("#checkbox-discussions").is(":checked")) { + this.show_discussions = '1'; + } else { + this.show_discussions = ''; + } + if ($("#checkbox-accidents").is(":checked")) { + this.show_markers = '1'; + this.show_accidents = '1'; + } else { + this.show_accidents = ''; + } + if ($("#checkbox-rsa").is(":checked")) { + this.show_markers = '1'; + this.show_rsa = '1'; + } else { + this.show_rsa = ''; + } + if ($("#checkbox-accurate").is(":checked")) { + this.accurate = '1'; + } else { + this.accurate = ''; + } + if ($("#checkbox-approx").is(":checked")) { + this.approx = '1'; + } else { + this.approx = ''; + } + if ($("#checkbox-fatal").is(":checked")) { + this.show_fatal = '1'; + } else { + this.show_fatal = ''; + } + if ($("#checkbox-severe").is(":checked")) { + this.show_severe = '1'; + } else { + this.show_severe = ''; + } + if ($("#checkbox-light").is(":checked")) { + this.show_light = '1'; + } else { + this.show_light = ''; + } if ($("#checkbox-urban").is(":checked") && $("#checkbox-nonurban").is(":checked")) { this.show_urban = 3; @@ -1153,59 +1208,61 @@ $(function () { setAgeGroupFilter: function() { var age_groups_array = this.age_groups.toString().split(',').map(function(item) { return parseInt(item); - });; + });; if (age_groups_array.indexOf(1) !== -1) { $("#checkbox-00-04").prop("checked", true); - }else{ + } else { $("#checkbox-00-04").prop("checked", false); } if (age_groups_array.indexOf(2) !== -1) { $("#checkbox-05-09").prop("checked", true); - }else{ + } else { $("#checkbox-05-09").prop("checked", false); } if (age_groups_array.indexOf(3) !== -1) { $("#checkbox-10-14").prop("checked", true); - }else{ + } else { $("#checkbox-10-14").prop("checked", false); } if (age_groups_array.indexOf(4) !== -1) { $("#checkbox-15-19").prop("checked", true); - }else{ + } else { $("#checkbox-15-19").prop("checked", false); - } + } if (age_groups_array.indexOf(5) !== -1) { $("#checkbox-20-24").prop("checked", true); - }else{ + } else { $("#checkbox-20-24").prop("checked", false); - } - var ages25_69 = [6,7,8,9,10,11,12,13,14]; - var ages25_69_exist = age_groups_array.filter(function(val) { return ages25_69.indexOf(val) !== -1}).length > 0; + } + var ages25_69 = [6, 7, 8, 9, 10, 11, 12, 13, 14]; + var ages25_69_exist = age_groups_array.filter(function(val) { + return ages25_69.indexOf(val) !== -1 + }).length > 0; if (ages25_69_exist) { $("#checkbox-25-69").prop("checked", true); - }else{ + } else { $("#checkbox-25-69").prop("checked", false); } if (age_groups_array.indexOf(15) !== -1) { $("#checkbox-70-74").prop("checked", true); - }else{ + } else { $("#checkbox-70-74").prop("checked", false); - } + } if (age_groups_array.indexOf(16) !== -1) { $("#checkbox-75-79").prop("checked", true); - }else{ + } else { $("#checkbox-75-79").prop("checked", false); } if (age_groups_array.indexOf(17) !== -1) { $("#checkbox-80-84").prop("checked", true); - }else{ + } else { $("#checkbox-80-84").prop("checked", false); - } + } if (age_groups_array.indexOf(18) !== -1) { $("#checkbox-85-plus").prop("checked", true); - }else{ + } else { $("#checkbox-85-plus").prop("checked", false); - } + } }, loadFilterFromParameters: function() { var bool_atrs = {}; @@ -1218,48 +1275,48 @@ $(function () { bool_atrs["checkbox-severe"] = this.show_severe; bool_atrs["checkbox-light"] = this.show_light; - $.each(bool_atrs, function(attr, attr_value) { - $('#' + attr).prop("checked", attr_value == '1'); - }); + $.each(bool_atrs, function(attr, attr_value) { + $('#' + attr).prop("checked", attr_value == '1'); + }); - if (this.show_urban == 3){ + if (this.show_urban == 3) { $("#checkbox-urban").prop("checked", true); $("#checkbox-nonurban").prop("checked", true); - }else if( this.show_urban == 2){ + } else if (this.show_urban == 2) { $("#checkbox-urban").prop("checked", true); $("#checkbox-nonurban").prop("checked", false); - }else if( this.show_urban == 1){ + } else if (this.show_urban == 1) { $("#checkbox-nonurban").prop("checked", true); $("#checkbox-urban").prop("checked", false); - }else{ + } else { $("#checkbox-nonurban").prop("checked", false); $("#checkbox-urban").prop("checked", false); } - if (this.show_intersection == 3){ + if (this.show_intersection == 3) { $("#checkbox-intersection").prop("checked", true); $("#checkbox-nonintersection").prop("checked", true); - }else if( this.show_intersection == 2){ + } else if (this.show_intersection == 2) { $("#checkbox-intersection").prop("checked", true); $("#checkbox-nonintersection").prop("checked", false); - }else if( this.show_intersection == 1){ + } else if (this.show_intersection == 1) { $("#checkbox-nonintersection").prop("checked", true); $("#checkbox-intersection").prop("checked", false); - }else{ + } else { $("#checkbox-nonintersection").prop("checked", false); $("#checkbox-intersection").prop("checked", false); } - if (this.show_lane == 3){ + if (this.show_lane == 3) { $("#checkbox-multi-lane").prop("checked", true); $("#checkbox-one-lane").prop("checked", true); - }else if( this.show_lane == 2){ + } else if (this.show_lane == 2) { $("#checkbox-multi-lane").prop("checked", true); $("#checkbox-one-lane").prop("checked", false); - }else if( this.show_lane == 1){ + } else if (this.show_lane == 1) { $("#checkbox-one-lane").prop("checked", true); $("#checkbox-multi-lane").prop("checked", false); - }else{ + } else { $("#checkbox-one-lane").prop("checked", false); $("#checkbox-multi-lane").prop("checked", false); } @@ -1275,8 +1332,8 @@ $(function () { radio_attrs["case_type"] = this.case_type; $.each(radio_attrs, function(attr, attr_value) { - $("input[type='radio'][name='" + attr +"']").each(function() { - if($(this).val() == attr_value) { + $("input[type='radio'][name='" + attr + "']").each(function() { + if ($(this).val() == attr_value) { $(this).prop("checked", true); } }); @@ -1294,7 +1351,7 @@ $(function () { this.show_holiday = $("input[type='radio'][name='holiday']:checked").val(); this.show_time = $("input[type='radio'][name='time']:checked").val(); // TODO: only parses the hour int for now, need to apply the minutes too - if (!isNaN(parseInt($("#stime").val())) && !isNaN(parseInt($("#etime").val()))){ + if (!isNaN(parseInt($("#stime").val())) && !isNaN(parseInt($("#etime").val()))) { this.start_time = parseInt($("#stime").val()); this.end_time = parseInt($("#etime").val()); $("#checkbox-time-all").prop('checked', true); @@ -1309,20 +1366,20 @@ $(function () { $(".heat-map-control").toggleClass('heat-map-control-red'); // Indicating switch availability this.indicatingAvailabilityOfIconsDotsSwitch(); - if (this.heatMapMode){ + if (this.heatMapMode) { this.oms.unspiderfy(); - if (this.clusterMode()){ + if (this.clusterMode()) { // Clear clusters from map this.clusterer.removeClusters(); // Drawing the HeatMap for clusters this.buildHeatMap("clusters"); - }else{ + } else { this.clearMarkersFromMap(); // Drawing the HeatMap for markers this.buildHeatMap("markers"); } - }else{ + } else { this.heatmap.setMap(null); this.reloadMarkers(); } @@ -1332,24 +1389,27 @@ $(function () { var clusterItemsCounter = 0; var heatMapMaxIntensity = 3; - if (markersOrClusters == "markers"){ - _.each(this.markers.models, function(marker){ - latlngListForHeatMap.push(new google.maps.LatLng(marker.get('latitude'),marker.get('longitude'))); + if (markersOrClusters == "markers") { + _.each(this.markers.models, function(marker) { + latlngListForHeatMap.push(new google.maps.LatLng(marker.get('latitude'), marker.get('longitude'))); }); - }else if (markersOrClusters == "clusters"){ - _.each(this.clusterList, function(cluster){ - latlngListForHeatMap.push({ location: new google.maps.LatLng(cluster.model.get('latitude'),cluster.model.get('longitude')), weight: cluster.model.get('size') }); + } else if (markersOrClusters == "clusters") { + _.each(this.clusterList, function(cluster) { + latlngListForHeatMap.push({ + location: new google.maps.LatLng(cluster.model.get('latitude'), cluster.model.get('longitude')), + weight: cluster.model.get('size') + }); clusterItemsCounter += cluster.model.get('size'); }); - if (clusterItemsCounter < 1000){ + if (clusterItemsCounter < 1000) { heatMapMaxIntensity = 10; - } else if (clusterItemsCounter > 1000 && clusterItemsCounter < 2000){ + } else if (clusterItemsCounter > 1000 && clusterItemsCounter < 2000) { heatMapMaxIntensity = 30; - } else if(clusterItemsCounter > 2000 && clusterItemsCounter < 4000){ + } else if (clusterItemsCounter > 2000 && clusterItemsCounter < 4000) { heatMapMaxIntensity = 90; - } else if(clusterItemsCounter > 4000 && clusterItemsCounter < 6000){ + } else if (clusterItemsCounter > 4000 && clusterItemsCounter < 6000) { heatMapMaxIntensity = 150; - } else if(clusterItemsCounter > 6000){ + } else if (clusterItemsCounter > 6000) { heatMapMaxIntensity = 250; } } @@ -1367,10 +1427,15 @@ $(function () { }, updateFilterString: function() { if (!this.clusterMode()) { - var fatal = this.show_fatal, severe = this.show_severe, light = this.show_light, severityText = " בחומרה "; - var accurate = this.accurate, approx = this.approx, accuracyText = " בעיגון "; - - // Severity variables and strings + var fatal = this.show_fatal, + severe = this.show_severe, + light = this.show_light, + severityText = " בחומרה "; + var accurate = this.accurate, + approx = this.approx, + accuracyText = " בעיגון "; + + // accident_severity variables and strings if (fatal == '1') { fatal = "קטלנית "; } else { @@ -1428,9 +1493,9 @@ $(function () { .append("" + accurate + "") .append("" + approx + "
") .append(" בין התאריכים
") - .append(""+ - moment(this.dateRanges[0]).format('LL') + " עד " + - moment(this.dateRanges[1]).format('LL') +"
") + .append("" + + moment(this.dateRanges[0]).format('LL') + " עד " + + moment(this.dateRanges[1]).format('LL') + "
") ; } else { @@ -1439,7 +1504,7 @@ $(function () { } }, indicatingAvailabilityOfIconsDotsSwitch: function() { - if (this.heatMapMode || this.clusterMode()){ + if (this.heatMapMode || this.clusterMode()) { // Indicating that the icons/dots switch is disabled $(".map-button.toggle-control").addClass("toggle-control-disabled"); $(".map-button.toggle-control")[0].title = 'שינוי תצוגת אייקונים אינו זמין במצב זה'; @@ -1452,4 +1517,3 @@ $(function () { } }); }); - diff --git a/static/js/constants.js b/static/js/constants.js index a043be133..fd251686b 100644 --- a/static/js/constants.js +++ b/static/js/constants.js @@ -104,13 +104,13 @@ ACCIDENT_MINOR_TYPE_TO_TYPE[ACCIDENT_TYPE_UNITED_HATZALA] = ACCIDENT_TYPE_UNITED var DEFAULT_ICON = ICONS[1][1]; -function getIcon(accidentType, severity) { +function getIcon(accident_type, accident_severity) { var icon = DEFAULT_ICON; try { - if (accidentType == "multiple") { - icon = MULTIPLE_ICONS[severity]; + if (accident_type == "multiple") { + icon = MULTIPLE_ICONS[accident_severity]; } else { - icon = ICONS[severity][ACCIDENT_MINOR_TYPE_TO_TYPE[accidentType]]; + icon = ICONS[accident_severity][ACCIDENT_MINOR_TYPE_TO_TYPE[accident_type]]; } } catch (err) { // stick to default icon @@ -142,7 +142,7 @@ SEVERITY_MAP[SEVERITY_SEVERE] = 'קשה'; SEVERITY_MAP[SEVERITY_LIGHT] = 'קלה'; SEVERITY_MAP[SEVERITY_IRRELEVANT_RSA] = 'אירוע'; -var SUBTYPE_STRING = [ +var ACCIDENT_TYPE_STRING = [ "פגיעה בהולך רגל", "התנגשות חזית אל צד", "התנגשות חזית באחור", diff --git a/static/js/marker.js b/static/js/marker.js index 8003b6667..669ca997d 100644 --- a/static/js/marker.js +++ b/static/js/marker.js @@ -84,13 +84,13 @@ var MarkerView = Backbone.View.extend({ this.$el.find(".title").text(this.marker.get("title")); this.$el.find(".id").text(fields.ACC_ID + ": " + this.marker.get("id")); this.$el.find(".provider_code").text(fields.PROVIDER_CODE + ": " + this.model.get("provider_code")); - this.$el.find(".roadType").text(fields.SUG_DEREH + ": " + localization.SUG_DEREH[this.model.get("roadType")]); - this.$el.find(".accidentType").text(fields.SUG_TEUNA + ": " + localization.SUG_TEUNA[this.model.get("subtype")]); - this.$el.find(".roadShape").text(fields.ZURAT_DEREH + ": " + localization.ZURAT_DEREH[this.model.get("roadShape")]); + this.$el.find(".road_type").text(fields.SUG_DEREH + ": " + localization.SUG_DEREH[this.model.get("road_type")]); + this.$el.find(".accident_type").text(fields.SUG_TEUNA + ": " + localization.SUG_TEUNA[this.model.get("accident_type")]); + this.$el.find(".road_shape").text(fields.ZURAT_DEREH + ": " + localization.ZURAT_DEREH[this.model.get("road_shape")]); this.$el.find(".severityText").text(fields.HUMRAT_TEUNA + ": " + localization.HUMRAT_TEUNA[this.model.get("severity")]); - this.$el.find(".dayType").text(fields.SUG_YOM + ": " + localization.SUG_YOM[this.model.get("dayType")]); + this.$el.find(".day_type").text(fields.SUG_YOM + ": " + localization.SUG_YOM[this.model.get("day_type")]); this.$el.find(".igun").text(fields.STATUS_IGUN + ": " + localization.STATUS_IGUN[this.model.get("locationAccuracy")]); - this.$el.find(".unit").text(fields.YEHIDA + ": " + localization.YEHIDA[this.model.get("unit")]); + this.$el.find(".police_unit").text(fields.YEHIDA + ": " + localization.YEHIDA[this.model.get("police_unit")]); this.$el.find(".mainStreet").text(this.model.get("mainStreet")); this.$el.find(".secondaryStreet").text(this.model.get("secondaryStreet")); this.$el.find(".junction").text(this.model.get("junction")); @@ -98,7 +98,7 @@ var MarkerView = Backbone.View.extend({ this.localize("HAD_MASLUL", "one_lane"); this.localize("RAV_MASLUL", "multi_lane"); this.localize("MEHIRUT_MUTERET", "speed_limit"); - this.localize("TKINUT", "intactness"); + this.localize("TKINUT", "road_intactness"); this.localize("ROHAV", "road_width"); this.localize("SIMUN_TIMRUR", "road_sign"); this.localize("TEURA", "road_light"); @@ -164,8 +164,8 @@ var MarkerView = Backbone.View.extend({ } else { markerTitle = "ביום " + moment(this.model.get("created")).format("dddd") + ", ה-" + moment(this.model.get("created")).format("LL") + - " אירעה תאונה " + SEVERITY_MAP[this.model.get("severity")] + - " מסוג " + localization.SUG_TEUNA[this.model.get("subtype")] + " " + + " אירעה תאונה " + SEVERITY_MAP[this.model.get("accident_severity")] + + " מסוג " + localization.SUG_TEUNA[this.model.get("accident_type")] + " " + loc; } break; @@ -291,7 +291,7 @@ var MarkerView = Backbone.View.extend({ name: this.model.get("title"), link: document.location.href, description: this.model.get("description"), - caption: SUBTYPE_STRING[this.model.get("subtype")] + caption: ACCIDENT_TYPE_STRING[this.model.get("accident_type")] // picture }); }, diff --git a/static/js/sidebar.js b/static/js/sidebar.js index 4ac1684b2..d5e42ba99 100644 --- a/static/js/sidebar.js +++ b/static/js/sidebar.js @@ -3,9 +3,9 @@ var markerCount = 0; var SidebarView = Backbone.View.extend({ className: "info-window", events: { - "click .current-view li" : "clickEntry", - "mouseover .current-view li" : "mouseOverEntry", - "mouseout .current-view li" : "mouseOutEntry", + "click .current-view li": "clickEntry", + "mouseover .current-view li": "mouseOverEntry", + "mouseout .current-view li": "mouseOutEntry", }, initialize: function(options) { this.map = options.map; @@ -39,11 +39,11 @@ var SidebarView = Backbone.View.extend({ var markerView = markerList[i]; var marker = markerView.marker; //take off all selections on current view update - if(markerView.isSelected()){ + if (markerView.isSelected()) { markerView.unselect(); } - if (bounds.contains(marker.getPosition()) ){ + if (bounds.contains(marker.getPosition())) { var markerModel = markerView.model; if (markerModel.get("type") == MARKER_TYPE_DISCUSSION) { continue; @@ -59,7 +59,7 @@ var SidebarView = Backbone.View.extend({ } else { var entryHtml = this.sidebarItemTemplate({ created: moment(markerModel.get("created")).format("LLLL"), - type: localization.SUG_TEUNA[markerModel.get("subtype")], + type: localization.SUG_TEUNA[markerModel.get("accident_type")], icon: markerView.getTitle("single"), }); } @@ -84,7 +84,7 @@ var SidebarView = Backbone.View.extend({ }, clickEntry: function(e) { var marker = this.getMarker(e); - if(marker){ + if (marker) { marker.view.choose(); } }, @@ -101,15 +101,15 @@ var SidebarView = Backbone.View.extend({ var currentView = this.$el.find(".current-view"); $(currentView).css("top", currentViewTop); }, - mouseOverEntry: function(e){ + mouseOverEntry: function(e) { var markerOfEntry = this.getMarker(e); - if(markerOfEntry){ + if (markerOfEntry) { markerOfEntry.view.select(); } }, - mouseOutEntry: function(e){ + mouseOutEntry: function(e) { var markerOfEntry = this.getMarker(e); - if(markerOfEntry){ + if (markerOfEntry) { markerOfEntry.view.unselect(); } }, diff --git a/static/js/statPanel.js b/static/js/statPanel.js index 85e5f2c1f..e49aa7130 100644 --- a/static/js/statPanel.js +++ b/static/js/statPanel.js @@ -62,9 +62,9 @@ var startJSPanelWithChart = function(jsPanel, widthOfPanel, heightOfPanel, chart return; } - if (currentTypeOfChart === "accidentsBySexAndAge"){ + if (currentTypeOfChart === "accidentsBySexAndAge") { $('#selectTypeOfData').hide(); - }else{ + } else { $('#selectTypeOfData').show(); } @@ -296,7 +296,7 @@ var startJSPanelWithChart = function(jsPanel, widthOfPanel, heightOfPanel, chart case "severityTotal": var sum; var jsonAccidentsBySeverity; - var groupedAccidentsBySeverity = _.countBy(app.markers.pluck("severity"), function(item) { + var groupedAccidentsBySeverity = _.countBy(app.markers.pluck("accident_severity"), function(item) { return item; }); @@ -306,14 +306,14 @@ var startJSPanelWithChart = function(jsPanel, widthOfPanel, heightOfPanel, chart }, 0); jsonAccidentsBySeverity = _.map(groupedAccidentsBySeverity, function(numOfAccidents, severity) { return { - "label": severity, + "label": accident_severity, "value": (numOfAccidents / sum).toFixed(2) }; }); } else { jsonAccidentsBySeverity = _.map(groupedAccidentsBySeverity, function(numOfAccidents, severity) { return { - "label": severity, + "label": accident_severity, "value": numOfAccidents.toString() }; }); @@ -636,20 +636,23 @@ var startJSPanelWithChart = function(jsPanel, widthOfPanel, heightOfPanel, chart params["fetch_markers"] = ''; params["fetch_vehicles"] = ''; params["fetch_involved"] = '1'; - $.get("charts-data", params, function(data){ + $.get("charts-data", params, function(data) { var involved = data.involved; var age_groups = {}; var dataset = []; for (var i = 0; i < involved.length; i++) { - if (age_groups[involved[i].age_group]){ + if (age_groups[involved[i].age_group]) { age_groups[involved[i].age_group]++; - }else{ + } else { age_groups[involved[i].age_group] = 1; } } for (var key in age_groups) { if (age_groups.hasOwnProperty(key)) { - dataset.push({ label: key, value: age_groups[key] }); + dataset.push({ + label: key, + value: age_groups[key] + }); } } FusionCharts.ready(function() { @@ -680,34 +683,36 @@ var startJSPanelWithChart = function(jsPanel, widthOfPanel, heightOfPanel, chart params["fetch_markers"] = ''; params["fetch_vehicles"] = ''; params["fetch_involved"] = '1'; - $.get("charts-data", params, function(data){ + $.get("charts-data", params, function(data) { var involved = data.involved; var age_groups = {}; var dataset = []; var males = []; var females = []; var keys = []; - var categories = { category: [] }; + var categories = { + category: [] + }; for (var i = 0; i < involved.length; i++) { - if (age_groups[involved[i].age_group]){ - if (involved[i].sex === 1){ - if (age_groups[involved[i].age_group].male){ + if (age_groups[involved[i].age_group]) { + if (involved[i].sex === 1) { + if (age_groups[involved[i].age_group].male) { age_groups[involved[i].age_group].male++; - }else{ + } else { age_groups[involved[i].age_group].male = 1; } - }else if (involved[i].sex === 2){ - if (age_groups[involved[i].age_group].female){ + } else if (involved[i].sex === 2) { + if (age_groups[involved[i].age_group].female) { age_groups[involved[i].age_group].female++; - }else{ + } else { age_groups[involved[i].age_group].female = 1; } } - }else{ + } else { age_groups[involved[i].age_group] = {}; - if (involved[i].sex === 1){ + if (involved[i].sex === 1) { age_groups[involved[i].age_group].male = 1; - }else if (involved[i].sex === 2){ + } else if (involved[i].sex === 2) { age_groups[involved[i].age_group].female = 1; } } @@ -719,20 +724,36 @@ var startJSPanelWithChart = function(jsPanel, widthOfPanel, heightOfPanel, chart } keys.sort(); for (var i = 0; i < keys.length; i++) { - categories.category.push({ label: keys[i]}); - if (age_groups[keys[i]].male){ - males.push({ value: age_groups[keys[i]].male.toString() }); - }else{ - males.push({ value: '0' }); - } - if (age_groups[keys[i]].female){ - females.push({ value: age_groups[keys[i]].female.toString() }); - }else{ - females.push({ value: '0' }); - } + categories.category.push({ + label: keys[i] + }); + if (age_groups[keys[i]].male) { + males.push({ + value: age_groups[keys[i]].male.toString() + }); + } else { + males.push({ + value: '0' + }); + } + if (age_groups[keys[i]].female) { + females.push({ + value: age_groups[keys[i]].female.toString() + }); + } else { + females.push({ + value: '0' + }); + } } - dataset.push({ seriesname: 'זכר', data: males}); - dataset.push({ seriesname: 'נקבה', data: females}); + dataset.push({ + seriesname: 'זכר', + data: males + }); + dataset.push({ + seriesname: 'נקבה', + data: females + }); FusionCharts.ready(function() { var statChart = new FusionCharts({ "type": 'mscolumn2d', @@ -833,4 +854,4 @@ $("body").on("jspanelclosed", function closeHandler(event, id) { // close handlers attached to body should be removed again //$("body").off("jspanelclosed", closeHandler); } -}); \ No newline at end of file +}); diff --git a/templates/index.html b/templates/index.html index e3b01964e..69501e9a5 100644 --- a/templates/index.html +++ b/templates/index.html @@ -357,7 +357,7 @@

-

+

@@ -368,12 +368,12 @@

-

-

+

+

-

+

@@ -389,7 +389,7 @@

-

+

@@ -414,7 +414,7 @@

-

+

@@ -647,11 +647,11 @@
חומרה:
- + - + - +