Map View

class tethys_sdk.gizmos.MapView(height='100%', width='100%', basemap=None, view={'center': [-100, 40], 'zoom': 2}, controls=[], layers=[], draw=None, legend=False, attributes={}, classes='', disable_basemap=False, feature_selection=None)

The Map View gizmo can be used to produce interactive maps of spatial data. It is powered by OpenLayers, a free and open source pure javascript mapping library. It supports layers in a variety of different formats including WMS, Tiled WMS, GeoJSON, KML, and ArcGIS REST. It includes drawing capabilities and the ability to create a legend for the layers included in the map.

Shapes that are drawn on the map by users can be retrieved from the map via a hidden text field named 'geometry' and it is updated every time the map is changed. The text in the text field is a string representation of JSON. The geometry definition contained in this JSON can be formatted as either GeoJSON or Well Known Text. This can be configured via the output_format option of the MVDraw object. If the Map View 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.

height

Height of the map element. Any valid css unit of length (e.g.: '500px'). Defaults to '520px'.

Type

str

width

Width of the map element. Any valid css unit of length (e.g.: '100%'). Defaults to '100%'.

Type

str

basemap

The base maps to display: choose from OpenStreetMap, MapQuest, or a Bing map. Valid values for the string option are: 'OpenStreetMap' and 'MapQuest'. If you wish to configure the base map with options, you must use the dictionary form. The dictionary form is required to use a Bing map, because an API key must be passed as an option. See below for more detail. A basemap switcher will automatically be provided if a list of more than one basemap is included.

Type

str, dict or a list of strings and/or dicts

view

An MVView object specifying the initial view or extent for the map.

Type

MVView

controls

A list of controls to add to the map. The list can be a list of strings or a list of dictionaries. Valid controls are ZoomSlider, Rotate, FullScreen, ScaleLine, ZoomToExtent, and 'MousePosition'. See below for more detail.

Type

list

layers

A list of MVLayer objects.

Type

list

draw

An MVDraw object specifying the drawing options.

Type

MVDraw

disable_basemap

Render the map without a base map.

Type

bool

feature_selection

A dictionary of global feature selection options. See below.

Type

bool

attributes

A dictionary representing additional HTML attributes to add to the primary element (e.g. {"onclick": "run_me();"}).

Type

dict

classes

Additional classes to add to the primary HTML element (e.g. "example-class another-class").

Type

str

Options Dictionaries

Many of the options above will accept dictionaries with additional options. These dictionaries should be structured with a single key that is the name of the original option with a value of another dictionary containing the additional options. For example, to provide additional options for the 'ZoomToExtent' control, you would create a dictionary with key 'ZoomToExtent' and value of a dictionary with the additional options like this:

{'ZoomToExtent': {'projection': 'EPSG:4326', 'extent': [-135, 22, -55, 54]}}

Most of the additional options correspond with the options objects in the OpenLayers API. The following sections provide links to the OpenLayers objects that you can refer to when selecting the options.

Base Maps

There are several base maps supported by the Map View gizmo: OpenStreetMap, Bing, Stamen, CartoDB, and ESRI. All base maps can be specified as a string or as an options dictionary. When using an options dictionary all base maps map services accept the option control_label, which is used to specify the label to be used in the Base Map control. For example:

{'Bing': {'key': 'Ap|k3yheRE', 'imagerySet': 'Aerial', 'control_label': 'Bing Aerial'}}

For additional options that can be provided to each base map service see the following links:

Note

The CartoDB and ESRI services are just pre-defined instances of the XYZ service. In addition to the standard XYZ options they have the following additional options:

CartoDB:
  • style: The style of map. Possibilities are 'light' or 'dark'.

  • labels: Boolean specifying whether or not to include labels.

ESRI:
  • layer: A string specifying which ESRI map to use. Possibilities are:
    • NatGeo_World_Map

    • Ocean_Basemap

    • USA_Topo_Maps

    • World_Imagery

    • World_Physical_Map

    • World_Shaded_Relief

    • World_Street_Map

    • World_Terrain_Base

    • World_Topo_Map

Controls

Use the following links to learn about options for the different controls:

Feature Selection

