def build_map():

    logger.info("Preparing data")
    data = get_data()

    logger.info("Initializing map")
    m = folium.Map(location=INITIAL_ZOOM, zoom_start=6, tiles="cartodbpositron")

    logger.info("Creating GeoJSON")
    events_map = folium.GeoJson(
        data,
        name="Events documented",
        style_function=None,
        tooltip=folium.GeoJsonTooltip(
            aliases=["Name", "Last Name", "Occupation", "Violence Type"],
            fields=["first_name", "last_name", "occupation", "method"],
            localize=True,
        ),
    ).add_to(m)

    # add a search by first names
    logger.info("Creating search box for names")
    namesearch = Search(
        layer=events_map,
        geom_type="Point",
        placeholder="Escribe un nombre",
        collapsed=False,
        search_label="first_name",
        search_zoom=12,
        #     weight=3
    ).add_to(m)

    # add a search by last name
    logger.info("Creating search box for last names")
    lastnamesearch = Search(
        layer=events_map,
        geom_type="Point",
        placeholder="Escribe un apellido",
        collapsed=False,
        search_label="last_name",
        search_zoom=12,
    ).add_to(m)

    logger.info("Saving to index.html")
    m.save("./index.html")
Beispiel #2
0
    def draw_map(connection):

        # https://georgetsilva.github.io/posts/mapping-points-with-folium/
        # https://geoffboeing.com/2015/10/exporting-python-data-geojson/
        # https: // stackoverflow.com / questions / 60585689 / how - to - display - information - in -geojson - popup - python
        # https://stackoverflow.com/questions/50998176/6-millions-of-markers-in-folium-leaflet-map

        start_time = time.time()

        df = mapper.retrieve_points(connection)

        cols = df.columns
        raw_json = mapper.df_to_geojson(df, cols)

        locations = df[['latitude', 'longitude']]
        location_list = locations.values.tolist()
        print(df.head())

        with open('searchdata.json', 'w') as fp:
            json.dump(raw_json, fp)

        print("--- %s seconds ---" % (time.time() - start_time))

        print('Drawing Map...')

        start_time = time.time()

        m = folium.Map(location=[54.968220, -1.868530],
                       zoom_start=7,
                       prefer_canvas=True)  # lat/long

        with open('searchdata.json') as access_json:
            read_content = json.load(access_json)

        geojson_obj = folium.GeoJson(
            'searchdata.json',
            popup=folium.GeoJsonPopup(fields=cols.tolist())).add_to(m)

        Search(layer=geojson_obj,
               search_zoom=12,
               search_label='name',
               collapsed=False).add_to(m)

        folium.LayerControl().add_to(m)
        folium.plugins.LocateControl().add_to(m)

        m.save('map.html')
        # mapper.minify()
        print("--- %s seconds ---" % (time.time() - start_time))

        print('\nOpen \'map.html\' in a browser to view generated map')
