def FoliumMap(df_):
    '''
    Function creates a new, empty map with folium, the map doesnt contain any datapoints yet but is intialized at the mean latitude & longitude
    point in our dataset. Then adds data points = flats (markers) to the map. For each observation (=row) of the dataset we read the latitude & longitude
    to create an icon which will be a display for the flat on the map. Furthermore we add a pop up text with basic information about the flat
    to each icon. We create clusters to achieve better visualisation.
    '''
    new_map = folium.Map(
        location=[df_['latitude'].mean(), df_['longitude'].mean()],
        zoom_start=12,
        tiles='cartodbpositron')
    mc = MarkerCluster()  # create empty cluster object
    for row in tqdm(df_.itertuples()):
        mc.add_child(
            folium.Marker(
                location=[row.latitude,
                          row.longitude],  #create markers and add to cluster
                popup=folium.Popup(
                    folium.IFrame(('''Size: {Size} <br>
                  m2: {m2} <br>
                  Base Price: {bp} <br>
                  Utilities: {up} <br> 
                  Total Price: {TotalPrice}''').format(Size=row.Size,
                                                       m2=row.m2,
                                                       bp=row[5],
                                                       up=row[6],
                                                       TotalPrice=row[7]),
                                  width=200,
                                  height=100)),
                icon=folium.Icon(icon='home')))  #define icon symbol
    new_map.add_child(mc)
    new_map.save(outfile='folium_map.html'
                 )  #saves file as html file in working directory
    return new_map
def makeSearchMapData():
    mask_store_info = getNearMaskStoreInfo(CoronaMaskList.addr)
    data_for_draw3 = mask_store_info.loc[:, [
        'name', 'latitude', 'longitude', 'remain_stat'
    ]]
    data_for_draw_except_nan3 = data_for_draw3.dropna()
    data_for_draw_except_nan3 = data_for_draw_except_nan3[
        data_for_draw_except_nan3['remain_stat'] != 'break']
    x = data_for_draw_except_nan3.loc[[1], ['latitude']].values
    y = data_for_draw_except_nan3.loc[[1], ['longitude']].values

    map_hs3 = folium.Map((x, y), zoom_start=14)

    mc3 = MarkerCluster()
    names = list(data_for_draw_except_nan3['name'])
    latitudes = list(data_for_draw_except_nan3['latitude'])
    longitudes = list(data_for_draw_except_nan3['longitude'])
    remain_stats = list(data_for_draw_except_nan3['remain_stat'])

    for i in tqdm(range(len(names))):
        mc3.add_child(
            folium.Marker(location=[latitudes[i], longitudes[i]],
                          icon=folium.Icon(color=color_dic[remain_stats[i]]),
                          popup=names[i] + ' ' +
                          remain_stat_kor[remain_stats[i]]))
        map_hs3.add_child(mc3)

    map_hs3.save("./mask_store4.html")
    webbrowser.open_new('mask_store4.html')


#executeMaskMap()
示例#3
0
def create_map():
    """
    Create an OSM-based map with location markers and save it to html file.
    """
    # https://deparkes.co.uk/2016/06/10/folium-map-tiles/
    m = folium.Map(
        location=[0, 0],
        tiles='Cartodb Positron',
        zoom_start=1
    )

    marker_cluster = MarkerCluster(
        name='CAT Locations',
        overlay=True,
        control=False,
        icon_create_function=None
    )

    locations = get_locations()
    for k in locations.keys():
        location = locations[k]['y'], locations[k]['x']
        marker = folium.Marker(location=location)
        popup = '{0}'.format(k)

        folium.Popup(popup).add_to(marker)
        marker_cluster.add_child(marker)

    marker_cluster.add_to(m)
    folium.LayerControl().add_to(m)

    m.save('map.html')
示例#4
0
def customers(request):
    starting_Lat = 40.610870
    starting_Long = -73.962158
    map_hooray = folium.Map(
        location=[starting_Lat, starting_Long],
        tiles="OpenStreetMap",
        zoom_start=12,
        max_zoom=12,
    )
    folium.Marker(
        location=[starting_Lat, starting_Long],
        icon=folium.Icon(color='black', icon='star'),
    ).add_to(map_hooray)
    all_lat = Transaction.objects.values('lat')
    all_long = Transaction.objects.values('long')
    mc = MarkerCluster()
    for i in range(len(all_lat)):
        mc.add_child(
            folium.Marker(
                location=[all_lat[i].get('lat'), all_long[i].get('long')]))
    map_hooray.add_child(mc)
    folium.plugins.Fullscreen(position='topright',
                              title='Full Screen',
                              title_cancel='Exit Full Screen',
                              force_separate_button=True).add_to(map_hooray)
    context = {'map': map_hooray._repr_html_()}
    return render(request, 'inventory/customers.html', context)