The feature_selection dictionary contains global settings that can be used to modify the behavior of the feature selection functionality. An explanation of valid options follows:

  • multiselect: Set to True to allow multiple features to be selected while holding the shift key on the keyboard. Defaults to False.

  • sensitivity: Integer value that adjust the feature selection sensitivity. Defaults to 2.

Tip

OpenLayers Version

Currently, OpenLayers version 5.3.0 is used by default with the Map View gizmo. If you need a specific version of OpenLayers you can specify the version number using the ol_version class attribute on the MapView class:

MapView.ol_version = '4.6.5'

Any versions that are provided by https://www.jsdelivr.com/package/npm/openlayers can be specified.

Controller Example

from tethys_sdk.gizmos import MapView, MVDraw, MVView, MVLayer, MVLegendClass

# Define view options
view_options = MVView(
    projection='EPSG:4326',
    center=[-100, 40],
    zoom=3.5,
    maxZoom=18,
    minZoom=2
)

# Define drawing options
drawing_options = MVDraw(
    controls=['Modify', 'Delete', 'Move', 'Point', 'LineString', 'Polygon', 'Box'],
    initial='Point',
    output_format='WKT'
)

# Define GeoJSON layer
geojson_object = {
  'type': 'FeatureCollection',
  'crs': {
    'type': 'name',
    'properties': {
      'name': 'EPSG:3857'
    }
  },
  'features': [
    {
      'type': 'Feature',
      'geometry': {
        'type': 'Point',
        'coordinates': [0, 0]
      }
    },
    {
      'type': 'Feature',
      'geometry': {
        'type': 'LineString',
        'coordinates': [[4e6, -2e6], [8e6, 2e6]]
      }
    },
    {
      'type': 'Feature',
      'geometry': {
        'type': 'Polygon',
        'coordinates': [[[-5e6, -1e6], [-4e6, 1e6], [-3e6, -1e6]]]
      }
    }
  ]
}

# Define GeoJSON point layer
geojson_point_object = {
  'type': 'FeatureCollection',
  'crs': {
    'type': 'name',
    'properties': {
      'name': 'EPSG:3857'
    }
  },
  'features': [
    {
      'type': 'Feature',
      'geometry': {
        'type': 'Point',
        'coordinates': [0, 0]
      }
    },
  ]
}

style = {'ol.style.Style': {
    'stroke': {'ol.style.Stroke': {
        'color': 'blue',
        'width': 2
    }},
    'fill': {'ol.style.Fill': {
        'color': 'green'
    }},
    'image': {'ol.style.Circle': {
        'radius': 10,
        'fill': None,
        'stroke': {'ol.style.Stroke': {
            'color': 'red',
            'width': 2
        }}
    }}
}}

geojson_layer = MVLayer(
    source='GeoJSON',
    options=geojson_object,
    layer_options={'style': style},
    legend_title='Test GeoJSON',
    legend_extent=[-46.7, -48.5, 74, 59],
    legend_classes=[
        MVLegendClass('polygon', 'Polygons', fill='green', stroke='blue'),
        MVLegendClass('line', 'Lines', stroke='blue')
    ]
)

geojson_point_layer = MVLayer(
    source='GeoJSON',
    options=geojson_point_object,
    legend_title='Test GeoJSON',
    legend_extent=[-46.7, -48.5, 74, 59],
    legend_classes=[
        MVLegendClass('line', 'Lines', stroke='#3d9dcd')
    ],
)

# Define GeoServer Layer
geoserver_layer = MVLayer(
    source='ImageWMS',
    options={'url': 'http://192.168.59.103:8181/geoserver/wms',
           'params': {'LAYERS': 'topp:states'},
           'serverType': 'geoserver'},
    legend_title='USA Population',
    legend_extent=[-126, 24.5, -66.2, 49],
    legend_classes=[
        MVLegendClass('polygon', 'Low Density', fill='#00ff00', stroke='#000000'),
        MVLegendClass('polygon', 'Medium Density', fill='#ff0000', stroke='#000000'),
        MVLegendClass('polygon', 'High Density', fill='#0000ff', stroke='#000000')
    ]
)