Beispiel #3
0
def update_map():
    area = pd.read_csv(
        "https://data.nsw.gov.au/data/dataset/97ea2424-abaf-4f3e-a9f2-b5c883f42b6a/resource/2776dbb8-f807-4fb2-b1ed-184a6fc2c8aa/download/covid-19-cases-by-notification-date-location-and-likely-source-of-infection.csv"
    )
    postcodes = pd.read_csv("australian_postcodes.csv")
    testing = pd.read_csv(
        "https://data.nsw.gov.au/data/dataset/5424aa3b-550d-4637-ae50-7f458ce327f4/resource/227f6b65-025c-482c-9f22-a25cf1b8594f/download/covid-19-tests-by-date-and-location-and-result.csv"
    )
    area = area.rename(columns={"likely_source_of_infection": "Source"})
    testing = testing.rename(columns={"result": "Test Result"})
    testing['Test Result'] = testing['Test Result'].replace({
        'Tested & excluded':
        'Negative Test',
        'Case - Confirmed':
        'Positive Test'
    })
    area['Source'] = area['Source'].replace({
        'Locally acquired - contact of a confirmed case and/or in a known cluster':
        'Local (Known Source)',
        'Locally acquired - source not identified':
        'Local (Unknown Source)',
        'Under investigation':
        'Under Investigation'
    })

    area = area.dropna()
    area = area.merge(postcodes, on='postcode', how='inner')

    source_area = area.copy()
    source_area = source_area.groupby(
        ['notification_date', 'postcode', 'Source']).count()
    source_area = source_area.reset_index()

    testing_area = testing.dropna()
    testing_area = testing_area.groupby(
        ['test_date', 'postcode', 'Test Result']).count()
    testing_area = testing_area.reset_index()

    chart_area = area.copy()
    chart_area = chart_area.groupby(['notification_date', 'postcode']).count()
    chart_area = chart_area.reset_index()

    area['Cases'] = area['postcode'].map(area['postcode'].value_counts())
    area = area.sort_values('notification_date').drop_duplicates('postcode',
                                                                 keep='last')
    geometry = [Point(xy) for xy in zip(area.long, area.lat)]
    a = area.drop(['long', 'lat'], axis=1)
    crs = {'init': 'epsg:4326'}
    gdf = geopandas.GeoDataFrame(a, crs=crs, geometry=geometry)

    #FOLIUM START
    start_coords = (-33.86051951, 151.2015802)
    m = folium.Map(location=start_coords,
                   zoom_start=14,
                   min_zoom=8,
                   width='100%',
                   height='100%')

    for index, row in area.iterrows():

        source_subset = source_area[source_area['postcode'] == row['postcode']]
        test_subset = testing_area[testing_area['postcode'] == row['postcode']]
        subset = chart_area[chart_area['postcode'] == row['postcode']]
        subset['cumul'] = subset['long'].cumsum()

        chart = alt.Chart(source_subset).mark_bar(
            cornerRadiusTopLeft=3, cornerRadiusTopRight=3).encode(
                x=alt.X('notification_date', axis=alt.Axis(title='Date')),
                y=alt.Y('long', axis=alt.Axis(title='New Cases')),
                color=alt.Color('Source', legend=alt.Legend(orient="left")),
                tooltip=[
                    alt.Tooltip('notification_date', title="Date"),
                    alt.Tooltip('Source', title="Source"),
                    alt.Tooltip('long', title="New Cases")
                ]).properties(title="New Cases in Postcode " +
                              str(int(row['postcode'])) + " (Latest Case: " +
                              row['notification_date'] + ")",
                              width=500,
                              height=200)

        cum_chart = alt.Chart(subset).mark_line(point=True).encode(
            x=alt.X('notification_date', axis=alt.Axis(title='Date')),
            y=alt.Y('cumul', axis=alt.Axis(title='Total Cases (Cumulative)')),
            tooltip=[
                alt.Tooltip('notification_date', title="Date"),
                alt.Tooltip('cumul', title="Total Cases")
            ]).properties(title="Total Cases in Postcode " +
                          str(int(row['postcode'])) + " (Current Total: " +
                          str(int(row['Cases'])) + ")",
                          width=500,
                          height=200)

        #test_chart = alt.Chart(test_subset).mark_bar(cornerRadiusTopLeft=3,
        #cornerRadiusTopRight=3).encode(
        #x=alt.X('test_date', axis=alt.Axis(title='Date')),
        #y=alt.Y('lga_code19', axis=alt.Axis(title='Tests Conducted')),
        #color = alt.Color('Test Result', legend = alt.Legend(orient="left")),
        #tooltip = [alt.Tooltip('test_date', title = "Date"), alt.Tooltip('Test Result', title = "Test Result"), alt.Tooltip('lga_code19', title = "Number")]
        #).properties(
        #	title = "Number of Tests in Postcode "+str(int(row['postcode']))+" (Total Tested: "+str(int(test_subset['lga_code19'].sum()))+")"+" - Testing data decomissioned as of 8th June",
        #	width = 1000,
        #	height = 200
        #)

        #chart = alt.hconcat(test_chart, chart, cum_chart).resolve_scale(color='independent')
        chart = alt.hconcat(chart,
                            cum_chart).resolve_scale(color='independent')
        chart.save('chart.html', embed_options={'renderer': 'svg'})

        with open('chart.html', 'r') as f:
            html = f.read()
        iframe = IFrame(html, height=330, width=600)
        popup = folium.Popup(iframe, max_width=2650)

        #day
        if row['notification_date'] >= '2020-09-04':
            marker_color = 'red'
            fill_color = 'red'
        #week
        elif row['notification_date'] >= '2020-08-28':
            marker_color = 'blue'
            fill_color = 'blue'
        else:
            marker_color = 'green'
            fill_color = 'green'

        folium.Circle(location=[row['lat'], row['long']],
                      tooltip=row['name'],
                      radius=row['Cases'] * 10,
                      color=marker_color,
                      fill=True,
                      fill_color=fill_color,
                      popup=popup).add_to(m)

        print(row['postcode'], 'done')

    citygeo = folium.GeoJson(gdf, show=False, name='Marker').add_to(m)

    pcsearch = Search(layer=citygeo,
                      geom_type='Point',
                      placeholder='Search for an NSW postcode',
                      collapsed=True,
                      search_label='postcode',
                      position='topleft',
                      search_zoom=14).add_to(m)

    subsearch = Search(layer=citygeo,
                       geom_type='Point',
                       placeholder='Search for an NSW suburb',
                       collapsed=True,
                       search_label='name',
                       position='topright',
                       search_zoom=14).add_to(m)

    folium.LayerControl().add_to(m)

    m.save('templates/index.html')
    print('done')