def generate_map():

    bike_service_proxy = BikeServiceProxy()
    bikes_map = folium.Map(location=GDANSK_CENTER_POSITION, zoom_start=10)
    markers_cluster = MarkerCluster()

    with open(PATH_TO_LOCATIONS, mode='r') as locations_file:
        locations_reader = csv.DictReader(locations_file)

        for station_row in locations_reader:

            available_bikes = get_available_bikes_number(station_row)
            if available_bikes > 0:

                available_bikes_ids = get_available_bikes_ids(station_row)
                coordinates = get_coordinates(station_row)

                for bike_id in available_bikes_ids:

                    battery_level = bike_service_proxy.battery_info_for_bike(
                        bike_id)
                    battery_info = get_battery_level_info(battery_level)
                    marker_color = get_marker_color(battery_level)

                    bike_marker = prepare_bike_marker(coordinates, bike_id,
                                                      battery_info,
                                                      marker_color)
                    markers_cluster.add_child(bike_marker)

    bikes_map.add_child(markers_cluster)
    bikes_map.save('bikes_map.html')
示例#6
0
def BuildMap(velib_op):
    """
    Create and save a folium map with operational velib in Paris and suburbs 
    
    Args:
        velib_op (DataFrame): Clean Dataset with [lat, long, Available velib, Nom de la station,
                                Nombre de bornes disponible] columns
    """

    m = folium.Map(location=[48.85, 2.35],
                   tiles='Cartodb Positron',
                   zoom_start=11)

    marker_cluster = MarkerCluster(name='Velib clustered',
                                   overlay=True,
                                   control=False,
                                   icon_create_function=None)

    for k, v in velib_op.iterrows():
        location = v.lat, v.long
        marker = folium.Marker(location=location)
        popup = 'Station:{}<br>Number of Velibs:{}<br>Number of available docks:{}'.format(
            v['Nom de la station'], v['Available velib'],
            v['Nombre de bornes disponibles'])
        folium.Popup(popup).add_to(marker)
        marker_cluster.add_child(marker)

    marker_cluster.add_to(m)

    m.save(
        "C:/Users/maxen/OneDrive - DXC Production/Industrialized AI Open Badge Boot Camp/3 Build AI Data Pipelines/real-time-velib/real-time-velib-analysis/web-application/templates/map.html"
    )

    return
def build_html_for(execution_date, conn, credentials):
    sql_query = build_query_for(execution_date.year, execution_date.month)
    logging.info(sql_query)
    df = sqlio.read_sql_query(sql_query, conn)

    if df.empty:
        logging.info('Query returned empty results set')
        return

    pickup_map = Map(
        location=[df['pickup_latitude'].mean(), df['pickup_longitude'].mean()],
        tiles='OpenStreetMap',
        zoom_start=12)

    mc = MarkerCluster()

    for row in df.itertuples():
        mc.add_child(
            folium.Marker(location=[row.pickup_latitude, row.pickup_longitude],
                          popup=str(row.pickup_latitude) + ',' +
                          str(row.pickup_longitude)))

    pickup_map.add_child(mc)
    html_file_name = "{}-{}_pickups_map.html".format(execution_date.year,
                                                     execution_date.month)
    pickup_map.save(outfile=html_file_name)

    upload_file_to_s3(
        html_file_name,
        "data-sprints-eng-test/outputs/monthly/{}".format(html_file_name),
        credentials, "text/html")

    os.remove(html_file_name)
示例#8
0
def map_wells(wh):
    latitude = 54.73
    longitude = -117.52704
    wells_map = folium.Map(location=[latitude, longitude], zoom_start=5)
    mc = MarkerCluster()
    # add markers to map
    for row in wh.itertuples():
        mc.add_child(
            folium.CircleMarker(
                #label = 'UWI: {}<br> Formation: {}<br> Current Operator: {}'.format(row.UWI,row.Formation,row.CurrentOperator)
                #label = folium.Popup(label,parse_html=False)
                location=[row.Surf_Latitude, row.Surf_Longitude],
                radius=3,
                popup=
                'UWI: {uwi}<br>Formation: {formation}<br>Current Operatonr:{currentop}'
                .format(uwi=row.UWI,
                        formation=row.Formation,
                        currentop=row.CurrentOperator)
                #popup=label,
                #color='blue',
                #fill=True,
                #parse_html=False,

                #fill_opacity=0.7,
            ))
    wells_map.add_child(mc)
    #wells_map.save('wells.html’)
    return (wells_map)
示例#9
0
def plot_geometry(geometry, marker_cluster=False):
    """
    Plot geometries in Folium

    Parameters:
    geometry (shapely.geometry.LineString/Point or geopandas.GeoSeries)

    Example:
    lat = [40.732605, 40.732612, 40.732255, 40.731856, 40.731469]
    lon = [-73.99607, -73.996087, -73.996351, -73.996639, -73.996932]
    t = LineString([[lon, lat] for lat, lon in zip(lat, lon)])
    plot_linestring(t)
    """
    if (type(geometry) != gpd.GeoSeries):
        geometry = gpd.GeoSeries(geometry)

    geometry_ = geometry.geometry[0]
    initial_coords = [geometry_.xy[1][0], geometry_.xy[0][0]]

    map_ = folium.Map(initial_coords, zoom_start=14)

    geometries_json = json.loads(geometry.to_json())
    geometries_geojson = folium.features.GeoJson(geometries_json)

    if (marker_cluster == True):  # exclusively for points plot
        mc = MarkerCluster()
        mc.add_child(geometries_geojson)
        map_.add_child(mc)
    else:
        map_.add_child(geometries_geojson)
    return map_
