Skip to content

geodemora module

Main module for the geodemora package

Map

Bases: ipyleaflet.Map

This Map class inherits the ipyleaftlet Map class.

Parameters:

Name Type Description Default
ipyleaflet ipyleaflet.Map

An ipyleaftlet map.

required
Source code in geodemora/geodemora.py
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class Map(ipyleaflet.Map):
    """This Map class inherits the ipyleaftlet Map class.

    Args:
        ipyleaflet (ipyleaflet.Map): An ipyleaftlet map.
    """    

    def __init__(self, **kwargs):

        if "center" not in kwargs:
            kwargs["center"] = [40, -100]

        if "zoom" not in kwargs:
            kwargs["zoom"] = 4

        if "scroll_wheel_zoom" not in kwargs:
            kwargs["scroll_wheel_zoom"] = True

        super().__init__(**kwargs)

        if "height" not in kwargs:
            self.layout.height = "600px"
        else:
            self.layout.height = kwargs["height"]

        self.add_control(FullScreenControl())
        self.add_control(LayersControl(position="topright"))
        self.add_control(DrawControl(position="topleft"))
        self.add_control(MeasureControl())
        self.add_control(ScaleControl(position="bottomleft"))

        if "google_map" not in kwargs:
            layer = TileLayer(
                url="https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}",
                attribution="Google",
                name="Google Satellite"
            )
            self.add_layer(layer)
        else:
            if kwargs["google_map"] == "ROADMAP":
                layer = TileLayer(
                    url="https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}",
                    attribution="Google",
                    name="Google Maps",
                )
                self.add_layer(layer)
            elif kwargs["google_map"] == "HYBRID":
                layer = TileLayer(
                    url="https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}",
                    attribution="Google",
                    name="Google Satellite"
                )
                self.add_layer(layer)

    def add_geojson(self, in_geojson, style=None, layer_name="Untitled"):
        """Adds a GeoJSON file to the map.
        Args:
            in_geojson (str): The file path to the input GeoJSON.
            style (dict, optional): The style for the GeoJSON layer. Defaults to None.
            layer_name (str, optional): The layer name for the GeoJSON layer. Defaults to "Untitled".
        Raises:
            FileNotFoundError: If the provided file path does not exist.
            TypeError: If the input geojson is not a str or dict.
        """

        import json

        if layer_name == "Untitled":
            layer_name = "Untitled " + random_string()

        if isinstance(in_geojson, str):

            if not os.path.exists(in_geojson):
                raise FileNotFoundError("The provided GeoJSON file could not be found.")

            with open(in_geojson) as f:
                data = json.load(f)

        elif isinstance(in_geojson, dict):
            data = in_geojson

        else:
            raise TypeError("The input geojson must be a type of str or dict.")

        if style is None:
            style = {
                "stroke": True,
                "color": "#000000",
                "weight": 2,
                "opacity": 1,
                "fill": True,
                "fillColor": "#0000ff",
                "fillOpacity": 0.4,
            }

        geo_json = ipyleaflet.GeoJSON(data=data, style=style, name=layer_name)
        self.add_layer(geo_json)

    def add_shapefile(self, in_shp, style=None, layer_name="Untitled"):
        """Add a shapefile to ipyleaflet map object.

        Args:
            in_shp (str): Filepath for an ESRI shapefile.  
            style (dict, optional): The style for the GeoJSON layer. Defaults to None.
            layer_name (str, optional): The layer name for the GeoJSON layer. Defaults to "Untitled".
        """        

        geojson = shp_to_geojson(in_shp)
        self.add_geojson(geojson, style = style, layer_name = layer_name)

    def add_ee_layer(
        self, ee_object, vis_params={}, name=None, shown=True, opacity=1.0
    ):
        """Adds a given EE object to the map as a layer.
        Args:
            ee_object (Collection|Feature|Image|MapId): The object to add to the map.
            vis_params (dict, optional): The visualization parameters. Defaults to {}.
            name (str, optional): The name of the layer. Defaults to 'Layer N'.
            shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
            opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.
        """

        ee_layer = ee_tile_layer(ee_object, vis_params, name, shown, opacity)
        self.add_layer(ee_layer)

    addLayer = add_ee_layer