# Define KML Layer
kml_layer = MVLayer(
    source='KML',
    options={'url': '/static/tethys_gizmos/data/model.kml'},
    legend_title='Park City Watershed',
    legend_extent=[-111.60, 40.57, -111.43, 40.70],
    legend_classes=[
        MVLegendClass('polygon', 'Watershed Boundary', fill='#ff8000'),
        MVLegendClass('line', 'Stream Network', stroke='#0000ff'),
    ]
)

# Tiled ArcGIS REST Layer
arc_gis_layer = MVLayer(
    source='TileArcGISRest',
    options={'url': 'http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' + 'Specialty/ESRI_StateCityHighway_USA/MapServer'},
    legend_title='ESRI USA Highway',
    legend_extent=[-173, 17, -65, 72]
)

# Define base map options
esri_layer_names = [
    'NatGeo_World_Map',
    'Ocean_Basemap',
    'USA_Topo_Maps',
    'World_Imagery',
    'World_Physical_Map',
    'World_Shaded_Relief',
    'World_Street_Map',
    'World_Terrain_Base',
    'World_Topo_Map',
]
esri_layers = [{'ESRI': {'layer': l}} for l in esri_layer_names]
basemaps = [
    'Stamen',
    {'Stamen': {'layer': 'toner', 'control_label': 'Black and White'}},
    {'Stamen': {'layer': 'watercolor'}},
    'OpenStreetMap',
    'CartoDB',
    {'CartoDB': {'style': 'dark'}},
    {'CartoDB': {'style': 'light', 'labels': False, 'control_label': 'CartoDB-light-no-labels'}},
    {'XYZ': {'url': 'https://maps.wikimedia.org/osm-intl/{z}/{x}/{y}.png', 'control_label': 'Wikimedia'}}
    'ESRI',
]
basemaps.extend(esri_layers)

# Specify OpenLayers version
MapView.ol_version = '5.3.0'

# Define map view options
map_view_options = MapView(
        height='600px',
        width='100%',
        controls=['ZoomSlider', 'Rotate', 'FullScreen',
                  {'MousePosition': {'projection': 'EPSG:4326'}},
                  {'ZoomToExtent': {'projection': 'EPSG:4326', 'extent': [-130, 22, -65, 54]}}],
        layers=[geojson_layer, geojson_point_layer, geoserver_layer, kml_layer, arc_gis_layer],
        view=view_options,
        basemap=basemaps,
        draw=drawing_options,
        legend=True
)

context = {'map_view_options': map_view_options}

Template Example

{% load tethys_gizmos %}

{% gizmo map_view_options %}

MVLayer

class tethys_sdk.gizmos.MVLayer(source, options, legend_title, layer_options=None, editable=True, legend_classes=None, legend_extent=None, legend_extent_projection='EPSG:4326', feature_selection=False, geometry_attribute=None, data=None)

MVLayer objects are used to define map layers for the Map View Gizmo.

source

The source or data type of the layer (e.g.: ImageWMS)

Type

str, required

options

A dictionary representation of the OpenLayers options object for ol.source.

Type

dict, required

legend_title

The human readable name of the layer that will be displayed in the legend.

Type

str, required

layer_options

A dictionary representation of the OpenLayers options object for ol.layer.

Type

dict

editable

If true the layer will be editable with the tethys_map_view drawing/editing tools.

Type

bool

feature_selection

Set to True to enable feature selection on this layer. Defaults to False.

Type

bool

geometry_attribute

The name of the attribute in the shapefile that describes the geometry

Type

str

legend_classes

A list of MVLegendClass objects.

Type

list

legend_extent

A list of four ordinates representing the extent that will be used on "zoom to layer": [minx, miny, maxx, maxy].

Type

list

legend_extent_projection

The EPSG projection of the extent coordinates. Defaults to "EPSG:4326".

Type

str

data

Dictionary representation of layer data

Type

dict

Example

# Define GeoJSON layer
geojson_object = {
  'type': 'FeatureCollection',
  'crs': {
    'type': 'name',
    'properties': {
      'name': 'EPSG:3857'
    }
  },
  'features': [
    {
      'type': 'Feature',
      'geometry': {
        'type': 'Point',
        'coordinates': [0, 0]
      }
    },
    {
      'type': 'Feature',
      'geometry': {
        'type': 'LineString',
        'coordinates': [[4e6, -2e6], [8e6, 2e6]]
      }
    },
    {
      'type': 'Feature',
      'geometry': {
        'type': 'Polygon',
        'coordinates': [[[-5e6, -1e6], [-4e6, 1e6], [-3e6, -1e6]]]
      }
    }
  ]
}