示例#10
0
def update_map():

    m_1 = folium.Map(location=[40.415157, -3.689048],
                     tiles='openstreetmap',
                     zoom_start=10)

    y, x = connect("datamad1019", "swimming-pools")

    aggResult = x.find({})
    df2 = pd.DataFrame(list(aggResult))
    df2.head()

    mc = MarkerCluster()
    for idx, row in df2.iterrows():
        if not math.isnan(row['Location']["cordinates"][1]) and not math.isnan(
                row['Location']["cordinates"][0]):
            link = '<a href=' + f'{row["Google_link"]}' + 'target="_blank">' + 'Satellite View' + '</a>'
            mc.add_child(
                Marker([
                    row['Location']["cordinates"][1],
                    row['Location']["cordinates"][0]
                ],
                       popup=folium.Popup(link)))
    m_1.add_child(mc)

    embed_map(m_1, "./templates/map.html")
    print(
        "New map generated. Please restart application to see new swimming pools."
    )
    return m_1
示例#11
0
def build_addr_folium_map(df_addr_geo,
                          group_col,
                          marker_data,
                          icon_prop_dict,
                          latlon_cols=('latitude', 'longitude'),
                          color_dict=None,
                          color_col=None):
    a_folium_map = folium.Map(
        location=df_addr_geo[list(latlon_cols)].mean(axis=0).tolist(),
        zoom_start=12)

    locations = dict()
    popups = dict()
    icons = dict()
    # we create 3 groups for layer to be displayed
    for group in df_addr_geo[group_col].unique():
        locations[group] = list()
        popups[group] = list()
        icons[group] = list()

        cluster = df_addr_geo.loc[df_addr_geo[group_col] == group]
        mc = MarkerCluster(
            name=group,
            options={
                "spiderfyOnMaxZoom": True,
                "removeOutsideVisibleBounds": True,
                "singleMarkerMode": False,
                "showCoverageOnHover": True,
                #"disableClusteringAtZoom": 18,
            })
        cols = marker_data + ['latitude', 'longitude']
        if color_col is not None:
            cols.append(color_col)
        for el in cluster[cols].to_dict(orient='records'):
            frame_body_template = ''
            for data_name in marker_data:
                frame_body_template += f'<h3>{data_name} : '
                frame_body_template += str(el[data_name]) + '<h3>'
            iframe = folium.IFrame(html=frame_body_template,
                                   width=300,
                                   height=300)
            popup = folium.Popup(iframe)
            location = [el.get(latlon_cols[0]), el.get(latlon_cols[1])]
            icon_prop = icon_prop_dict[group]
            if color_dict is not None:
                icon_prop.update({
                    "color":
                    color_dict.get(el.get(color_col, None), 'black')
                })
            icon = folium.Icon(**icon_prop)
            locations[group].append(location)
            popups[group].append(popup)
            icons[group].append(icon)
            mc.add_child(
                folium.Marker(location=location, popup=popup, icon=icon))
        a_folium_map.add_child(mc)
    a_folium_map.add_child(folium.LayerControl())
    return a_folium_map
示例#12
0
def generate_base_map(gdf):
    """[summary] creates a base map for use in building Naptan maps.

    Args:
        gdf ([geopandas data]): [description]
        map_name ([str]): [str identify of the map]
    Returns:
        [type]: [description]
    """

    gm = folium.Map(
        location=[gdf["Latitude"].mean(), gdf["Longitude"].mean()],
        zoom_start=11,
        prefer_canvas=True,
        zoom_control=True,
        control_scale=True,
    )
    #  add measure control with km and area return calculations.
    gm.add_child(
        MeasureControl(
            position="bottomright",
            primary_length_unit="kilometers",
            secondary_length_unit="miles",
            secondary_area_unit="acres",
            primary_area_unit="sqmeters",
        ))
    # added lat long pop up for reference
    folium.LatLngPopup().add_to(gm)
    # clustering added
    mc = MarkerCluster().add_to(gm)

    # add the popups with relevant data
    for row in gdf.itertuples():
        html = f"""<!DOCTYPE html><div class="boxed">
                <b>ATCOCode:</b> <i>{row.ATCOCode}</i><br>
                <b>StopType:</b> <i>{row.StopType}</i><br>
                <b>StopPoint:</b> <i>{row.StopPoint}</i><br>
                <b>Coordinates:</b> <i>{row.Latitude}, {row.Longitude}</i><br>
                <b>Locality_Name:</b> {row.LocalityName}<br>
                <b>AreaName:</b> <i>{row.AreaName}</i><br>
                </div>
                """
        # add the markers to the marker cluster.
        mc.add_child(
            folium.Marker(
                location=[row.Latitude, row.Longitude],
                popup=html,
                radius=8,
                icon=folium.Icon(color="green", prefix="fa-", icon="ok-sign"),
            ))
    # add layer control.
    folium.LayerControl(collapsed=False, position="topright").add_to(gm)
    # get name of the mapped area.
    map_name = gdf.AreaName.iloc[0]
    # save the map
    save_generated_map(mc, map_name=map_name)
    return gm