add_ee_layer(ee_object, vis_params={}, name=None, shown=True, opacity=1.0)

Adds a given EE object to the map as a layer.

Parameters:

Name Type Description Default
ee_object Collection | Feature | Image | MapId

The object to add to the map.

required
vis_params dict

The visualization parameters. Defaults to {}.

{}
name str

The name of the layer. Defaults to 'Layer N'.

None
shown bool

A flag indicating whether the layer should be on by default. Defaults to True.

True
opacity float

The layer's opacity represented as a number between 0 and 1. Defaults to 1.

1.0
Source code in geodemora/geodemora.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
def add_ee_layer(
    self, ee_object, vis_params={}, name=None, shown=True, opacity=1.0
):
    """Adds a given EE object to the map as a layer.
    Args:
        ee_object (Collection|Feature|Image|MapId): The object to add to the map.
        vis_params (dict, optional): The visualization parameters. Defaults to {}.
        name (str, optional): The name of the layer. Defaults to 'Layer N'.
        shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
        opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.
    """

    ee_layer = ee_tile_layer(ee_object, vis_params, name, shown, opacity)
    self.add_layer(ee_layer)

add_geojson(in_geojson, style=None, layer_name='Untitled')

Adds a GeoJSON file to the map.

Parameters:

Name Type Description Default
in_geojson str

The file path to the input GeoJSON.

required
style dict

The style for the GeoJSON layer. Defaults to None.

None
layer_name str

The layer name for the GeoJSON layer. Defaults to "Untitled".

'Untitled'

Raises:

Type Description
FileNotFoundError

If the provided file path does not exist.

TypeError

If the input geojson is not a str or dict.

Source code in geodemora/geodemora.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def add_geojson(self, in_geojson, style=None, layer_name="Untitled"):
    """Adds a GeoJSON file to the map.
    Args:
        in_geojson (str): The file path to the input GeoJSON.
        style (dict, optional): The style for the GeoJSON layer. Defaults to None.
        layer_name (str, optional): The layer name for the GeoJSON layer. Defaults to "Untitled".
    Raises:
        FileNotFoundError: If the provided file path does not exist.
        TypeError: If the input geojson is not a str or dict.
    """

    import json

    if layer_name == "Untitled":
        layer_name = "Untitled " + random_string()

    if isinstance(in_geojson, str):

        if not os.path.exists(in_geojson):
            raise FileNotFoundError("The provided GeoJSON file could not be found.")

        with open(in_geojson) as f:
            data = json.load(f)

    elif isinstance(in_geojson, dict):
        data = in_geojson

    else:
        raise TypeError("The input geojson must be a type of str or dict.")

    if style is None:
        style = {
            "stroke": True,
            "color": "#000000",
            "weight": 2,
            "opacity": 1,
            "fill": True,
            "fillColor": "#0000ff",
            "fillOpacity": 0.4,
        }

    geo_json = ipyleaflet.GeoJSON(data=data, style=style, name=layer_name)
    self.add_layer(geo_json)

add_shapefile(in_shp, style=None, layer_name='Untitled')

Add a shapefile to ipyleaflet map object.

Parameters:

Name Type Description Default
in_shp str

Filepath for an ESRI shapefile.

required
style dict

The style for the GeoJSON layer. Defaults to None.

None
layer_name str

The layer name for the GeoJSON layer. Defaults to "Untitled".

'Untitled'
Source code in geodemora/geodemora.py
109
110
111
112
113
114
115
116
117
118
119
def add_shapefile(self, in_shp, style=None, layer_name="Untitled"):
    """Add a shapefile to ipyleaflet map object.

    Args:
        in_shp (str): Filepath for an ESRI shapefile.  
        style (dict, optional): The style for the GeoJSON layer. Defaults to None.
        layer_name (str, optional): The layer name for the GeoJSON layer. Defaults to "Untitled".
    """        

    geojson = shp_to_geojson(in_shp)
    self.add_geojson(geojson, style = style, layer_name = layer_name)

ee_tile_layer(ee_object, vis_params={}, name='Layer untitled', shown=True, opacity=1.0)

Converts and Earth Engine layer to ipyleaflet TileLayer.

Parameters:

Name Type Description Default
ee_object Collection | Feature | Image | MapId

The object to add to the map.

required
vis_params dict

The visualization parameters. Defaults to {}.

{}
name str

The name of the layer. Defaults to 'Layer untitled'.

'Layer untitled'
shown bool

A flag indicating whether the layer should be on by default. Defaults to True.

True
opacity float

The layer's opacity represented as a number between 0 and 1. Defaults to 1.

1.0
Source code in geodemora/geodemora.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def ee_tile_layer(
    ee_object, vis_params={}, name="Layer untitled", shown=True, opacity=1.0
):
    """Converts and Earth Engine layer to ipyleaflet TileLayer.
    Args:
        ee_object (Collection|Feature|Image|MapId): The object to add to the map.
        vis_params (dict, optional): The visualization parameters. Defaults to {}.
        name (str, optional): The name of the layer. Defaults to 'Layer untitled'.
        shown (bool, optional): A flag indicating whether the layer should be on by default. Defaults to True.
        opacity (float, optional): The layer's opacity represented as a number between 0 and 1. Defaults to 1.
    """

    image = None

    if (
        not isinstance(ee_object, ee.Image)
        and not isinstance(ee_object, ee.ImageCollection)
        and not isinstance(ee_object, ee.FeatureCollection)
        and not isinstance(ee_object, ee.Feature)
        and not isinstance(ee_object, ee.Geometry)
    ):
        err_str = "\n\nThe image argument in 'addLayer' function must be an instace of one of ee.Image, ee.Geometry, ee.Feature or ee.FeatureCollection."
        raise AttributeError(err_str)

    if (
        isinstance(ee_object, ee.geometry.Geometry)
        or isinstance(ee_object, ee.feature.Feature)
        or isinstance(ee_object, ee.featurecollection.FeatureCollection)
    ):
        features = ee.FeatureCollection(ee_object)

        width = 2

        if "width" in vis_params:
            width = vis_params["width"]

        color = "000000"

        if "color" in vis_params:
            color = vis_params["color"]

        image_fill = features.style(**{"fillColor": color}).updateMask(
            ee.Image.constant(0.5)
        )
        image_outline = features.style(
            **{"color": color, "fillColor": "00000000", "width": width}
        )

        image = image_fill.blend(image_outline)
    elif isinstance(ee_object, ee.image.Image):
        image = ee_object
    elif isinstance(ee_object, ee.imagecollection.ImageCollection):
        image = ee_object.mosaic()

    map_id_dict = ee.Image(image).getMapId(vis_params)
    tile_layer = TileLayer(
        url=map_id_dict["tile_fetcher"].url_format,
        attribution="Google Earth Engine",
        name=name,
        opacity=opacity,
        visible=shown,
    )
    return tile_layer

shp_to_geojson(in_shp, out_geojson=None)

Converts a shapefile to GeoJSON.

Parameters:

Name Type Description Default
in_shp str

The file path to the input shapefile.

required
out_geojson str

The file path to the output GeoJSON. Defaults to None.

None

Raises:

Type Description
FileNotFoundError

If the input shapefile does not exist.

Returns:

Name Type Description
dict

The dictionary of the GeoJSON.

Source code in geodemora/geodemora.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def shp_to_geojson(in_shp, out_geojson=None):
    """Converts a shapefile to GeoJSON.
    Args:
        in_shp (str): The file path to the input shapefile.
        out_geojson (str, optional): The file path to the output GeoJSON. Defaults to None.
    Raises:
        FileNotFoundError: If the input shapefile does not exist.
    Returns:
        dict: The dictionary of the GeoJSON.
    """
    import json
    import shapefile

    in_shp = os.path.abspath(in_shp)

    if not os.path.exists(in_shp):
        raise FileNotFoundError("The provided shapefile could not be found.")

    sf = shapefile.Reader(in_shp)
    geojson = sf.__geo_interface__

    if out_geojson is None:
        return geojson
    else:
        out_geojson = os.path.abspath(out_geojson)
        out_dir = os.path.dirname(out_geojson)
        if not os.path.exists(out_dir):
            os.makedirs(out_dir)
        with open(out_geojson, "w") as f:
            f.write(json.dumps(geojson))

Last update: 2022-06-06