style_map = {
    'Point': {'ol.style.Style': {
        'image': {'ol.style.Circle': {
            'radius': 5,
            'fill': {'ol.style.Fill': {
                'color': 'red',
            }},
            'stroke': {'ol.style.Stroke': {
                'color': 'red',
                'width': 2
            }}
        }}
    }},
    'LineString': {'ol.style.Style': {
        'stroke': {'ol.style.Stroke': {
            'color': 'green',
            'width': 3
        }}
    }},
    'Polygon': {'ol.style.Style': {
        'stroke': {'ol.style.Stroke': {
            'color': 'blue',
            'width': 1
        }},
        'fill': {'ol.style.Fill': {
            'color': 'rgba(0, 0, 255, 0.1)'
        }}
    }},
}

geojson_layer = MVLayer(source='GeoJSON',
                        options=geojson_object,
                        layer_options={'style_map': style_map},
                        legend_title='Test GeoJSON',
                        legend_extent=[-46.7, -48.5, 74, 59],
                        legend_classes=[
                            MVLegendClass('polygon', 'Polygons', fill='rgba(0, 0, 255, 0.1)', stroke='blue'),
                            MVLegendClass('line', 'Lines', stroke='green'),
                            MVLegendClass('point', 'Points', fill='red')
                        ])

# Define GeoServer Layer
geoserver_layer = MVLayer(source='ImageWMS',
                          options={'url': 'http://192.168.59.103:8181/geoserver/wms',
                                   'params': {'LAYERS': 'topp:states'},
                                   'serverType': 'geoserver'},
                          legend_title='USA Population',
                          legend_extent=[-126, 24.5, -66.2, 49],
                          legend_classes=[
                              MVLegendClass('polygon', 'Low Density', fill='#00ff00', stroke='#000000'),
                              MVLegendClass('polygon', 'Medium Density', fill='#ff0000', stroke='#000000'),
                              MVLegendClass('polygon', 'High Density', fill='#0000ff', stroke='#000000')
                          ])

# Define GeoServer Tile Layer with Custom tile grid
# The default EPSG:900913 gridset can be used with OpenLayers.
# You must ensure that OpenLayers requests tiles with the same gridset and origin as the gridset GeoServer uses
# to use GeoWebCaching capabilities. This is done by setting the TILESORIGIN parameter and specifying a custom tileGrid.
# Refer to OpenLayers API for ol.tilegrid.TileGrid for explanation and options.
# See: http://docs.geoserver.org/2.7.0/user/webadmin/tilecache/index.html
geoserver_layer = MVLayer(source='TileWMS',
                          options={'url': 'http://192.168.59.103:8181/geoserver/wms',
                                   'params': {'LAYERS': 'topp:states',
                                              'TILED': True,
                                              'TILESORIGIN': '0.0,0.0'},
                                   'serverType': 'geoserver',
                                   'tileGrid': {
                                   'resolutions': [
                                       156543.03390625,
                                       78271.516953125,
                                       39135.7584765625,
                                       19567.87923828125,
                                       9783.939619140625,
                                       4891.9698095703125,
                                       2445.9849047851562,
                                       1222.9924523925781,
                                       611.4962261962891,
                                       305.74811309814453,
                                       152.87405654907226,
                                       76.43702827453613,
                                       38.218514137268066,
                                       19.109257068634033,
                                       9.554628534317017,
                                       4.777314267158508,
                                       2.388657133579254,
                                       1.194328566789627,
                                       0.5971642833948135,
                                       0.2985821416974068,
                                       0.1492910708487034,
                                       0.0746455354243517,
                                     ],
                                     'extent': [-20037508.34, -20037508.34, 20037508.34, 20037508.34],
                                     'origin': [0, 0],
                                     'tileSize': [256, 256]
                                   }
                          },
                          legend_title='USA Population')