示例#13
0
    def gen_map(self):
        # read database
        connection = sqlite3.connect("posts.db")
        cursor = connection.cursor()
        sql = f"""SELECT * FROM "{self.handle}" """
        cursor.execute(sql)
        result = cursor.fetchall()
        connection.close()

        # Generate map, cluster class and create empty coordinates list
        if self.handle == "4x4theboiz":
            my_map = Map(location=[-25.25, 21.2], zoom_start=5)
        elif self.handle == "teampolarsteps":
            my_map = Map(location=[52.35, 5.3], zoom_start=9)
        elif self.handle == "cityofcapetown":
            my_map = Map(location=[-34.1, 18.420], zoom_start=10)
        elif self.handle == "backpackingtours":
            my_map = Map(location=[10, 100], zoom_start=3)
        elif self.handle == "tony_ontheroad":
            my_map = Map(location=[38.5, -2.75], zoom_start=6)
        elif self.handle == "rolling_sloane":
            my_map = Map(location=[55, 2.64], zoom_start=4)
        elif self.handle == "cape_secrets":
            my_map = Map(location=[-33.4, 18.8], zoom_start=8)

        else:
            my_map = Map(location=[0, 0], zoom_start=2)
        mc = MarkerCluster()
        coords = []

        # For each location convert address to coordinates, create popup and marker,
        # add to marker cluster
        for i in range(0, len(result), 1):

            popup_content = f"{result[i][0]} <br> " \
                            f"<a href={result[i][1]} > See Post"
            p = Popup(popup_content, max_width=400)
            mk = Marker([result[i][2], result[i][3]], p)
            mc.add_child(mk)
            lat_lon = (result[i][2], result[i][3])
            coords.append(lat_lon)

        # Add Polyline with coords
        if self.handle == "4x4theboiz":
            polyline = PolyLine(coords, color="red", weight=2, opacity=0.7)
            polyline.add_to(my_map)
        elif self.handle == "tony_ontheroad":
            polyline = PolyLine(coords, color="red", weight=2, opacity=0.7)
            polyline.add_to(my_map)
        else:
            pass
        # Add Marker Cluster with mc
        my_map.add_child(mc)
        # Save the Map Instance Into a HTML file
        map_name = f"templates/map_{self.handle}.html"
        my_map.save(map_name)
示例#14
0
def draw_mult_map(df_a, df_b):

    m = folium.Map(location=[df_a['lat'].mean(), df_b['long'].mean()],
                   zoom_start=15,
                   control_scale=True)

    feature_group_estaciones = folium.FeatureGroup(
        name='Estaciones de Bicicletas')
    feature_group_tiendas = folium.FeatureGroup(name='bicicleterias')

    marker_cluster_estaciones = MarkerCluster()
    marker_cluster_tiendas = MarkerCluster()

    for row in df_a.iterrows():
        marker_estaciones = folium.Marker(
            location=[row[1]['lat'], row[1]['long']],
            popup=str(row[1]['nro_est']) + '. ' + str(row[1]['nombre']),
            icon=folium.Icon(color='green'))
        marker_cluster_estaciones.add_child(marker_estaciones)

    for row in df_b.iterrows():
        marker_tiendas = folium.Marker(
            location=[row[1]['lat'], row[1]['long']],
            popup=row[1]['nombre'],
            icon=folium.Icon(color='red'))
        marker_cluster_tiendas.add_child(marker_tiendas)

    feature_group_estaciones.add_child(marker_cluster_estaciones)
    feature_group_tiendas.add_child(marker_cluster_tiendas)

    m.add_child(feature_group_estaciones)
    m.add_child(feature_group_tiendas)
    m.add_child(folium.LayerControl())

    #OPTIONAL PLUGGINS
    #minimaps
    minimap = MiniMap(toggle_display=True)
    m.add_child(minimap)

    #measure tool
    m.add_child(MeasureControl())
    #show de coordinates from cursor position
    MousePosition().add_to(m)

    #draw tools
    draw = Draw(export=True)
    draw.add_to(m)

    #full screen
    Fullscreen(position='topright',
               title='Expand me',
               title_cancel='Exit me',
               force_separate_button=True).add_to(m)
    return m
示例#15
0
def mupLoader(mapElement, fname, color):
    # open csv file and read coln
    initLen = len(data)
    print(initLen, len(data))
    markuster = MarkerCluster()
    for row in data.itertuples():
        markuster.add_child(Marker(
            location=[row[5], row[6]],
            popup=row[1]
        ))
    mapElement.add_child(markuster)
