Example #1
0
File: map.py Project: pmains/folium
    def _get_self_bounds(self):
        """
        Computes the bounds of the object itself (not including it's children)
        in the form [[lat_min, lon_min], [lat_max, lon_max]].

        """
        return get_bounds(self.location)
Example #2
0
    def _get_self_bounds(self):
        """
        Computes the bounds of the object itself (not including it's children)
        in the form [[lat_min, lon_min], [lat_max, lon_max]].

        """
        return get_bounds(self.location)
Example #3
0
def test_mulyipolyline():
    m = Map()

    locations = [[[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]],
                 [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]]]

    multipolyline = PolyLine(locations=locations, popup='MultiPolyLine')
    multipolyline.add_to(m)

    expected_options = {
        'smoothFactor': 1.0,
        'noClip': False,
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'opacity': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polyline(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations,
               name=multipolyline.get_name(),
               map=m.get_name())

    rendered = multipolyline._template.module.script(multipolyline)
    assert normalize(rendered) == normalize(expected_rendered)
    assert multipolyline.get_bounds() == get_bounds(locations)
    assert json.dumps(multipolyline.to_dict()) == multipolyline.to_json()
    assert multipolyline.options == expected_options
Example #4
0
def test_polygon_marker():
    m = Map()
    locations = [[35.6636, 139.7634], [35.6629, 139.7664], [35.6663, 139.7706],
                 [35.6725, 139.7632], [35.6728, 139.7627], [35.6720, 139.7606],
                 [35.6682, 139.7588], [35.6663, 139.7627]]
    polygon = Polygon(locations=locations, popup='I am a polygon')
    polygon.add_to(m)

    expected_options = {
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'noClip': False,
        'opacity': 1.0,
        'smoothFactor': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polygon(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations, name=polygon.get_name(), map=m.get_name())

    rendered = polygon._template.module.script(polygon)
    assert _normalize(rendered) == _normalize(expected_rendered)
    assert polygon.get_bounds() == get_bounds(locations)
    assert json.dumps(polygon.to_dict()) == polygon.to_json()
    assert polygon.options == json.dumps(expected_options,
                                         sort_keys=True,
                                         indent=2)  # noqa
Example #5
0
def test_mulyipolyline():
    m = Map()

    locations = [[[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]],
                 [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]]]

    multipolyline = PolyLine(locations=locations, popup='MultiPolyLine')
    multipolyline.add_to(m)

    expected_options = {
        'smoothFactor': 1.0,
        'noClip': False,
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'opacity': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polyline(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations, name=multipolyline.get_name(), map=m.get_name())

    rendered = multipolyline._template.module.script(multipolyline)
    assert normalize(rendered) == normalize(expected_rendered)
    assert multipolyline.get_bounds() == get_bounds(locations)
    assert json.dumps(multipolyline.to_dict()) == multipolyline.to_json()
    assert multipolyline.options == expected_options
Example #6
0
def test_polyline():
    m = Map()
    locations = [[40, -80], [45, -80]]
    polyline = PolyLine(locations=locations, popup='I am PolyLine')
    polyline.add_to(m)

    expected_options = {
        'smoothFactor': 1.0,
        'noClip': False,
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'opacity': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polyline(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations, name=polyline.get_name(), map=m.get_name())

    rendered = polyline._template.module.script(polyline)
    assert rendered.strip().split() == expected_rendered.strip().split()
    assert polyline.get_bounds() == get_bounds(locations)
    assert json.dumps(polyline.to_dict()) == polyline.to_json()
    assert polyline.options == json.dumps(expected_options, sort_keys=True, indent=2)  # noqa
Example #7
0
def test_polyline():
    m = Map()
    locations = [[40.0, -80.0], [45.0, -80.0]]
    polyline = PolyLine(locations=locations, popup='I am PolyLine')
    polyline.add_to(m)

    expected_options = {
        'smoothFactor': 1.0,
        'noClip': False,
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'opacity': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polyline(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations, name=polyline.get_name(), map=m.get_name())

    rendered = polyline._template.module.script(polyline)
    assert normalize(rendered) == normalize(expected_rendered)
    assert polyline.get_bounds() == get_bounds(locations)
    assert json.dumps(polyline.to_dict()) == polyline.to_json()
    assert polyline.options == expected_options
Example #8
0
def get_map_list_single_run(eval_view, range_key, trip_id_pattern):
    map_list = []
    color_list = ['blue', 'red', 'purple', 'orange']
    for phoneOS, phone_map in eval_view.map("calibration").items():
        print("Processing data for %s phones" % phoneOS)
        for curr_calibrate, curr_calibrate_trip_map in phone_map.items():
            if trip_id_pattern not in curr_calibrate:
                print(
                    "curr_calibrate = %s, not matching pattern %s, skipping" %
                    (curr_calibrate, trip_id_pattern))
                continue
            curr_map = folium.Map()
            all_points = []
            for i, (phone_label, phone_data_map) in enumerate(
                    curr_calibrate_trip_map.items()):
                print("%d, %s, %s" % (i, phone_label, phone_data_map.keys()))
                location_df = phone_data_map["location_df"]
                latlng_route_coords = list(
                    zip(location_df.latitude, location_df.longitude))
                all_points.extend(latlng_route_coords)
                # print(latlng_route_coords[0:10])
                if len(latlng_route_coords) > 0:
                    print(
                        "Processing %s, %s, found %d locations, adding to map"
                        % (curr_calibrate, phone_label,
                           len(latlng_route_coords)))
                    pl = folium.PolyLine(latlng_route_coords,
                                         popup="%s" % (phone_label),
                                         color=color_list[i])
                    pl.add_to(curr_map)
                else:
                    print("Processing %s, %s, found %d locations, skipping" %
                          (curr_calibrate, phone_label,
                           len(latlng_route_coords)))
            curr_bounds = ful.get_bounds(all_points)
            print(curr_bounds)
            top_lat = curr_bounds[0][0]
            mid_lng = (curr_bounds[0][1] + curr_bounds[1][1]) / 2
            print(
                "for trip %s with %d points, midpoint = %s, %s, plotting at %s, %s"
                % (curr_calibrate, len(all_points), top_lat, mid_lng, top_lat,
                   mid_lng))
            folium.map.Marker(
                [top_lat, mid_lng],
                icon=fof.DivIcon(
                    icon_size=(200, 36),
                    html=
                    '<div style="font-size: 12pt; color: green;">%s: %s</div>'
                    % (phoneOS, curr_calibrate))).add_to(curr_map)
            curr_map.fit_bounds(pl.get_bounds())
            map_list.append(curr_map)
    return map_list
Example #9
0
    def _get_self_bounds(self):
        """
        Computes the bounds of the object itself (not including it's children)
        in the form [[lat_min, lon_min], [lat_max, lon_max]].

        """
        if not self.embed:
            raise ValueError('Cannot compute bounds of non-embedded GeoJSON.')

        data = json.loads(self.data)
        if 'features' not in data.keys():
            # Catch case when GeoJSON is just a single Feature or a geometry.
            if not (isinstance(data, dict) and 'geometry' in data.keys()):
                # Catch case when GeoJSON is just a geometry.
                data = {'type': 'Feature', 'geometry': data}
            data = {'type': 'FeatureCollection', 'features': [data]}

        return get_bounds(data, lonlat=True)
Example #10
0
 def _get_self_bounds(self):
     """Compute the bounds of the object itself."""
     return get_bounds(self.locations)
Example #11
0
def test_polygon_marker():
    m = Map()
    locations = [[35.6636, 139.7634],
                 [35.6629, 139.7664],
                 [35.6663, 139.7706],
                 [35.6725, 139.7632],
                 [35.6728, 139.7627],
                 [35.6720, 139.7606],
                 [35.6682, 139.7588],
                 [35.6663, 139.7627]]
    polygon = Polygon(locations=locations, popup='I am a polygon')
    polygon.add_to(m)

    expected_options = {
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'noClip': False,
        'opacity': 1.0,
        'smoothFactor': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polygon(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations, name=polygon.get_name(), map=m.get_name())

    rendered = polygon._template.module.script(polygon)
    assert normalize(rendered) == normalize(expected_rendered)
    assert polygon.get_bounds() == get_bounds(locations)
    assert json.dumps(polygon.to_dict()) == polygon.to_json()
    assert polygon.options == expected_options
Example #12
0
def get_map_list_eval_sections(eval_view, os_pattern, trip_id_pattern,
                               compare_pattern):
    compare_pattern_re = re.compile("(" + compare_pattern +
                                    ")|accuracy_control")
    print(compare_pattern_re)
    map_list = []
    color_list = [mco.rgb2hex(c) for c in mcm.tab20.colors]
    for phoneOS, phone_map in eval_view.map("evaluation").items():
        section_map = {}
        all_points = {}
        print("Processing data for %s phones" % phoneOS)
        if os_pattern not in phoneOS:
            print("pattern %s not found in %s, skipping" %
                  (os_pattern, phoneOS))
            continue

        for curr_eval, curr_eval_trip_map in phone_map.items():
            print("curr_eval = %s" % curr_eval)
            for curr_eval_trip_id, eval_trip_compare_map in curr_eval_trip_map.items(
            ):
                if trip_id_pattern not in curr_eval_trip_id:
                    print("pattern %s not found in %s, skipping" %
                          (trip_id_pattern, curr_eval_trip_id))
                    continue
                for i, (compare_id, compare_tr) in enumerate(
                        eval_trip_compare_map.items()):
                    # print(i, len(eval_trip_compare_map.items()))
                    # print(compare_pattern_re.search(compare_id))
                    if compare_pattern_re.search(compare_id) is None:
                        print(
                            "compare_id = %s, not matching pattern %s, skipping"
                            % (compare_id, compare_pattern))
                        continue
                    if "power_control" in compare_id:
                        print("Skipping the last item (power_control)")
                        continue
                    for sr in compare_tr["evaluation_section_ranges"]:
                        # print("Considering section %s" % sr)
                        gt_leg = eval_view.spec_details.get_ground_truth_for_leg(
                            compare_tr["trip_id_base"], sr["trip_id_base"])
                        # print("Found ground truth %s for %s" % (gt_leg, sr["trip_id"]))
                        if gt_leg["type"] != "TRAVEL":
                            print(
                                "Found non-travel trip, no spatial ground truth, skipping..."
                            )
                            continue
                        sec_id = curr_eval_trip_id + "_" + sr["trip_id"]
                        if sec_id not in section_map:
                            print("curr_section_id = %s, creating new map" %
                                  sec_id)
                            section_map[sec_id] = folium.Map()
                            all_points[sec_id] = []
                            gt_leg_gj = eval_view.spec_details.get_geojson_for_leg(
                                gt_leg)
                            pl_gt = folium.GeoJson(gt_leg_gj,
                                                   name="ground_truth")
                            pl_gt.add_to(section_map[sec_id])
                        curr_map = section_map[sec_id]
                        curr_all_points = all_points[sec_id]
                        location_df = sr["location_df"]
                        print("Found %d locations for %s, %s, %s, %s" %
                              (len(location_df), curr_eval, curr_eval_trip_id,
                               compare_id, sec_id))
                        if len(location_df) > 0:
                            lonlat_route_coords = list(
                                zip(location_df.longitude,
                                    location_df.latitude))
                            latlon_route_coords = list(
                                zip(location_df.latitude,
                                    location_df.longitude))
                            trip_gj = gj.Feature(
                                geometry=gj.LineString(lonlat_route_coords),
                                properties={"style": {
                                    "color": color_list[i]
                                }})
                            pl = folium.GeoJson(trip_gj, name=compare_id)
                            curr_all_points.extend(latlon_route_coords)
                            print(
                                "Processing %s, %s, %s, %s found %d locations, adding to map with color %s"
                                % (curr_eval,
                                   curr_eval_trip_id, compare_id, sec_id,
                                   len(lonlat_route_coords), color_list[i]))
                            pl.add_to(curr_map)
                        else:
                            print(
                                "Processing %s, %s, %s, %s found %d locations, skipping"
                                % (curr_eval, curr_eval_trip_id, compare_id,
                                   sec_id, len(latlon_route_coords)))

        print(
            "Finished processing %d (%d) sections for phoneOS %s, formatting maps"
            % (len(section_map), len(all_points), phoneOS))
        print([(sec_id, len(point_list))
               for sec_id, point_list in all_points.items()])

        for sec_id, point_list in all_points.items():
            curr_map = section_map[sec_id]
            if len(point_list) > 0:
                curr_bounds = ful.get_bounds(point_list)
                print(curr_bounds)
                top_lat = curr_bounds[0][0]
                mid_lng = (curr_bounds[0][1] + curr_bounds[1][1]) / 2
                print(
                    "for trip %s with %d points, midpoint = %s, %s, plotting at %s, %s"
                    % (curr_eval_trip_id, len(point_list), top_lat, mid_lng,
                       top_lat, mid_lng))
                folium.map.Marker(
                    [top_lat, mid_lng],
                    icon=fof.DivIcon(
                        icon_size=(200, 36),
                        html=
                        '<div style="font-size: 12pt; color: green;">%s: %s</div>'
                        % (phoneOS, sec_id))).add_to(curr_map)
                curr_map.fit_bounds(curr_bounds)
                folium.LayerControl().add_to(curr_map)
        map_list.extend(section_map.values())
    print("Returning %s" % map_list)
    return map_list
Example #13
0
def get_map_list_eval_trips(eval_view, os_pattern, trip_id_pattern,
                            compare_pattern):
    compare_pattern_re = re.compile("(" + compare_pattern +
                                    ")|accuracy_control")
    print(compare_pattern_re)
    map_list = []
    color_list = [mco.rgb2hex(c) for c in mcm.tab20.colors]
    for phoneOS, phone_map in eval_view.map("evaluation").items():
        print("Processing data for %s phones" % phoneOS)
        if os_pattern not in phoneOS:
            print("pattern %s not found in %s, skipping" %
                  (os_pattern, phoneOS))
            continue

        for curr_eval, curr_eval_trip_map in phone_map.items():
            print("curr_eval = %s" % curr_eval)
            for curr_eval_trip_id, eval_trip_compare_map in curr_eval_trip_map.items(
            ):
                if trip_id_pattern not in curr_eval_trip_id:
                    print("pattern %s not found in %s, skipping" %
                          (trip_id_pattern, curr_eval_trip_id))
                    continue
                print("curr_eval_trip_id = %s, creating new map" % curr_eval)
                curr_map = folium.Map()
                all_points = []
                for i, (compare_id, compare_tr) in enumerate(
                        eval_trip_compare_map.items()):
                    # print(i, len(eval_trip_compare_map.items()))
                    # print(compare_pattern_re.search(compare_id))
                    if compare_pattern_re.search(compare_id) is None:
                        print(
                            "compare_id = %s, not matching pattern %s, skipping"
                            % (compare_id, compare_pattern))
                        continue
                    if "power_control" in compare_id:
                        print("Skipping the last item (power_control)")
                        continue
                    location_df = compare_tr["location_df"]
                    print("Found %d locations for %s, %s, %s" %
                          (len(location_df), curr_eval, curr_eval_trip_id,
                           compare_id))
                    if len(location_df) > 0:
                        lonlat_route_coords = list(
                            zip(location_df.longitude, location_df.latitude))
                        latlon_route_coords = list(
                            zip(location_df.latitude, location_df.longitude))
                        trip_gj = gj.Feature(
                            geometry=gj.LineString(lonlat_route_coords),
                            properties={"style": {
                                "color": color_list[i]
                            }})
                        pl = folium.GeoJson(trip_gj, name=compare_id)
                        all_points.extend(latlon_route_coords)
                        print(
                            "Processing %s, %s, %s, found %d locations, adding to map with color %s"
                            % (curr_eval, curr_eval_trip_id, compare_id,
                               len(lonlat_route_coords), color_list[i]))
                        pl.add_to(curr_map)
                    else:
                        print(
                            "Processing %s, %s, %s, found %d locations, skipping"
                            % (curr_eval, curr_eval_trip_id, compare_id,
                               len(latlon_route_coords)))

                if len(all_points) > 0:
                    curr_bounds = ful.get_bounds(all_points)
                    # print(curr_bounds)
                    top_lat = curr_bounds[0][0]
                    mid_lng = (curr_bounds[0][1] + curr_bounds[1][1]) / 2
                    print(
                        "for trip %s with %d points, midpoint = %s, %s, plotting at %s, %s"
                        % (curr_eval_trip_id, len(all_points), top_lat,
                           mid_lng, top_lat, mid_lng))
                    folium.map.Marker(
                        [top_lat, mid_lng],
                        icon=fof.DivIcon(
                            icon_size=(200, 36),
                            html=
                            '<div style="font-size: 12pt; color: green;">%s: %s</div>'
                            % (phoneOS, curr_eval_trip_id))).add_to(curr_map)
                    curr_map.fit_bounds(pl.get_bounds())
                    folium.LayerControl().add_to(curr_map)
                map_list.append(curr_map)
    print("Returning %s" % map_list)
    return map_list
Example #14
0
 def _get_self_bounds(self):
     """Compute the bounds of the object itself."""
     return get_bounds(self.locations)