# Define KML Layer
kml_layer = MVLayer(source='KML',
                    options={'url': '/static/tethys_gizmos/data/model.kml'},
                    legend_title='Park City Watershed',
                    legend_extent=[-111.60, 40.57, -111.43, 40.70],
                    legend_classes=[
                        MVLegendClass('polygon', 'Watershed Boundary', fill='#ff8000'),
                        MVLegendClass('line', 'Stream Network', stroke='#0000ff'),
                    ])

# Tiled ArcGIS REST Layer
arc_gis_layer = MVLayer(source='TileArcGISRest',
                        options={'url': 'http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/' + 'Specialty/ESRI_StateCityHighway_USA/MapServer'},
                        legend_title='ESRI USA Highway',
                        legend_extent=[-173, 17, -65, 72]),

MVLegendClass

class tethys_sdk.gizmos.MVLegendClass(type, value, fill='', stroke='', ramp=[])

MVLegendClasses are used to define the classes listed in the legend.

type

The type of feature to be represented by the legend class. Either 'point', 'line', 'polygon', or 'raster'.

Type

str, required

value

The value or name of the legend class.

Type

str, required

fill

Valid RGB color for the fill (e.g.: '#00ff00', 'rgba(0, 255, 0, 0.5)'). Required for 'point' or 'polygon' types.

Type

str

stoke

Valid RGB color for the stoke/line (e.g.: '#00ff00', 'rgba(0, 255, 0, 0.5)'). Required for 'line' types and optional for 'polygon' types.

Type

str

ramp

A list of hexidecimal RGB colors that will be used to construct a color ramp. Required for 'raster' types.

Type

list

Example

point_class = MVLegendClass(type='point', value='Cities', fill='#00ff00')
line_class = MVLegendClass(type='line', value='Roads', stroke='rbga(0,0,0,0.7)')
polygon_class = MVLegendClass(type='polygon', value='Lakes', stroke='#0000aa', fill='#0000ff')

MVLegendImageClass

class tethys_sdk.gizmos.MVLegendImageClass(value, image_url)

MVLegendImageClasses are used to define the classes listed in the legend using a pre-generated image.

value

The value or name of the legend class.

Type

str, required

image_url

The url to the legend image.

Type

str, required

Example

image_class = MVLegendImageClass(value='Cities',
                                 image_url='https://upload.wikimedia.org/wikipedia/commons/d/da/The_City_London.jpg'
                                 )

MVLegendGeoServerImageClass

class tethys_sdk.gizmos.MVLegendGeoServerImageClass(value, geoserver_url, style, layer, width=20, height=10)

MVLegendGeoServerImageClasses are used to define the classes listed in the legend using the GeoServer generated legend.

value

The value or name of the legend class.

Type

str, required

geoserver_url