示例#16
0
def main(year: str, curr_location: tuple):
    """
    Main function of the module. Generates map based on year and usr current location.
    """
    film_info_dict = read_file(year)
    film_info_dict = add_distance(curr_location, film_info_dict)
    closest = unpack_info(film_info_dict)

    # generate the map
    film_map = folium.Map(location=list(curr_location), zoom_start=10)
    fg = MarkerCluster(name='The closest films')
    lines = folium.FeatureGroup(name='Connections')

    # add home point
    fg.add_child(
        folium.Marker(location=list(curr_location),
                      icon=folium.Icon(icon='glyphicon glyphicon-home',
                                       color='blue')))

    for film in closest:
        location = list(film[0])

        html = f'''
                   <div style='font-family: Arial;'>
                   <b>Year:</b> {film[1][0]}
                   <br>
                   <b>Film:</b> {film[1][1]}
                   </div>
                '''
        iframe = folium.IFrame(html, width=200, height=100)

        popup = folium.Popup(iframe, max_width=250)
        fg.add_child(
            folium.Marker(location=location,
                          popup=popup,
                          icon=folium.Icon(
                              icon='glyphicon glyphicon-map-marker',
                              color='red')))
        lines.add_child(
            folium.PolyLine(locations=[list(curr_location), location],
                            line_opacity=0.1,
                            color='#e88000'))

    film_map.add_child(fg)
    film_map.add_child(lines)

    folium.TileLayer('cartodbdark_matter').add_to(film_map)
    folium.LayerControl().add_to(film_map)

    film_map.save(f'{year}_movies_map.html')
    return f'{year}_movies_map.html'
def map2():
    adr = mergedTables.objects.all()
    qs_adr = adr
    df_of_query_result_adr = read_frame(qs_adr)
    newTable_adr = df_of_query_result_adr
    m = folium.Map(location=[48.8566, 2.3522],
                   tiles="Stamen Toner",
                   zoom_start=2)
    #cergy=['49.034955','2.069925']
    #pau=['43.319568','-0.360571']
    newTable_ent_adr = newTable_adr[['ENT_LAT', 'ENT_LON']]
    newTable_stu_adr = newTable_adr[['ADR_LAT', 'ADR_LON']]
    newTable_site_adr = newTable_adr[['SITE_LAT', 'SITE_LON']]
    newTable_ent_adr = newTable_ent_adr.dropna(axis=0,
                                               subset=['ENT_LAT', 'ENT_LON'])
    newTable_stu_adr = newTable_stu_adr.dropna(axis=0,
                                               subset=['ADR_LAT', 'ADR_LON'])
    newTable_site_adr = newTable_site_adr.dropna(
        axis=0, subset=['SITE_LAT', 'SITE_LON'])
    #newTable_ent_adr= [[row['ENT_LAT'],row['ENT_LON']] for index,row in newTable_ent_adr.iterrows() ]
    #newTable_stu_adr= [[row['ADR_LAT'],row['ADR_LON']] for index,row in newTable_stu_adr.iterrows() ]
    #HeatMap(cergy).add_to(m)
    HeatMap(newTable_stu_adr).add_to(m)
    mc = MarkerCluster()
    folium.CircleMarker(
        [49.034955, 2.069925],
        radius=20,
        popup='Cergy Campus',
        color='red',
    ).add_to(m)
    folium.CircleMarker(
        [43.319568, -0.360571],
        radius=20,
        popup='Pau Campus',
        color='red',
    ).add_to(m)

    for i in range(0, len(newTable_stu_adr)):
        #mc.add_child(folium.Marker([newTable_ent_adr.iloc[i]['ENT_LAT'],newTable_ent_adr.iloc[i]['ENT_LON']],icon=folium.Icon(icon='cloud'))).add_to(m)
        mc.add_child(
            folium.Marker([
                newTable_ent_adr.iloc[i]['ENT_LAT'],
                newTable_ent_adr.iloc[i]['ENT_LON']
            ])).add_to(m)
        #mc.add_child(folium.Marker([newTable_stu_adr.iloc[i]['ADR_LAT'],newTable_stu_adr.iloc[i]['ADR_LON']],icon=folium.Icon(color='red'))).add_to(m)
        #folium.Marker([newTable_site_adr.iloc[i]['SITE_LAT'],newTable_site_adr.iloc[i]['SITE_LON']],icon=folium.Icon(icon='green')).add_to(m)
        #m.add_children(plugins.HeatMap(newTable_adr_lo, radius=15))

    m.save(os.path.join(BASE_DIR,
                        'DjangoWeb V1\Interface\\templates\map.html'))
    return None
def getMap(df):

    #Vancouver location Co-ordinates.
    VC_COORDINATES = (49.2827, -123.1207)
    crime_map = folium.Map(location=VC_COORDINATES, zoom_start=8)
    marker = MarkerCluster()

    # This add markers on blank map
    for i in df.itertuples():
        marker.add_child(folium.Marker(location=[i.Latitude, i.Longitude],
                                       popup=i.TYPE))
    crime_map.add_child(marker)
    crime_map.save('static/map.html')
    return crime_map