Beispiel #4
0
    folium.Marker([lat, lon],
                  tooltip=r['Name'],
                  icon=folium.Icon(color='red', icon='cutlery')).add_to(groupA)

for i, r in df2.iterrows():
    lon, lat = coordTransform.bd09_to_gcj02(r['lon'], r['lat'])
    folium.Marker(
        [lat, lon],
        tooltip=r['Name'],
        icon=folium.DivIcon(
            icon_size=(100, 72),
            icon_anchor=(0, 0),
            html=
            '<div style="font-size: 12px;color: organe; background: white;">' +
            f"{r['Name']}" + '</div>')
    ).add_to(
        groupB
    )  #,icon=folium.Icon(color='red', icon='cutlery')icon=folium.Icon(color='red', icon='cutlery'),icon=DivIcon(icon_size=(150,36),icon_anchor=(0,0),html='<div style="font-size: 24pt">Test</div>')
    folium.Marker([lat, lon],
                  tooltip=r['Name'],
                  icon=folium.Icon(color='gray',
                                   icon='cutlery')).add_to(groupB)

map_f.add_child(groupA)
map_f.add_child(groupB)
map_f.add_child(bankgroup)
folium.LayerControl().add_to(map_f)
Search(bankgroup, geom_type='Points', search_zoom=None,
       position='topleft').add_to(map_f)

map_f.save('bank_g5_all.html')
Beispiel #5
0
            "name": "two"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [19.0402, 47.4979]
        }
    }, {
        "type": "Feature",
        "properties": {
            "name": "three"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [25.4858, 42.7339]
        }
    }]
}

geojson_obj = folium.GeoJson(points).add_to(m)

statesearch = Search(layer=geojson_obj,
                     geom_type='Point',
                     placeholder="Search",
                     collapsed=False,
                     search_label='name',
                     search_zoom=4,
                     position='topright').add_to(m)