The url to your geoserver (e.g. http://localhost:8181/geoserver).

Type

str, required

style

The name of the geoserver style (e.g. green).

Type

str, required

layer

The name of the geoserver layer (e.g. rivers).

Type

str, required

width

The legend width (default is 20).

Type

int

height

The legend height (default is 10).

Type

int

Example

image_class = MVLegendGeoServerImageClass(value='Cities',
                                          geoserver_url='http://localhost:8181/geoserver',
                                          style='green',
                                          layer='rivers',
                                          width=20,
                                          height=10)

MVDraw

class tethys_sdk.gizmos.MVDraw(controls=['Modify', 'Delete', 'Move', 'Point', 'LineString', 'Polygon', 'Box', 'Pan'], initial='Pan', output_format='GeoJSON', line_color='#ffcc33', fill_color='rgba(255, 255, 255, 0.2)', point_color='#ffcc33', initial_features=None, snapping_enabled=True, snapping_options={}, snapping_layer={}, feature_selection=False, legend_title='Drawing Layer', data=None)

MVDraw objects are used to define the drawing options for Map View.

controls

List of drawing controls to add to the map. Valid options are 'Modify', 'Delete', 'Move', 'Point', 'LineString', 'Polygon' and 'Box', 'Pan'.

Type

list

initial

Drawing control to be enabled initially. Must be included in the controls list, defaults to 'Pan'.

Type

str

initial_features

GeoJSON string containing features to add to the drawing layer.

Type

str

output_format

Format to output to the hidden text area. Either 'WKT' (for Well Known Text format) or 'GeoJSON'. Defaults to 'GeoJSON'

Type

str

line_color

User control for customizing the stroke color of annotation objects

Type

str

fill_color

User control for customizing the fill color of polygons (suggest rgba format for setting transparency)

Type

str

point_color

User control for customizing the color of points

Type

str

snapping_enabled

When enabled, features will be able to snap to other features on the drawing layer or in given snapping layers. Defaults to True.

Type

bool

snapping_options

Supported options include edge, vertex, pixelTolerance. See: https://openlayers.org/en/latest/apidoc/module-ol_interaction_Snap.html

Type

dict

snapping_layer

Dictionary with one key representing the attribute to use for identifying the layer and the value being the value to match (e.g.: {'legend_title': 'My Layer'}, {'data.my_attribute': 'value'}).

Type

dict

feature_selection

Set to True to enable feature selection on the drawing layer. Defaults to False.

Type

bool

legend_title

Title to display in the legend for the drawing layer. Defaults to 'Drawing Layer'.

Type

str

data

Dictionary representation of data to attach to the drawing layer.

Type

dict

Example

drawing_options = MVDraw(
    controls=['Modify', 'Delete', 'Move', 'Point', 'LineString', 'Polygon', 'Box', 'Pan'],
    initial='Point',
    output_format='GeoJSON',
    line_color='#663399',
    fill_color='rgba(255,255,255,0.2)',
    point_color='#663399'
)

MVView

class tethys_sdk.gizmos.MVView(projection, center, zoom, maxZoom=28, minZoom=0)

MVView objects are used to define the initial view of the Map View. The initial view is set by specifying a center and a zoom level.

projection

Projection of the center coordinates given. This projection will be used to transform the coordinates into the default map projection (EPSG:3857).

Type

str

center

An array with the coordinates of the center point of the initial view.

Type

list

zoom

The zoom level for the initial view.

Type

int or float

maxZoom

The maximum zoom level allowed. Defaults to 28.

Type

int or float

minZoom

The minimum zoom level allowed. Defaults to 0.

Type

int or float

Example

view_options = MVView(
    projection='EPSG:4326',
    center=[-100, 40],
    zoom=3.5,
    maxZoom=18,
    minZoom=2
)

JavaScript API

For advanced features, the JavaScript API can be used to interact with the OpenLayers map object that is generated by the Map View JavaScript library.

TETHYS_MAP_VIEW.getMap()

This method returns the OpenLayers map object. You can use the OpenLayers Map API version 4.0.1 to perform operations on this object such as adding layers and custom controls.

$(function() { //wait for page to load

    var ol_map = TETHYS_MAP_VIEW.getMap();
    ol_map.addLayer(...);
    ol_map.setView(...);

});

Caution

The Map View Gizmo is powered by OpenLayers version 4.0.1. When referring to the OpenLayers documentation, ensure that you are browsing the correct version of documentation (see the URL of the documentation page).

TETHYS_MAP_VIEW.updateLegend()

This method can be used to update the legend after removing/adding layers to the map.

$(function() { //wait for page to load

    var ol_map = TETHYS_MAP_VIEW.getMap();
    ol_map.addLayer(...);
    TETHYS_MAP_VIEW.updateLegend();

});

TETHYS_MAP_VIEW.zoomToExtent(latlongextent)

This method can be used to set the view of the map to the extent provided. The extent is assumed to be given in the EPSG:4326 coordinate reference system.

$(function() { //wait for page to load

    var extent = [-109.49945001309617, 37.58047995600726, -109.44540360290348, 37.679502621605735];
    TETHYS_MAP_VIEW.zoomToExtent(extent);
});

TETHYS_MAP_VIEW.clearSelection()

This method applies to the WMS layer feature selection functionality. Use this method to clear the current selection via JavaScript.

TETHYS_MAP_VIEW.clearSelection();

TETHYS_MAP_VIEW.overrideSelectionStyler(geometry_type, styler)

This method applies to the WMS layer feature selection functionality. This method can be used to override the default styling for the points, lines, and polygons selected feature layers.

  • geometry_type (str): The type of the layer that the styler function will apply to. One of: 'points', 'lines', or 'polygons'.

  • styler (func): A function that accepts two arguments, feature and resolution, and returns an array of valid ol.style objects.

function my_styler(feature, resolution) {
var image, properties;
    properties = feature.getProperties();

    // Default icon
    image = new ol.style.Circle({
        radius: 5,
        fill: new ol.style.Fill({
            color: 'red'
        })
    });

    if ('type' in properties) {
        if (properties.type === 'TANK') {
            image = new ol.style.RegularShape({
                fill: new ol.style.Fill({
                    color: SELECTED_NODE_COLOR
                }),
                stroke: new ol.style.Stroke({
                    color: 'white',
                    width: 1
                }),
                points: 4,
                radius: 14,
                rotation: 0,
                angle: Math.PI / 4
            });

        }
        else if (properties.type === 'RESERVOIR') {
            image = new ol.style.RegularShape({
                fill: new ol.style.Fill({
                    color: SELECTED_NODE_COLOR
                }),
                stroke: new ol.style.Stroke({
                    color: 'white',
                    width: 1
                }),
                points: 3,
                radius: 14,
                rotation: 0,
                angle: 0
            });
        }
    }

    return [new ol.style.Style({image: image})];

}

TETHYS_MAP_VIEW.overrideSelectionStyler('points', my_styler);

TETHYS_MAP_VIEW.onSelectionChange(callback)

This method applies to the WMS layer feature selection functionality. The callback function provided will be called each time the feature selection is changed.

  • callback (func): A function that accepts three arguments, points_layer, lines_layer, polygons_layer. These are handles on the OpenLayers layers that are rendering the selected features. The features are divided into three layers by type.

function my_callback(points_layer, lines_layer, polygons_layer) {
   console.log(points_layer);
}

TETHYS_MAP_VIEW.onSelectionChange(my_callback);

TETHYS_MAP_VIEW.getSelectInteraction()

This method applies to the WFS/GeoJSON/KML layer feature selection functionality.

$(function() { //wait for page to load

    var selection_interaction = TETHYS_MAP_VIEW.getSelectInteraction();

    //when selected, print feature to developers console
    selection_interaction.getFeatures().on('change:length', function(e) {
      if (e.target.getArray().length > 0) {
        // this means there is at least 1 feature selected
        var selected_feature = e.target.item(0); // 1st feature in Collection
        console.log(selected_feature);

      }
    });

});

TETHYS_MAP_VIEW.reInitializeMap()

This method is intended for initializing a map generated from an AJAX request.

Caution

This method assumes there is only one and that there will only ever be one map on the page.

Note

In order to use this, you will either need to use a MapView gizmo or import the JavaScript/CSS libraries in the main html template page using the register_gizmo_dependency tag in the register_gizmos block.

For example:

{% block import_gizmos %}
    {% import_gizmo_dependency map_view %}
{% endblock %}

Four elements are required:

1) A controller for the AJAX call with a map view gizmo.