示例#19
0
def clustermap(df, main_class, location):
    """
    This is a function that creates a cluster map.

    Parameters
    ----------
    df (dataframe): dataframe with latitude and longitude columns
    main_class (string): overarching class to analyze from dataframe
    location (list): latitude and longitude  of central map location (e.g. NYC = [40.693943, -74.025])

    Returns
    -------
    A cluster map of sensors

    """
    if ('latitude' in df.columns) and ('longitude' in df.columns):

        # create dataframe that is grouped by sensor and counts occurrence of overarching class for each one

        gdf = df.groupby(['sensor_id', 'latitude',
                          'longitude'])[main_class].count().reset_index()

        # convert to geo dataframe and create geometry column with lat/long

        gdf = gpd.GeoDataFrame(gdf,
                               crs={'init': 'epsg:4326'},
                               geometry=gpd.points_from_xy(
                                   gdf.longitude, gdf.latitude))

        circlemap = folium.Map(location=location, zoom_start=12)

        # add marker for each sensor, use a clustered view (zoom in to see individual sensors)
        # added labels for each sensor which displays the sensor number and the counted occurence for music
        mc = MarkerCluster()
        for index, row in gdf.iterrows():
            mc.add_child(
                folium.Marker(
                    location=[str(row['latitude']),
                              str(row['longitude'])],
                    clustered_marker=True))

        # add marker cluster layer to empty map

        circlemap.add_child(mc)
        return circlemap
    else:
        print(
            "Dataframe does not have latitude and longitude columns or check to make sure column names are 'latitude'"
            "and 'longitude'")
示例#20
0
文件: __init__.py 项目: synw/dataswim
 def mcluster(self, lat_col: str, lon_col: str):
     """
     Add a markers cluster to the map
     """
     try:
         mc = MarkerCluster()
         rows = []
         for _, v in self.df.iterrows():
             tup = (v[lat_col], v[lon_col])
             rows.append(tup)
         for el in rows:
             mc.add_child(folium.Marker([el[0], el[1]]))
         self.dsmap.add_child(mc)
     except Exception as e:
         self.err(e, "Can not add marker cluster")
示例#21
0
def make_map(gdf):
    gm = folium.Map(
        location=[gdf["Latitude"].mean(), gdf["Longitude"].mean()],
        zoom_start=11,
        prefer_canvas=True,
        zoom_control=True,
        control_scale=True,
    )
    #  add measure control with km and area return calculations.
    gm.add_child(
        MeasureControl(
            position="bottomright",
            primary_length_unit="kilometers",
            secondary_length_unit="miles",
            secondary_area_unit="acres",
            primary_area_unit="sqmeters",
        ))
    # added lat long pop up for reference
    folium.LatLngPopup().add_to(gm)
    # clustering added
    mc = MarkerCluster().add_to(gm)

    # add the popups with relevant data
    for row in gdf.itertuples():
        html = f"""<!DOCTYPE html><div class="boxed">
                <b>ATCOCode:</b> <i>{row.ATCOCode}</i><br>
                <b>StopType:</b> <i>{row.StopType}</i><br>
                <b>StopPoint:</b> <i>{row.StopPoint}</i><br>
                <b>Coordinates:</b> <i>{row.Latitude}, {row.Longitude}</i><br>
                <b>Locality_Name:</b> {row.LocalityName}<br>
                <b>AreaName:</b> <i>{row.AreaName}</i><br>
                </div>
                """
        # add the markers to the marker cluster.
        mc.add_child(
            folium.Marker(
                location=[row.Latitude, row.Longitude],
                popup=html,
                radius=8,
                icon=folium.Icon(color="green", prefix="fa-", icon="ok-sign"),
            ))
    # add layer control.
    folium.LayerControl(collapsed=False, position="topright").add_to(gm)

    return gm
示例#22
0
    def draw_heat_map(geo_map: Map, requests: dict):
        show = True
        requests_list = sorted(requests.items(), key=lambda item: item[0])
        for request_type in requests_list:
            if show:
                feature_group = FeatureGroup(name=request_type[0], show=True)
                show = False
            else:
                feature_group = FeatureGroup(name=request_type[0], show=False)
            mc = MarkerCluster()
            for request in request_type[1]:
                # print(request[2])
                popup_info = 'Request Type: \n' + request[3] + '\nAddress: ' + request[2]
                mc.add_child(Marker(location=[request[0], request[1]], popup=popup_info))
            mc.add_to(feature_group)
            feature_group.add_to(geo_map)

        LayerControl().add_to(geo_map)
示例#23
0
    def mapper(self, doc_id, db_name):
        AUS_BOUND_BOX = (113.338953078, -43.6345972634, 153.569469029,
                         -10.6681857235)
        # centeroid = [(AUS_BOUND_BOX[1] + AUS_BOUND_BOX[3]) / 2, (AUS_BOUND_BOX[0] + AUS_BOUND_BOX[2]) / 2]
        data = self.retrieve_data(doc_id, db_name)
        df = pd.DataFrame(data['data'])

        map = folium.Map(location=[-37.814, 144.96332],
                         zoom_start=12,
                         tiles='OpenStreetMap')
        folium.TileLayer('Mapbox Control Room').add_to(map)
        folium.TileLayer('Stamen Terrain').add_to(map)
        folium.TileLayer('Stamen Toner').add_to(map)
        folium.TileLayer('stamenwatercolor').add_to(map)
        folium.TileLayer('cartodbpositron').add_to(map)

        cluster = MarkerCluster(name='Cluster')
        fg = folium.FeatureGroup(name='Sentiment Distribution')
        pos_fg = folium.FeatureGroup(name='Positive')
        neu_fg = folium.FeatureGroup(name='Neutral')
        neg_fg = folium.FeatureGroup(name='Negative')

        for index, row in df.iterrows():
            cor = row['coordinates']
            if AUS_BOUND_BOX[0] <= cor[0] <= AUS_BOUND_BOX[
                    2] and AUS_BOUND_BOX[1] <= cor[1] <= AUS_BOUND_BOX[3]:
                marker, pos_fg, neu_fg, neg_fg = self.create_marker(
                    cor, row['sentiment'], row['text'], pos_fg, neu_fg, neg_fg)
                cluster.add_child(marker)

        fg.add_child(cluster)
        fg.add_child(pos_fg)
        fg.add_child(neu_fg)
        fg.add_child(neg_fg)
        map.add_child(fg)

        # map.add_child(pos_fg)
        # map.add_child(neu_fg)
        # map.add_child(neg_fg)

        # folium.LayerControl().add_to(fg)
        folium.LayerControl().add_to(map)

        return map