m.save('example.html')
webbrowser.open("example.html", m)
Beispiel #6
0
def make_map():

    SEATTLE_COORDINATES = (47.6062, -122.3321)
    zoom_start = 12

    # create empty map zoomed in on San Francisco
    map = folium.Map(location=SEATTLE_COORDINATES, zoom_start=zoom_start, control_scale=True)

    # add neighborhoods on top of this. This is an experiment to be replaced with a polygon geojson
    geo_json_data = json.load(open('neighborhoods.geojson'))
    # parcel_data = json.load(open('Zoned_Parcels_forJSON.json'))
    # parcel2_data = json.load(open('Zoned_Parcels_forJSON_Featur.json'))


    # regular style of polygons


    def style_function(feature):
        return {
            'weight': 2,
            'dashArray': '5, 5',
            'fillOpacity': 0,
            'lineOpacity': 1,
        }


    def highlight_function(feature):
        return {
            'fillColor': 'blue',
            'weight': 2,
            'lineColor': 'black',
            'lineWeight': 2,
            'dashArray': '5, 5',
            'fillOpacity': 0.5,
            'lineOpacity': 1,
        }


    # apply the neighborhood outlines to the map
    neighborhoods = folium.features.GeoJson(geo_json_data,
                                   style_function=style_function,
                                   highlight_function=highlight_function,
                                   )
    # parcels = folium.features.GeoJson(parcel_data,
    #                                style_function=style_function,
    #                                highlight_function=highlight_function,
    #                                )

    neighborhoods2 = folium.map.FeatureGroup(name="neighborhoods2", overlay=True, control=True, show=True,)

    with open("neighborhoods.geojson") as f:
        geo_json_data_test = json.load(f)

    for i in range(0,len(geo_json_data_test["features"])):
        c = folium.features.GeoJson(geo_json_data_test["features"][i]["geometry"],
            name=(geo_json_data_test["features"][i]["properties"]["name"]),
            style_function=style_function,
            highlight_function=highlight_function,)
        folium.Popup(geo_json_data_test["features"][i]["properties"]["name"], geo_json_data_test["features"][i]["properties"]["nhood"]).add_to(c)
        neighborhoods2.add_child(c)

    import pdb; pdb.set_trace()  
    neighborhoods2.add_to(map)
    print(neighborhoods)
    print(neighborhoods2)

    neighborhoodsearch = Search(
        layer=neighborhoods2,
        geom_type='Polygon',
        placeholder='Search for a neighborhood name',
        collapsed=False,
        search_label='name',
        weight=3,
        fillColor="black",
        fillOpacity = 0.6
    ).add_to(map)
    # We need to fix kwargs and popups of polygons iterating through geojson


    # print(geo_json_data[1,:])
    # geo_json_data_df = pd.DataFrame.from_dict(geo_json_data)
    # geo_json_data_df.to_csv(r'/Users/Anaavu/Documents/GitHub/ADUniverse/app/geo_json_data_df.csv')


    # add a marker for every record in the filtered data, use a clustered view
    for _, row in data[0:MAX_RECORDS].iterrows():
        popup = folium.Popup("Feasibility: " + str(row['Random Number']) +
                             "<br> Address: " + str(row['Address']), max_width=300)
        # html_str = """
        # <a href="https://www.ibm.com/" target="_blank"> Details.</a>
        # """
        # iframe = folium.IFrame(html=html_str, width=100, height=50)
        # popup = folium.Popup(iframe, max_width=2650)
        folium.Marker([row['Latitude'], row['Longitude']], popup=popup).add_to(map)




        #     popup = folium.Popup(i['name'])
        # c.add_to(map)

    map.save("map.html")
    lon, lat = coordTransform.bd09_to_gcj02(r['lon'], r['lat'])
    folium.Marker(
        [lat, lon],
        tooltip=r['Name'],
        icon=folium.DivIcon(
            icon_size=(100, 72),
            icon_anchor=(0, 0),
            html=
            '<div style="font-size: 12px;color: organe; background: white;">' +
            f"{r['Name']}" + '</div>')
    ).add_to(
        groupB
    )  #,icon=folium.Icon(color='red', icon='cutlery')icon=folium.Icon(color='red', icon='cutlery'),icon=DivIcon(icon_size=(150,36),icon_anchor=(0,0),html='<div style="font-size: 24pt">Test</div>')
    folium.Marker([lat, lon],
                  tooltip=r['Name'],
                  icon=folium.Icon(color='gray',
                                   icon='cutlery')).add_to(groupB)

citysearch = Search(layer=geo,
                    geom_type='Point',
                    placeholder='Search',
                    search_zoom=16,
                    collapsed=True,
                    search_label='name').add_to(map_f)
#
map_f.add_child(groupA)
map_f.add_child(groupB)
map_f.add_child(bankgroup)
# map_f.add_child(all)
folium.LayerControl().add_to(map_f)
map_f.save('bank_g5_with_search.html')
    zoom_start=16.5
)

geojson_obj = folium.GeoJson(points, name="마커 보기").add_to(m)


for i in points["features"]:
    lati = i["geometry"]["coordinates"][1]
    longti = i["geometry"]["coordinates"][0]
    name = i["properties"]["name"]
    html = Template("""
    {{name}}<br>
    </p>
    """).render(name=name)  # html 형태로 마커 클릭 시 팝업 추가
    popup = folium.Popup(html, max_width=200)
    folium.Marker(location=[lati, longti], popup=popup).add_to(
        m)  # html 형태로 마커 클릭 시 팝업 추가

Search(layer=geojson_obj,
       geom_type='Point',
       placeholder="장소 검색",
       search_label='name',
       search_zoom=17,
       collapsed=False,
       position='topright').add_to(m)  # 장소 검색 기능 추가

plugins.LocateControl().add_to(m)  # gps 기능 추가

def make_html():
    m.save('spot_search.html')