@login_required()
def dam_break_map_ajax(request):
    """
    Controller for the dam_break_map ajax request.
    """
    if request.GET:
        ...

        #get layers
        map_layer_list = ...

        # Define initial view for Map View
        view_options = MVView(
            projection='EPSG:4326',
            center=[(bbox[0]+bbox[2])/2.0, (bbox[1]+bbox[3])/2.0],
            zoom=10,
            maxZoom=18,
            minZoom=2,
        )

        # Configure the map
        map_options = MapView(height='500px',
                              width='100%',
                              layers=map_layer_list,
                              controls=['FullScreen'],
                              view=view_options,
                              basemap='OpenStreetMap',
                              legend=True,
                              )

        context = { 'map_options': map_options }

        return render(request, 'dam_break_map_ajax/map_ajax.html', context)

2) A url map to the controller in app.py

...
    UrlMap(name='dam_break_map_ajax',
           url='dam-break/map/dam_break_map_ajax',
           controller='dam_break.controllers.dam_break_map_ajax'),
...

3) A template for with the tethys gizmo (e.g. map_ajax.html)

{% load tethys_gizmos %}

{% gizmo map_options %}

4) The AJAX call in the javascript

$(function() { //wait for page to load

    $.ajax({
        url: ajax_url,
        method: 'GET',
        data: ajax_data,
        success: function(data) {
            //add new map to map div
            $('#main_map_div').html(data);

            TETHYS_MAP_VIEW.reInitializeMap();
        }
    });

});