示例#24
0
def main(user_lst, friends_lst, num):
    map_html = folium.Map()
    marker_cluster = MarkerCluster().add_to(map_html)
    geolocator = ArcGIS(timeout=10)
    lst = [
        "Name: ", "Location: ", "Description: ", "url: ", "Followers: ",
        "Friends: ", "Listed: ", "Created: ", "Favourites: ", "Posts: "
    ]

    # Adding User on map

    place = geolocator.geocode(user_lst[1])
    if place == None:
        popup_message = '<img src="{}"/><br>'.format(user_lst[-1])
        for i in range(len(user_lst) - 1):
            popup_message += "{}{}<br>".format(lst[i], user_lst[i])
        marker_cluster.add_child(
            folium.Marker(location=[randint(-90, 90),
                                    randint(-180, 180)],
                          popup=popup_message,
                          icon=folium.Icon(color='green')))
    else:
        popup_message = '<img src="{}"/><br>'.format(user_lst[-1])
        for i in range(len(user_lst) - 1):
            popup_message += "{}{}<br>".format(lst[i], user_lst[i])
        marker_cluster.add_child(
            folium.Marker(location=[place.latitude, place.longitude],
                          popup=popup_message,
                          icon=folium.Icon(color='green')))

    # Adding friends on map

    for i in range(len(friends_lst)):
        place = geolocator.geocode(friends_lst[i][1])
        if place == None:
            popup_message = '<img src="{}"/><br>'.format(friends_lst[i][-1])
            for j in range(len(friends_lst[i]) - 1):
                popup_message += "{}{}<br>".format(lst[j], friends_lst[i][j])
            marker_cluster.add_child(
                folium.Marker(location=[randint(-90, 90),
                                        randint(-180, 180)],
                              popup=popup_message,
                              icon=folium.Icon(color='red')))
        else:
            popup_message = '<img src="{}"/><br>'.format(friends_lst[i][-1])
            for j in range(len(friends_lst[i]) - 1):
                popup_message += "{}{}<br>".format(lst[j], friends_lst[i][j])
            marker_cluster.add_child(
                folium.Marker(location=[place.latitude, place.longitude],
                              popup=popup_message,
                              icon=folium.Icon(color='red')))

    map_html.save("templates/map_html.html")
示例#25
0
def build_shops_map(competitor_shops_df: pandas.DataFrame,
                    shops_df: pandas.DataFrame) -> folium.Map:
    competitors_map = folium.Map(
        location=[
            competitor_shops_df["CompetitorShopLatitude"].mean(),
            competitor_shops_df["CompetitorShopLongitude"].mean(),
        ],
        zoom_start=7,
    )
    # creating a Marker for each point in df_sample. Each point will get a popup with their zip
    mc = MarkerCluster()
    for index, row in competitor_shops_df.iterrows():
        lat = row["CompetitorShopLatitude"]
        lon = row["CompetitorShopLongitude"]
        company = row["CompetitorShopCompany"]
        city = row["CompetitorShopAdress"]
        mc.add_child(
            folium.Marker(
                location=[lat, lon],
                popup=company + "@" + city + "[" + str(lat) + ";" + str(lon) +
                "]",
            ))

    competitors_map.add_child(mc)

    mm = MarkerCluster()
    for index, row in shops_df.iterrows():
        lat = row["Latitude"]
        lon = row["Longitude"]
        company = row["Company"]
        city = row["Adress"]
        mm.add_child(
            folium.Marker(
                location=[lat, lon],
                popup=company + "@" + city + "[" + str(lat) + ";" + str(lon) +
                "]",
                icon=folium.Icon(color="red", icon="info-sign"),
            ))
    competitors_map.add_child(mm)

    return competitors_map
