{% extends "page.html" %} {% load staticfiles tethys_gizmos %} {% block styles %} {{ block.super }} {% endblock %} {% block bodytag %}data-spy="scroll" data-target="#showcase_nav_list" style="position: relative;"{% endblock %} {% block primary_content %}
{# Navigation ----------------------------------------------------------------------------------------------------#}
{# end col #} {# Content -------------------------------------------------------------------------------------------------------#}

Gizmo Showcase

Gizmos are building blocks that can be used to create beautiful interactive controls for web apps. Using gizmos, developers can add date-pickers, plots, and maps to their templates with minimal coding. This page provides the documentation developers need to user Gizmos.

{# Quick Start -------------------------------------------------------------------------------------------------#}

Quick Start

What does "minimal coding" mean? Take a look at the following example. Let's say you want to include a date picker in your template using a gizmo. First, create a dictionary with all the configuration options for the date picker (more on that later) in your view/controller for the template and add it to the context:

def my_view(request):
    date_picker_options = {'display_text': 'Date',
                           'name': 'date1',
                           'autoclose': True,
                           'format': 'MM d, yyyy',
                           'start_date': '2/15/2014',
                           'start_view': 'decade',
                           'today_button': True,
                           'initial': 'February 15, 2014'}

    context = {'date_picker_options': date_picker_options}

    return render(request, 'path/to/my/template.html', context)

Next, open the template you intend to add the gizmo to and load the tethys_gizmos library. Be sure to do this somewhere nearthe top of your template—before any gizmo occurances. This only needs to be done once for each template that uses gizmos.

{% templatetag openblock %} load tethys_gizmos {% templatetag closeblock %}

Now, use the gizmo tag to insert the date picker anywhere in your template. Pass the name of the gizmo and the options dictionary that you passed to the template from your view as arguments:

{% templatetag openblock %} gizmo date_picker date_picker_options {% templatetag closeblock %}

Finally, at the end of your template—after all of the gizmo tags—insert the gizmo_dependencies tag. This only needs to be done once for each template that uses gizmos.

{% templatetag openblock %} gizmo_dependencies {% templatetag closeblock %}

All together your template may look something like this:

{% templatetag openblock %} load tethys_gizmos {% templatetag closeblock %}
<html>
    <head>
        ...
    </head>
    <body>
        ...
        {% templatetag openblock %} gizmo date_picker date_picker_options {% templatetag closeblock %}
        ...
        {% templatetag openblock %} gizmo_dependencies {% templatetag closeblock %}
    </body>
</html>

How it Works

Gizmos are composed of HTML, JavaScript, and CSS. When the template is rendered, each of the gizmo tags are replaced by the HTML that is needed to render the gizmo. All gizmos accept a Python dictionary with options for configuring the gizmo. The options for each gizmo are documented on this page.

The JavaScript and CSS dependencies are loaded into the template at the location of the gizmo_dependencies tag. Note that the gizmo_dependencies tag must be called after all of the gizmo tags otherwise some of the dependencies may not be loaded properly.

Optionally, the gizmo_dependencies tag can be called with either js or css to load only the JavaScript or only the CSS dependencies, respectively. The rule that this tag must be called after all gizmo tags still applies. The gizmo_dependencies must be called twice (once for each option) when this feature is used.

{% templatetag openblock %} gizmo_dependencies js {% templatetag closeblock %}
{% templatetag openblock %} gizmo_dependencies css {% templatetag closeblock %}

The tethys_gizmos library must be loaded at the top of the template to provide the gizmo and gizmo_dependencies template tags.

{# Button Group ------------------------------------------------------------------------------------------------#}

Button Group

The button group gizmo can be used to generate a single button or a group of buttons. Groups of buttons can be stacked horizontally or vertically. For a single button, specify a button group with one button. This gizmo is a wrapper for Twitter Bootstrap buttons.

{% gizmo button_group single_button %} {% gizmo button_group horizontal_buttons %} {% gizmo button_group vertical_buttons %}

Controller


single_button = {'buttons': [
                             {'display_text': 'Click Me',
                              'name': 'click_me_name',
                              'attributes': 'onclick=alert(this.name);',
                              'type': 'submit'}
                             ]}

horizontal_buttons = {'buttons': [
                {'display_text': 'Add',
                                 'icon': 'glyphicon glyphicon-plus',
                                 'style': 'success'},
                                {'display_text': 'Delete',
                                 'icon': 'glyphicon glyphicon-trash',
                                 'disabled': True,
                                 'style': 'danger'}
                                ]}

vertical_buttons = {'buttons': [
                               {'display_text': 'Edit',
                                'icon': 'glyphicon glyphicon-wrench',
                                'style': 'warning',
                                'attributes':'id=edit_button'},
                               {'display_text': 'Info',
                                'icon': 'glyphicon glyphicon-question-sign',
                                'style': 'info',
                                'attributes': 'name=info'},
                               {'display_text': 'Apps',
                                'icon': 'glyphicon glyphicon-home',
                                'href': '/apps',
                                'style': 'primary'}
                               ],
                   'vertical': True}

HTML


{% gizmo button_group.html single_button %}
{% gizmo button_group.html horizontal_buttons %}
{% gizmo button_group.html vertical_buttons %}

Button Group Options

Name Type Default Description
buttons list required A list of dictionaries where each dictionary contains the options for a button (see Button Options table below)
vertical boolean False Set to true to have button group stack vertically

Button Options

Name Type Default Description
display_text string None Display text that appears on the button
name string None Name of the input element that will be used for form submission
style string None Name of the input element that will be used for form submission
icon string None Name of a valid Twitter Bootstrap icon class (see the Bootstrap glyphicon reference)
href string None Link for anchor type buttons
attributes string None Use this to add any additional attributes to the html element
submit boolean False Set this to true to make the button a submit type button for forms
disabled boolean False Set the disabled state
{# Date Picker -------------------------------------------------------------------------------------------------#}

Date Picker

Date pickers are used to make the input of dates streamlined and easy. Rather than typing the date, the user is presented with a calendar to select the date. This date picker was implemented using Bootstrap Datepicker.

{% gizmo date_picker date_picker %} {% gizmo date_picker date_picker_error %}

Controller


date_picker = {'display_text': 'Date',
               'name': 'date1',
               'autoclose': True,
               'format': 'MM d, yyyy',
               'start_date': '2/15/2014',
               'start_view': 'decade',
               'today_button': True,
               'initial': 'February 15, 2014'}

date_picker_error = {'display_text': 'Date',
                     'name': 'date2',
                     'initial': '10/2/2013',
                     'disabled': True,
                     'error': 'Here is my error text'}

HTML


{% gizmo date_picker date_picker %}
{% gizmo date_picker date_picker_error %}

Date Picker Options

Name Type Default Description
display_text string None Display text for the label that accompanies date picker
name string required Name of the input element that will be used for form submission
autoclose boolean False Set whether datepicker auto closes when a date is selected
calendar_weeks boolean False Set whether calendar week numbers are shown on the left of the datepicker
clear_button boolean False Set whether the clear button is displayed or not
days_of_week_disabled string '' Days of the week that are disabled 0-6 with 0 being Sunday and 6 being Saturday. Multiple days are comma separated (e.g.: '0,6')
end_date date string end of time Last date that can be selected. All other dates after this date are shown as disabled.
format string 'dd/mm/yy' String reprensenting date format. For valid see Bootstrap Datepicker documentation here.
min_view_mode string, number 'days' Set the minimum view mode. Possible values are 'days' or 0, 'months' or 1, 'years' or 2
multidate number 1 Enables multiselection of dates up to the number given
start_date string beginning of time First date that can be selected. All other dates before this date are shown as disabled
start_view string, number 'month' View the date picker starts on. Valid vlaues include 'month' or 0, 'year' or 1, and 'decade' or 2
today_button boolean False Set whether a today button is displayed or not
today_highlight boolean False Wet whether to highlight the current date
week_start number 0 Set the day the week starts on 0-6, where 0 is Sunday and 6 is Saturday.
initial string None Initial date to appear in date picker
disabled boolean False Disabled state of the date picker
error string None Error message for form validation
{# Range Slider ------------------------------------------------------------------------------------------------#}

Range Slider

Sliders can be used to request an input value from a range of possible values. A slider is configured with a dictionary of key-value options. The table below summarizes the options for sliders.

{% gizmo range_slider slider1 %} {% gizmo range_slider slider2 %}

Controller


slider1 = {'display_text': 'Slider 1',
           'name': 'slider1',
           'min': 0,
           'max': 100,
           'initial': 50,
           'step': 1}
slider2 = {'display_text': 'Slider 2',
           'name': 'slider2',
           'min': 0,
           'max': 1,
           'initial': 0.5,
           'step': 0.1,
           'disabled': True,
           'error': 'Incorrect, please choose another value.'}

HTML


{% gizmo range_slider slider1 %}
{% gizmo range_slider slider2 %}

Slider Options

Name Type Default Description
display_text string None Display text for the label that accompanies slider
name string required Name of the input element that will be used on form submission
min numeric required Minimum value of range
max numeric required Maximum value of range
initial numeric required Initial value of slider
step numeric required Increment between values in range
disabled boolean False Disabled state of the slider
error string None Error message for form validation
{# Select Input ------------------------------------------------------------------------------------------------#}

Select Input

Select inputs are used to select values from an given set of values. Use this gizmo to create select inputs and multi select inputs. This uses the Select2 functionality.

{% gizmo select_input select_input2 %} {% gizmo select_input select_input2_multiple %} {% gizmo select_input select_input_multiple %} {% gizmo select_input select_input2_error %}

Controller


select_input2 = {'display_text': 'Select2',
                'name': 'select1',
                'multiple': False,
                'options': [('One', '1'), ('Two', '2'), ('Three', '3')],
                'initial': ['Two']}

select_input2_multiple = {'display_text': 'Select2 Multiple',
                         'name': 'select2',
                         'multiple': True,
                         'options': [('One', '1'), ('Two', '2'), ('Three', '3')]}

select_input_multiple = {'display_text': 'Select Multiple',
                         'name': 'select2.1',
                         'multiple': True ,
                         'original':True,
                         'options': [('One', '1'), ('Two', '2'), ('Three', '3')]}

select_input2_error = {'display_text': 'Select2 Disabled',
                      'name': 'select3',
                      'multiple': False,
                      'options': [('One', '1'), ('Two', '2'), ('Three', '3')],
                      'disabled': True,
                      'error': 'Here is my error text'}

HTML


{% gizmo select_input select_input2 %}
{% gizmo select_input select_input2_multiple %}
{% gizmo select_input select_input_multiple %}
{% gizmo select_input select_input2_error %}

Select Input Options

Name Type Default Description
display_text string None Display text for the label that accompanies select input
name string required Name of the input element that will be used for form submission
multiple boolean False If True, select input will be a multi-select.
original boolean False If True, Select2 functionality will be turned off.
options list None List of tuples that represent the options and values of the select input
disabled boolean False Disabled state of the select input
error string None Error message for form validation
{# Text Input --------------------------------------------------------------------------------------------------#}

Text Input

The text input gizmo makes it easy to add text inputs to your app that are styled similarly to the other input snippets.

{% gizmo text_input text_input %} {% gizmo text_input text_error_input %}

Controller


text_input = {'display_text': 'Text',
              'name': 'inputAmount',
              'placeholder': 'e.g.: 10.00',
              'prepend': '$'}

text_error_input = {'display_text': 'Text Error',
                    'name': 'inputEmail',
                    'initial': 'bob@example.com',
                    'disabled': True,
                    'icon_append':'glyphicon glyphicon-envelope',
                    'error': 'Here is my error text'}

HTML


{% gizmo text_input text_input %}
{% gizmo text_input text_error_input %}
    

Text Input Options

Name Type Default Description
display_text string None Display text for the label that accompanies select input
name string required Name of the input element that will be used for form submission
initial string None The initial text that that will appear in the text input when it loads
placeholder string None Placeholder text is static text that displayed in the input when it is empty
prepend string None Text that is prepended to the text input
append string None Text that is appended to the text input
icon_prepend string None The name of a valid Bootstrap v2.3 icon. The icon will be prepended to the input.
icon_append string None The name of a valid Bootstrap v2.3 icon. The icon will be appended to the input.
disabled boolean False Disabled state of the select input
error string None Error message for form validation
{# Toggle Switch -----------------------------------------------------------------------------------------------#}

Toggle Switch

Toggle switches can be used as an alternative to check boxes for boolean or binomial input. Toggle switches are implemented using the excellent Bootstrap Switch project.

{% gizmo toggle_switch toggle_switch %} {% gizmo toggle_switch toggle_switch_styled %} {% gizmo toggle_switch toggle_switch_disabled %}

Controller


toggle_switch = {'display_text': 'Defualt Toggle',
                 'name': 'toggle1'}

toggle_switch_styled = {'display_text': 'Styled Toggle',
                        'name': 'toggle2',
                        'on_label': 'Yes',
                        'off_label': 'No',
                        'on_style': 'success',
                        'off_style': 'danger',
                        'initial': True,
                        'size': 'large'}

toggle_switch_disabled = {'display_text': 'Disabled Toggle',
                          'name': 'toggle3',
                          'on_label': 'On',
                          'off_label': 'Off',
                          'on_style': 'success',
                          'off_style': 'warning',
                          'size': 'mini',
                          'initial': False,
                          'disabled': True,
                          'error': 'Here is my error text'}

HTML


{% gizmo toggle_switch toggle_switch %}
{% gizmo toggle_switch toggle_switch_styled %}
{% gizmo toggle_switch toggle_switch_disabled %}

Toggle Switch Options

Name Type Default Description
display_text string None Display text for the label that accompanies switch
name string required Name of the input element that will be used for form submission
on_label string 'ON' Text that appears in the "on" position of the switch
off_label string 'OFF' Text that appears in the "off" position of the switch
on_style string 'primary' Color of the "on" position. Either: 'default', 'info', 'primary', 'success', 'warning', or 'danger'
off_style string 'default' Color of the "off" position. Either: 'default', 'info', 'primary', 'success', 'warning', or 'danger'
size string 'regular' Size of the switch. Either: 'large', 'small', or 'mini'.
initial boolean False The initial position of the switch (True for "on" and False for "off")
disabled boolean False Disabled state of the switch
error string None Error message for form validation
{# Table View --------------------------------------------------------------------------------------------------#}

Table View

Table views can be used to display tabular data. The table view gizmo can be configured to have columns that are editable. When used in this capacity, embed the table view in a form with a submit button.

{% gizmo table_view table_view %} {% gizmo table_view table_view_edit %}

Controller


table_view = {'column_names': ('Name', 'Age', 'Job'),
              'rows': [('Bill', 30, 'contractor'),
                       ('Fred', 18, 'programmer'),
                       ('Bob', 26, 'boss')],
              'hover': True,
              'striped': True,
              'bordered': False,
              'condensed': False}
                
table_view_edit = {'column_names': ('Name', 'Age', 'Job'),
                   'rows': [('Bill', 30, 'contractor'),
                            ('Fred', 18, 'programmer'),
                            ('Bob', 26, 'boss')],
                   'hover': True,
                   'striped': True,
                   'bordered': False,
                   'condensed': False,
                   'editable_columns': (False, 'ageInput', 'jobInput'),
                   'row_ids': [21, 25, 31]}

HTML


{% gizmo table_view table_view %}
{% gizmo table_view table_view_edit %}

Table View Options

Name Type Default Description
column names tuple/list None A tuple or list of strings that represent the table columns names.
rows tuple/list required A list/tuple of lists/tuples representing each row in the table.
hover boolean False Illuminate rows on hover (does not work on striped tables)
striped boolean False Stripe rows
bordered boolean False Add borders and rounded corners
condensed boolean False A tigher packed table
editable_columns list/tuple None A list or tuple with an entry for each column in the table. The entry is either False for non-editable columns or a string that will be used to create identifiers for the input fields in that column.
row_ids list/tuple None A list or tuple of ids for each row in the table. These will be combined with the string in the editable_columns parameter to create unique identifiers for eacy input field in the table. If not specified, each row will be assigned an integer value.
{# Plot View ---------------------------------------------------------------------------------------------------#}

Plot View

Plot views can be used to generate interactive plots of tabular data. All of the plots available through this gizmo are powered by the Highcharts JavaScript library.

{% gizmo highcharts_plot_view line_plot_view %}

Controller


highcharts_object = {
    'chart': {
          'type': 'spline'
      },
      'title': {
          'text': 'Plot Title'
      },
      'subtitle': {
          'text': 'Plot Subtitle'
      },
      'legend': {
          'layout': 'vertical',
          'align': 'right',
          'verticalAlign': 'middle',
          'borderWidth': 0
      },
      'xAxis': {
          'title': {
              'enabled': True,
              'text': 'Altitude (km)'
          },
          'labels': {
              'formatter': 'function () { return this.value + " km"; }'
          }
      },
      'yAxis': {
          'title': {
              'enabled': True,
              'text': 'Temperature (*C)'
          },
          'labels': {
              'formatter': 'function () { return this.value + " *C"; }'
          }
      },
      'tooltip': {
          'headerFormat': '{series.name}
', 'pointFormat': '{point.x} km: {point.y}*C' }, 'series': [{ 'name': 'Air Temp', 'color': '#0066ff', 'dashStyle': 'ShortDash', 'marker' : {'enabled': False}, 'data': [[0, 5], [10, -70], [20, -86.5], [30, -66.5], [40, -32.1], [50, -12.5], [60, -47.7], [70, -85.7], [80, -106.5]] },{ 'name': 'Water Temp', 'color': '#ff6600', 'data': [[0, 15], [10, -50], [20, -56.5], [30, -46.5], [40, -22.1], [50, -2.5], [60, -27.7], [70, -55.7], [80, -76.5]]} ]} line_plot_view = {'highcharts_object': highcharts_object, 'width': '500px', 'height': '500px'}

HTML


{% gizmo highcharts_plot_view line_plot_view %}
{% gizmo highcharts_plot_view web_plot %}

Controller


# Web/polar chart example                   
web_plot_object = {
      'chart': {
            'polar': True,
            'type': 'line'
        },
        'title': {
            'text': 'Polar Chart'
        },
        'pane': {
            'size': '80%'
        },
        'xAxis': {
            'categories': ['Infiltration', 'Soil Moisture', 'Precipitation',
                     'Evaporation', 'Roughness', 'Runoff',
                     'Permeability', 'Vegetation'],
            'tickmarkPlacement': 'on',
            'lineWidth': 0
        },
        'yAxis': {
            'gridLineInterpolation': 'polygon',
            'lineWidth': 0,
            'min': 0
        },
        'series': [{
            'name': 'Park City',
            'data': [0.2, 0.5, 0.1, 0.8, 0.2, 0.6, 0.8, 0.3],
            'pointPlacement': 'on'
        }, {
            'name': 'Little Dell',
            'data': [0.8, 0.3, 0.2, 0.5, 0.1, 0.8, 0.2, 0.6],
            'pointPlacement': 'on'
        }
        ]}

web_plot = {'highcharts_object': web_plot_object,
              'width': '500px',
              'height': '500px'}                  
          

HTML


{% gizmo highcharts_plot_view web_plot %}
{% gizmo highcharts_plot_view timeseries_plot %}

Controller


# Timeseries plot example            
timeseries_plot_object = {
    'chart': {
        'type': 'area',
        'zoomType': 'x'
    },
    'title': {
        'text': 'Irregular Timeseries Plot'
    },
    'xAxis': {
        'maxZoom': 30 * 24 * 3600000, # 30 days in milliseconds
        'type': 'datetime'
    },
    'yAxis': {
        'title': {
            'text': 'Snow depth (m)'
        },
        'min': 0
    },
    'legend': {
        'layout': 'vertical',
        'align': 'right',
        'verticalAlign': 'top',
        'x': -350,
        'y': 125,
        'floating': True,
        'borderWidth': 1,
        'backgroundColor': '#FFFFFF'
    },
    'series': [{
        'name': 'Winter 2007-2008',
        'data': [
            [datetime(2008, 12,  2), 0.8 ],
            [datetime(2008, 12,  9), 0.6 ],
            [datetime(2008, 12, 16), 0.6 ],
            [datetime(2008, 12, 28), 0.67],
            [datetime(2009,  1,  1), 0.81],
            [datetime(2009,  1,  8), 0.78],
            [datetime(2009,  1, 12), 0.98],
            [datetime(2009,  1, 27), 1.84],
            [datetime(2009,  2, 10), 1.80],
            [datetime(2009,  2, 18), 1.80],
            [datetime(2009,  2, 24), 1.92],
            [datetime(2009,  3,  4), 2.49],
            [datetime(2009,  3, 11), 2.79],
            [datetime(2009,  3, 15), 2.73],
            [datetime(2009,  3, 25), 2.61],
            [datetime(2009,  4,  2), 2.76],
            [datetime(2009,  4,  6), 2.82],
            [datetime(2009,  4, 13), 2.8 ],
            [datetime(2009,  5,  3), 2.1 ],
            [datetime(2009,  5, 26), 1.1 ],
            [datetime(2009,  6,  9), 0.25],
            [datetime(2009,  6, 12), 0   ]
        ]
    }]
}

timeseries_plot = {'highcharts_object': timeseries_plot_object,
                     'width': '500px',
                     'height': '500px'}                  
          

HTML


{% gizmo highcharts_plot_view timeseries_plot %}

Plot View Options

Name Type Default Description
highcharts_object PySON required The highcharts_object contains the definition of the chart. The full Highcharts API is supported via this object. The object can either be a JavaScript string or a JavaScript-equivilent Python data structure. The latter is recommended.

Implementation Notes

Plots are configured using the highcharts_object parameter. This parameter allows developers to specify any valid option from the Highcharts JavaScript API in equivilent Python data structures. There are a few notable differences:

  • The Python equivilent of JavaScript objects are dictionaries. However, the keys for Python dictionaries must be strings.
  • Python datetime objects (see the timeseries plot example above).
  • Some Highcharts API parameters require JavaScript functions to be passed in (e.g.: axis scale labels). To accomplish this in Python, pass a string representing the equivilent JavaScript function definition. These function definitions must be anonymous (no name). An example of this is shown in the line plot example above.
  • Be sure to use the Python syntax for Booleans (True instead of true).

The recommended strategy for creating plots using the Highcharts Plot View is to find a similar example from the Highcharts demos page. Use the Edit in jsFiddle link to see the source code. Note that the JavaScript and CSS imports are automatically handled by the gizmo. Use the JavaScript source of the example to construct the equivilent in Python, following the guidelines discussed in the previous paragraphs.

{# Message Box -------------------------------------------------------------------------------------------------#}

Message Box

Message box gizmos can be used to display messages to users. These are especially useful for alerts and warning messages. The message box gizmo is implemented using Twitter Bootstrap's modal.

Show Message Box {% gizmo message_box message_box %}

Controller


message_box = {'name': 'sampleModal',
               'title': 'Message Box Title',
               'message': 'Congratulations! This is a message box',
               'dismiss_button': 'Nevermind',
               'affirmative_button': 'Proceed',
               'width': 500,
               'affirmative_attributes': 'href=javascript:void(0);'}

HTML


<!-- Trigger Button -->
<a href="#{{ message_box.name }}" class="btn btn-success" data-toggle="modal">
  Show Message Box
</a>

<!-- Message Box -->
{% gizmo message_box message_box %}

Message Box Options

Name Type Default Description
name string required Unique name for the message box
title string required Title that appears at the top of the message box
message string ' ' Message that will appear in the main body of the message box
dismiss_button string 'Cancel' Title for the dismiss button (a.k.a.: the "Cancel" button)
affirmative_button string 'Ok' Title for the affirmative action button (a.k.a.: the "OK" button)
affirmative_attributes string None Use this to place any html attributes on the affirmative button. (e.g.: 'href="/action" onclick="doSomething();"')
width numeric 560 The width of the message box in pixels
{# Google Map --------------------------------------------------------------------------------------------------#}

Google Map

This gizmo can be used to generate map views of spatial data. By default the data will be shown using Google Earth (3D globe). However, Google Earth requires a browser plugin that is not supported on all operating systems or browsers. For systems that don't support the Google Earth plugin, a Google Maps map (2D map) will be generated instead. Note that the link to the data must be publicly accessible to be shown on a Google Map

NOTE: Do not create more than one map on a page at any given time.

ALSO NOTE: Only Google Earth is able to show KML animations. If the map reverts to Google Maps, animations will not be shown properly.

Demo cannot be shown on this page because of the demo for the editable google map. Click on button below for live demo.

Live Demo

Controller


google_map = {'height': '500px',
                'width': '100%',
                'kml_service': '/apps/my-app/get-kml',
                'maps_api_key':'S0mEaPIk3y'}

KML Service Controller


from django.http import JsonResponse

def get_kml(request):
    """
    This action is used to pass the kml data to the google map.
    It must return a JSON response with a Python dictionary that
    has the key 'kml_links'.
    """
    kml_links = ['http://www.example.com/soil-poly-v3.kml',
                 'http://www.example.com/ele-poly-terrain.kml']

    return JsonResponse({'kml_links': kml_links})
            

HTML


{% gizmo google_map google_map %}

Google Map Options

Name Type Default Description
height string '400px' Height of the map element. Any valid css unit of length.
width string '400px' Width of the map element. Any valid css unit of length.
kml_service string ' ' Url for a web service that will return kml data. Call is made to this service asyncronously to prevent the UI from locking up while map data is being retieved. This service must return JSON object with a 'kml_links' property that contains an array of urls to publicly accessible kml files.
maps_api_key string ' ' For the Google Maps backup map to be enabled, an API key for Google Maps must be provided. If the API key is provided in the settings.py via the TETHYS_GIZMOS_GOOGLE_MAPS_API_KEY option, this parameter is not required.

Settings

The Map View gizmo uses the Google Maps v3 API as an alternative when the Google Earth Plugin is not supported. The Google Maps API requires an API key to use. This can be set either through the 'maps_api_key' parameter of the gizmos option or it can be set globally in the settings.py file. To set the API key globally, add this parameter to your settings.py:

TETHYS_GIZMOS_GOOGLE_MAPS_API_KEY = 'S0m3@piK3Y'

If you do not provide the API key globally, developers will need to provide their own API keys via the 'maps_api_key' option for the gizmo.

{# Map View ----------------------------------------------------------------------------------------------------#}

Map View

This gizmo can be used to generate map views of spatial data. By default the data will be shown using Google Earth (3D globe). However, Google Earth requires a browser plugin that is not supported in all operating systems or browsers. For systems that don't support the Google Earth plugin, a Google Maps map (2D map) will be generated instead. Note that the link to the data must be publicly accessible to be shown on a Google Map

NOTE: Do not create more than one map on a page at any given time.

Demo cannot be shown on this page because of the demo for the editable google map. Click on button below for live demo.

Live Demo

Controller


google_map = {'height': '500px',
                'width': '100%',
                'kml_service': '/apps/my-app/get-kml',
                'maps_api_key':'S0mEaPIk3y'}

KML Service Controller


from django.http import JsonResponse

def get_kml(request):
    """
    This action is used to pass the kml data to the google map.
    It must return a JSON response with a Python dictionary that
    has the key 'kml_links'.
    """
    kml_links = ['http://www.example.com/soil-poly-v3.kml',
                 'http://www.example.com/ele-poly-terrain.kml']

    return JsonResponse({'kml_links': kml_links})
              

HTML


{% gizmo google_map google_map %}

Google Map Options

Name Type Default Description
height string '400px' Height of the map element. Any valid css unit of length.
width string '400px' Width of the map element. Any valid css unit of length.
kml_service string ' ' Url for a web service that will return kml data. Call is made to this service asyncronously to prevent the UI from locking up while map data is being retieved. This service must return JSON object with a 'kml_links' property that contains an array of urls to publicly accessible kml files.
maps_api_key string ' ' For the Google Maps backup map to be enabled, an API key for Google Maps must be provided. If the API key is provided in the settings.py via the TETHYS_GIZMOS_GOOGLE_MAPS_API_KEY option, this parameter is not required.

Settings

The Map View gizmo uses the Google Maps v3 API as an alternative when the Google Earth Plugin is not supported. The Google Maps API requires an API key to use. This can be set either through the 'maps_api_key' parameter of the gizmos option or it can be set globally in the settings.py file. To set the API key globally, add this parameter to your settings.py:

TETHYS_GIZMOS_GOOGLE_MAPS_API_KEY = 'S0m3@piK3Y'

If you do not provide the API key globally, developers will need to provide their own API keys via the 'maps_api_key' option for the gizmo.

{# Editable Google Map -----------------------------------------------------------------------------------------#}

Editable Google Map

The editable map gizmo uses Google Maps 3 with the drawing library enabled to allow geospatial user input. An optional background dataset can be specified for reference. Only the shapes drawn by the user are returned (see Retrieving Shapes section).

NOTE: Do not create more than one map on a page at any given time.

Click here for demo on a separate page.

{% if flash_message %}
JSON:

{{ flash_message }}

{% endif %}
{% csrf_token %} {% gizmo editable_google_map editable_google_map %}

Controller


editable_map = {'height': '600px',
                  'width': '100%',
                 'reference_kml_action': '/apps/my-app/get-kml',
                  'maps_api_key': 'S0mEaPIk3y',
                  'drawing_types_enabled': ['POLYGONS', 'POINTS', 'POLYLINES'],
                  'initial_drawing_mode': 'POINTS',
                  'output_format': 'WKT'}
            

KML Service Controller


from django.http import JsonResponse

def get_kml(request):
    """
    This action is used to pass the kml data to the google map.
    It must return a JSON response with a Python dictionary that
    has the key 'kml_links'.
    """
    kml_links = ['http://www.example.com/soil-poly-v3.kml',
                 'http://www.example.com/ele-poly-terrain.kml']

    return JsonResponse({'kml_links': kml_links})
            

HTML


{% gizmo editable_google_map editable_map %}
            

Google Editable Map Options

Name Type Default Description
height string required Height of map container in normal css units
width string required Width of map container in normal css units
maps_api_key string required The Google Maps API key. If the API key is provided in the settings.py via the TETHYS_GIZMOS_GOOGLE_MAPS_API_KEY option, this parameter is not required.
reference_kml_action url string " " The action that returns the background kml datasets. These datasets are used for reference only.
drawing_types_enabled list of strings [ ] A list of the types of geometries the user will be allowed to draw (POLYGONS, POINTS, POLYLINES).
initial_drawing_mode string " " A string representing the drawing mode that will be enbabled by default. Valid modes are: 'POLYGONS', 'POINTS', 'POLYLINES'. The mode used must be one of the drawing_types_enabled that the user is allowed to draw.
output_format string "GEOJSON" A string speicifying the format of the string that is output by the editable map tool. Valid values are 'GEOJSON' for GeoJSON format or 'WKT' for Well Known Text Format.
input_overlays PySON None A JavaScript-equivilent Python data structure representing GeoJSON or WktJSON containing the geometry and attributes to be added to the map as overlays (see example below). Only points, lines and polygons are supported.

Controller


GeoJSON


geo_json = {'type':'WKTGeometryCollection',
            'geometries':[
                          {'type':'Point',
                           'wkt':'POINT(-111.5123462677002 40.629197012613545)',
                           'properties':{'id':1,'value':1}
                           },
                          {'type':'Polygon',
                           'wkt':'POLYGON((-111.50153160095215 40.63193284946615, -111.50101661682129 40.617210120505035, -111.48625373840332 40.623594711231775, -111.49123191833496 40.63193284946615, -111.50153160095215 40.63193284946615))',
                           'properties':{'id':2,'value':2}
                           },
                          {'type':'PolyLine',#
                           'wkt':'POLYLINE(-111.49123191833496 40.65003865742191, -111.49088859558105 40.635319920747456, -111.48127555847168 40.64912697157757, -111.48024559020996 40.634668574229735)',
                           'properties':{'id':3,'value':3}
                           }
                          ]
            }

editable_google_map = {'height': '700px',
                         'width': '100%',
                         'maps_api_key': 'S0mEaPIk3y',
                         'drawing_types_enabled': ['POLYGONS', 'POINTS', 'POLYLINES'],
                         'initial_drawing_mode': 'POINTS',
                         'input_overlays': geo_json}

WktJSON


wkt_json = {"type":"GeometryCollection",
            "geometries":[
                          {"type":"Point",
                           "coordinates":[40.629197012613545,-111.5123462677002],
                           "properties":{"id":1,"value":1}},
                          {"type":"Polygon",
                           "coordinates":[[40.63193284946615,-111.50153160095215],[40.617210120505035,-111.50101661682129],[40.623594711231775,-111.48625373840332],[40.63193284946615,-111.49123191833496]],
                           "properties":{"id":2,"value":2}},
                          {"type":"LineString",
                           "coordinates":[[40.65003865742191,-111.49123191833496],[40.635319920747456,-111.49088859558105],[40.64912697157757,-111.48127555847168],[40.634668574229735,-111.48024559020996]],
                           "properties":{"id":3,"value":3}}
                          ]
            }

editable_google_map = {'height': '700px',
                         'width': '100%',
                         'maps_api_key': 'S0mEaPIk3y',
                         'drawing_types_enabled': ['POLYGONS', 'POINTS', 'POLYLINES'],
                         'initial_drawing_mode': 'POINTS',
                         'input_overlays': wkt_json}

Settings

The Google Editable Map uses the Google Maps v3 API, which requires an API key to use. This can be set either through the 'maps_api_key' parameter of the gizmos option or it can be set globally in the settings.py file. To set the API key globally, add this parameter to your settings.py:

TETHYS_GIZMOS_GOOGLE_MAPS_API_KEY = 'S0m3@piK3Y'

If you do not provide the API key globally, developers will need to provide their own API keys via the 'maps_api_key' option for the gizmo.

Retrieving Shapes

The shapes can be retrieved from the map in two ways. A hidden text field named 'geometry' is updated evertime the map is changed. The text in the text field is a string representation of JSON. The geometry can be formatted as either GeoJSON or Well Known Text. This can be configured by setting the output_format parameter. If the editable map is embedded in a form, the geometry that is drawn on the map will automatically be submitted with the rest of the form via the hidden text field.

Alternatively, the data can be extracted directly using the JavaScript API (see below).

Editable Map JavaScript API

For advanced features, the JavaScript API can be used to interact with the editable map. If you need capabilities beyond the scope of this API, we recommend using the Google Maps version 3 API to create your own map.

TETHYS_EDIT_MAP.getGeoJson()

This method returns the GeoJSON object representing all of the overlays on the map.

TETHYS_EDIT_MAP.getGeoJsonString()

This method returns a stringified GeoJSON object representing all of the overlays on the map.

TETHYS_EDIT_MAP.getWktJson()

This method returns a Well Known Text JSON object representing all of the overlays on the map.

TETHYS_EDIT_MAP.getWktJsonString()

This method returns a stringified Well Known Text JSON object representing all of the overlays on the map.

TETHYS_EDIT_MAP.swapKmlService(kml_service)

Use this method to swap out the current reference kml layers for new ones.

  • kml_service (string) = url that returns a JSON object with a property called 'kml_link' that is an array of publicly accessible urls to kml or kmz documents
TETHYS_EDIT_MAP.swapOverlayService(overlay_service, clear_overlays)

Use this method to add new overlays to the map dynaically without reloading the page.

  • overlay_service (string) = url that returns a JSON object with a property called 'overlay_json' that has a value of a WKT or GeoJSON object in the same format as is used for input_overlays (see above)
  • clear_overlays (boolean) = if true, will clear all overlays from the map prior to adding the new overlays. Otherwise all overlays will be retained.
{# Fetch Climate -----------------------------------------------------------------------------------------------#}

FetchClimate

This gizmo can be used to get climate data based off of a bounding box over an area or a point. It is based off of Microsoft Research. See the FetchClimate page for more info.

NOTE: Do not create more than one map on a page at any given time.

Fetchclimate With Map

Demo cannot be shown on this page because of the demo for the editable google map. Click on button below for live demo.

Live Demo

Controller


  fetchclimate_with_map_plot = {
                'serverUrl':'http://fetchclimate2.cloudapp.net',
                'variables': {
                  'prate':[423,432,426,424],
                  'elev':[]
                },
                'map': {
                  'css' : {'height': '600px',
                            'width': '100%',},
                  'map_data' : {
                    'api_key': 'S0mEaPIk3y',
                    'drawing_types_enabled': ['RECTANGLE', 'POINTS'],
                    'initial_drawing_mode': 'RECTANGLE',
                    'max_num_grids': 2
                  }
                },
                'plot' : {
                  'dimensions' : {'height': 350, 'width': 500}
                }
              }
  

HTML


  {% gizmo fetchclimate fetchclimate_with_map_plot %}
  

Fetchclimate With Javascript API Output

{% gizmo fetchclimate fetchclimate_array %}

Controller


  fetchclimate_array = {
                  'serverUrl':'http://fetchclimate2.cloudapp.net',
                  'variables': {
                    'prate':[423,432,426,424],
                    'elev':[]
                  },
                  'grid' : {
                    'name' : 'Provo Canyon Watershed',
                    'boundingBox' : [40.308836,40.381579,-111.654462,-111.550778],
                    'gridResolution':[25,25]
                  },
                  'point' : {
                    'name' : 'Clyde Building'
                    'location':[40.246942,-111.647971]
                  }
                }
  

HTML


  {% gizmo fetchclimate fetchclimate_array %}
  

FetchClimate Options

URL Parameter
Name Type Default Description
serverUrl string 'http://fetchclimate2.cloudapp.net' The URL to the FetchClimate server (e.g 'serverUrl':'http://fetchclimate2.cloudapp.net')
Map Parameters

Optional if grid or point included. Otherwise, required!

Name Type Default Description
css dictionary {} Custom css elements. FORMAT:{'css-element-name': 'css-value'}. If no width or height included, 500px X 500px assumed.
map_data dictionary {} Data needed to create the map.
Map Parameters - map_data
Name Type Default Description
api_key string '' API key for Google maps.
drawing_types_enabled string array ['RECTANGLE'] A list of the types of geometries the user will be allowed to draw. Valid types are: RECTANGLE, and POINTS. (e.g.: drawing_types_enabled=['RECTANGLE', 'POINTS'])
initial_drawing_mode string array 'RECTANGLE' A string representing the drawing mode that will be enbabled by default. Valid modes are: 'RECTANGLE', 'POINTS'. The mode used must be one of the drawing_types_enabled that the user is allowed to draw.
max_num_grids integer unlimited The maximum number of grids allowed for the user. Default is unlimited. (e.g 'max_num_grids':0).
max_num_points integer unlimited The maximum number of points allowed for the user. Default is unlimited. (e.g 'max_num_points':0).
Plot Parameters
Name Type Default Description
dimensions dictionary -> 'string': {'string':integer, 'string':integer} width - 100%, height - 500px The integer is in pixels for width (Highcharts width reference) or height (Highcharts height reference). Not required to be defined.
Variable Parameters

To find out which variables you can use and their parameters, go to your service url with '/api/configuration' at the end. (e.g. http://fetchclimate2.cloudapp.net/api/configuration). Look in "EnvironmentalVariables" for the variable names. Then, to find the data source ID's of sources available, go to "DataSources".

Name Type Default Description
variables dictionary -> 'string': [integer, integer, etc..] 'precip': [] Must have variable defined. It is in the fomat {'variable_name' : [variable_id,variable_id,variable_id]}.
Grid Parameters

Optional if there is a map or point included. Otherwise, it is required! No map needed. If map included, it will intitialize with input grid.

Name Type Default Description
title string '' The name of the grid area.
boundingBox array [] An array of length 4 with bounding lat and lons. e.g. [min lat, max lat, min lon, max lon].
gridResolution array [] An array of length 2. Number of grid cells in lat and lon directions. e.g.[lat resolution,lon resolution].
Point Parameters

Optional if there is a map or grid included. Otherwise, it is required! No map needed. If map included, it will intitialize with input point.

Name Type Default Description
title string '' The name of the point location.
location array [] An array of length 2 with lat and lon of point. e.g. [lat, lon].

Fetchclimate JavaScript API

This is available if you use the plot feature. To use it, replace all 'date' or 'DATE' in the names with 'plot' or 'PLOT' (except for 'fcDataRequestComplete' or 'fcOneDataRequestComplete').

For advanced features, the JavaScript API can be used to get the data once the request is complete.

FETCHCLIMATE_DATA.getAllData()

ONCE THE AJAX CALLS ARE COMPLETE - This method returns an object with the initial key level as the variable names and the next level as the grid/point names with the data inside of the grid name key. However, if the AJAX calls are not complete, it returns -1.

How to know when the AJAX calls are complete? - The Event Listener

When ALL requests are complete - 'e.detail' contains all of the data returned from the AJAX calls (see below).

The Entire Request Complete Event Listener


jQuery('#fetchclimate_data')[0].addEventListener('fcDataRequestComplete', function(e) {
    console.log(e.detail);
});
          

When ONE of the requests is complete - 'e.detail' contains all of the data returned from the AJAX calls (see below).

The Single Request Complete Event Listener


jQuery('#fetchclimate_data')[0].addEventListener('fcOneDataRequestComplete', function(e) {
    console.log(e.detail);
});
          
{# end col #}
{# end gizmo-showcase-wrapper #} {% endblock %} {% block scripts %} {% gizmo_dependencies css %} {{ block.super }} {% gizmo_dependencies js %} {% endblock %}