示例#26
0
def draw_map(df, cluster_marks=True):

    m = folium.Map(location=[df['lat'].mean(), df['long'].mean()],
                   zoom_start=15,
                   control_scale=True)

    if cluster_marks == True:

        mc = MarkerCluster()

        for row in df.iterrows():
            mc.add_child(
                folium.Marker(location=[row[1]['lat'], row[1]['long']],
                              popup=row[1]['nombre']))
        m.add_child(mc)
    else:
        for row in df.iterrows():
            folium.Marker(location=[row[1]['lat'], row[1]['long']],
                          popup=row[1]['nombre']).add_to(m)

    #OPTIONAL PLUGGINS
    #minimaps
    minimap = MiniMap(toggle_display=True)
    m.add_child(minimap)

    #measure tool
    m.add_child(MeasureControl())
    #show de coordinates from cursor position
    MousePosition().add_to(m)

    #draw tools
    draw = Draw(export=True)
    draw.add_to(m)

    #full screen
    Fullscreen(position='topright',
               title='Expand me',
               title_cancel='Exit me',
               force_separate_button=True).add_to(m)

    return m
示例#27
0
def CreatePopupCluster(markerArr):

    marker_cluster = MarkerCluster(
        name='1000 clustered icons',
        overlay=True,
        control=True,
        icon_create_function=None
    )

    [marker_cluster.add_child(marker) for marker in markerArr]

    return marker_cluster
示例#28
0
    def generate_map_html(self, data):
        df = pd.DataFrame(data=data,
                          columns=[
                              "scientificName", "municipality", "state",
                              "country", "latitude", "longitude", "date"
                          ])
        columns = [
            "scientificName", "municipality", "state", "country", "date"
        ]
        df.drop(columns, axis=1, inplace=True)

        df.replace('', np.nan, inplace=True)

        # Drop NaN values from dataframe
        df = df.dropna(subset=['longitude'])
        df = df.dropna(subset=['latitude'])

        # Remove extra padding from column names
        df.columns = df.columns.str.strip()
        df.head()

        map_html = folium.Map(
            location=[df['latitude'].mean(), df['longitude'].mean()],
            zoom_start=4)

        # Cluster markers interactively
        mc = MarkerCluster()

        # Creating a Marker for each point in df_sample.
        for row in df.itertuples():
            if (row.latitude != None and row.longitude != None):
                mc.add_child(
                    folium.Marker(location=[row.latitude, row.longitude]))

        map_html.add_child(mc)

        outPath = os.path.dirname(__file__).strip(
            'visualizations') + 'templates/visualizations/map.html'

        map_html.save(outPath)
def executeMaskMap():
    my_info_df = getMaskStoreInfo()
    data_for_draw = my_info_df.loc[:, ['name', 'latitude', 'longitude']]
    data_for_draw_except_nan = data_for_draw.dropna()

    sales_dict = getMaskStoreSalesInfo()

    my_store_and_sales_info_df = mergeSalesInfobyStoreCode(
        sales_dict, my_info_df)
    data_for_draw2 = my_store_and_sales_info_df.loc[:, [
        'name', 'latitude', 'longitude', 'remain_stat'
    ]]
    data_for_draw2_nan = data_for_draw2.dropna()

    # 판매 중지 데이터 없애기
    data_for_draw_except_nan2 = data_for_draw2_nan[
        data_for_draw2_nan['remain_stat'] != 'break']

    map_hs2 = folium.Map((37.3402849, 126.7313189), zoom_start=15)
    # minimap = plugins.Minimap()
    # map_hs2.add_child(minimap)

    mc2 = MarkerCluster()

    names = list(data_for_draw_except_nan2['name'])
    latitudes = list(data_for_draw_except_nan2['latitude'])
    longitudes = list(data_for_draw_except_nan2['longitude'])
    remain_stats = list(data_for_draw_except_nan2['remain_stat'])

    for i in tqdm(range(len(names))):
        mc2.add_child(
            folium.Marker(location=[latitudes[i], longitudes[i]],
                          icon=folium.Icon(color=color_dic[remain_stats[i]]),
                          tooltip=names[i],
                          popup=names[i] + ' ' +
                          remain_stat_kor[remain_stats[i]]))
        map_hs2.add_child(mc2)
    map_hs2.save("./mask_store_total.html")
示例#30
0
    def build_marker_cluster(m, df, category):

        dff = df.dropna(axis=0, how='any', subset=['Latitude',
                                                   'Longtitude']).copy()

        if category == 'Volunteers':
            dff = dff.loc[(dff.Health == 'Yes') & (dff.Availability == 'Yes')]
            marker_color = '#00d700'
        elif category == 'Requests':
            marker_color = '#d77a00'

        #add marker cluster
        mc = MarkerCluster(name=translator(category, language),
                           control=True,
                           overlay=True,
                           showCoverageOnHover=False)

        #add circle markers
        for idx, row in dff.iterrows():

            dense_cities = [
                'Montreal', 'Toronto', 'Ottawa', 'Montréal', 'Cote St Luc',
                'Gatineau'
            ]  #HACK: make people outside major clusters reflect their true radius
            if category == 'Volunteers' and row[
                    'City/Town'] not in dense_cities:
                radius = row['Radius'] * 1000
            else:
                radius = 250

            mc.add_child(
                folium.Circle(radius=radius,
                              location=[row['Latitude'], row['Longtitude']],
                              popup=get_popup_html(row, category),
                              color=marker_color,
                              fill=True,
                              fill_color=marker_color)).add_to(m)