コード例 #1
0
ファイル: FunctionsIMAP.py プロジェクト: Apoorb/IMAP-PyCode
def add_points_AB2(mapobj, gdf, popup_field_list):
    #Source: https://github.com/python-visualization/folium/pull/376
    #Source IMP: https://github.com/python-visualization/folium/blob/master/examples/MarkerCluster.ipynb
    # Create empty lists to contain the point coordinates and the point pop-up information
    coords, popups = [], [] 
    # Loop through each record in the GeoDataFrame
    for i, row in gdf.iterrows():
        # Append lat and long coordinates to "coords" list
        coords.append([row.geometry.y, row.geometry.x])
        # Create a string of HTML code used in the IFrame popup
        # Join together the fields in "popup_field_list" with a linebreak between them
        label = '<br>'.join([field + ': ' + str(row[field]) for field in popup_field_list])
        popups.append(label)
        icon_create_function = """\
    function(cluster) {
        return L.divIcon({
        html: '<b>' + cluster.getChildCount() + '</b>',
        className: 'marker-cluster marker-cluster-large',
        iconSize: new L.Point(20, 20)
        });
    }"""
    marker_cluster = MarkerCluster(
    locations=coords, popups=popups,
    name='1000 clustered icons',
    overlay=True,
    control=True,
    icon_create_function=icon_create_function)
    marker_cluster.add_to(mapobj)
    folium.LayerControl().add_to(mapobj)
    return mapobj
コード例 #2
0
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
コード例 #3
0
def get_friends_locations(user_screen_name, bearer_token) -> str:
    '''
    Gets user name from twitter, returns name of file with created html map.
    '''

    data = get_friends_list(user_screen_name, bearer_token)
    try:
        info_on_users = [(user['name'], user['location'])
                         for user in data['users']]
    except KeyError:
        return None
    points_to_put_on_map = [(name, get_location(address))
                            for name, address in info_on_users]
    points_to_put_on_map = [(name, tuple(map(float, coordinates)))
                            for name, coordinates in points_to_put_on_map
                            if coordinates]

    locations_map = folium.Map(tiles='stamenterrain')
    friends = MarkerCluster()
    for name, coordinates in points_to_put_on_map:
        folium.Marker(coordinates, popup=name,
                      icon=folium.Icon(color='red')).add_to(friends)
    friends.add_to(locations_map)

    return locations_map  # folium Map instance
コード例 #4
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_
コード例 #5
0
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)
コード例 #6
0
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()
コード例 #7
0
def create_map():
    df = load_data()
    latitude = df['latitude']
    longitude = df['longitude']
    popups = df['comment']
    n_rivals = df['n_rivals']
    vmax = df['n_rivals'].max()
    m = folium.Map(location=[55.7522, 37.6156])
    marker_cluster = MarkerCluster()
    marker_cluster.add_to(m)
    folium.LayerControl().add_to(m)
    for lat, lon, popup, n_rival in zip(latitude, longitude, popups, n_rivals):
        if 'Калейдоскоп' in popup:
            popup = 'burgerking\nг.Москва, Химкинский бульвар, д. 7/23 ТЦ Калейдоскоп, 4 этаж\nКонкурентов: 3'
        folium.Marker(location=[lat, lon],
                      popup=popup,
                      icon=folium.Icon(
                          color=color_change(n_rival))).add_to(marker_cluster)
    colormap = StepColormap(['green', 'blue', 'orange', 'red'],
                            vmin=0,
                            vmax=vmax,
                            index=[0, 1, 4, 8, vmax]).scale(0, vmax)
    today = date.today()
    colormap.caption = f'Количество конкурентов ({today.strftime("%B, %Y")})'
    colormap.add_to(m)
    m.save("Moscow_Map.html")
コード例 #8
0
ファイル: maps.py プロジェクト: robzwolf/vhacks-2018
def create_map(jdata, center_coords):
    # Loads data from csv into pandas dataframe
    with open("yelp_businesses.json") as f:
        jdata = json.loads(f.read())
        center_coords = jdata["region"]["center"]["latitude"], \
                        jdata["region"]["center"]["longitude"]
    df = pd.read_json(json.dumps(jdata["health"]))
    df.head(2)
    # print(df.head(3))

    # creates an empty map zoomed in Rome
    print(center_coords)
    working_map = folium.Map(location=center_coords, zoom_start=12)

    # creates a marker cluster
    cluster = MarkerCluster().add_to(working_map)

    # Add markers to cluster, iterating over dataframe
    for index, row in df.iterrows():
        folium.Marker(
            location=[
                row["coordinates"]["latitude"], row["coordinates"]["longitude"]
            ],
            popup="{0}: {1} stars".format(row["name"], row["rating"]),
            icon=folium.Icon(color='green', icon='ok-sign'),
        ).add_to(cluster)

    cluster.add_to(working_map)
    display(working_map)
    working_map.save(outfile="../templates/map.html")
コード例 #9
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
コード例 #10
0
def create_potential_duplicates_map(base_map, near_duplicates: pd.DataFrame):
    if near_duplicates is None:
        return

    marker_cluster = MarkerCluster(control=False)
    marker_cluster.add_to(base_map)
    sub_group = FeatureGroupSubGroup(marker_cluster,
                                     name='Near-Duplicate Locations',
                                     control=True,
                                     show=True)

    # # add markers
    # ['LocationA', 'NameA', 'coordinatesA', 'LocationB', 'NameB', 'coordinatesB', 'dist_m']
    for ix, row in near_duplicates.iterrows():
        for is_row_a in [True, False]:
            dup_location_marker(row, is_row_a).add_to(sub_group)
        # add lines
        folium.PolyLine((row.coordinatesA, row.coordinatesB),
                        color="red",
                        weight=2.5,
                        opacity=1).add_to(sub_group)

    sub_group.add_to(base_map)

    return None
コード例 #11
0
    def add_markers_as_cluster(self, list_objs):
        """

        :param list_objs: dictionary of stations.handler.List
        :param group_name:
        :return:
        """
        for list_name, item in list_objs.items():
            fg = self.get_group(name=list_name,
                                add_to_map=True,
                                return_group=True)

            mc = MarkerCluster()

            for idx in range(item.length):
                html_obj = self.get_html_object(item, idx)
                popup = self.get_popup(html_obj)
                marker = self.get_marker(
                    [item.get('lat_dd')[idx],
                     item.get('lon_dd')[idx]],
                    popup=popup,
                    icon=folium.Icon(
                        color='blue' if list_name == 'master' else 'red',
                        icon='map-marker'),
                    tooltip=item.get('statn')[idx] or 'Click me!')
                marker.add_to(mc)
            mc.add_to(fg)
コード例 #12
0
    def add_markers_as_cluster(self, stations_list):
        """
        :param stations_dict:
        :return:
        """
        fg = self.get_group(name='stations',
                            add_to_map=True,
                            return_group=True)

        mc = MarkerCluster()

        for statn_dict in stations_list:
            if statn_dict.get('stationName') and statn_dict.get(
                    'wgs84Latitude') and statn_dict.get('wgs84Longitude'):
                html_obj = self.get_html_object(statn_dict)
                popup = self.get_popup(html_obj)
                marker = self.get_marker(
                    [
                        statn_dict.get('wgs84Latitude'),
                        statn_dict.get('wgs84Longitude')
                    ],
                    popup=popup,
                    icon=folium.Icon(
                        color='blue' if statn_dict.get('stationIdentityTypeKey'
                                                       ) ==
                        'oceanografisktNummer' else 'green' if statn_dict.
                        get('stationIdentityTypeKey') ==
                        'klimatnummer' else 'red'),
                    tooltip=statn_dict.get('stationName') or 'Click me!')
                marker.add_to(mc)
        mc.add_to(fg)
コード例 #13
0
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')
コード例 #14
0
ファイル: views.py プロジェクト: updine/updine.github.io
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)
コード例 #15
0
def addMarkers(m, df, variable, unit):
    normalized = normalize(df[variable])
    mc = MarkerCluster(name=variable+unit, options={'spiderfyOnMaxZoom':'False', 'disableClusteringAtZoom' : '4'})
    for i in range(len(df)):
        folium.CircleMarker(location=[df.lat[i], df.lon[i]], radius=(normalized[i] * 10), tooltip='%s: %f%s <br> date: %s' % (variable, df[variable][i], unit, df['time'][i]), color='darkOrange', fill=True).add_to(mc)
    mc.add_to(m)
    return m
コード例 #16
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)
コード例 #17
0
    def add_radius_circles_as_cluster(self, list_objs):
        """

        :param list_objs: dictionary of stations.handler.List
        :param group_name:
        :return:
        """
        for list_name, item in list_objs.items():
            fg = self.get_group(name='-'.join([list_name, 'radius']),
                                add_to_map=True,
                                return_group=True)
            mc = MarkerCluster()
            check = False
            for idx in range(item.length):
                if item.has_attribute('radius'):
                    if item.get('radius')[idx]:
                        check = True
                        folium.Circle(
                            tuple([
                                item.get('lat_dd')[idx],
                                item.get('lon_dd')[idx]
                            ]),
                            radius=int(item.get('radius')[idx]),
                            fill_color='#3186cc',
                            weight=.5,
                        ).add_to(mc)
            if check:
                mc.add_to(fg)
コード例 #18
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
コード例 #19
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
コード例 #20
0
ファイル: mapgen.py プロジェクト: branchmaster/atmapper
    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)
コード例 #21
0
ファイル: main.py プロジェクト: coolum001/crashmapqld
def add_clusters(folium_map: folium.Map) -> None:
    '''
    annotate_map: add clustered fatal crash markers to map

    Parameters:
    folium_map: map to which markers are to be added as Layer

    Returns:
    None

    Side Effects:
    Adds markers to input map as a Layer

    '''
    global fatal
    lat = list(fatal['Crash_Latitude_GDA94'])
    lng = list(fatal['Crash_Longitude_GDA94'])
    dead_count = list(fatal['Count_Casualty_Fatality'])
    crash_nature = list(fatal['Crash_Nature'])
    crash_type = list(fatal['Crash_Type'])

    FATAL_MARKER_SIZE = 10
    FATAL_MARKER_FILL_OPACITY = 0.25

    # create a marker cluster layer
    clusters = MarkerCluster(name='Clustered Markers', show=False, control=True)

    # for each fatal crash, add marker to layer
    # marker is translucent so zoom out will look ok

    # Note: crash_type not used in this version
    
    for marker_y, marker_x, marker_dc, marker_cn, marker_ct in zip(
        lat, lng, dead_count, crash_nature, crash_type
    ):
        circ_mkr = folium.CircleMarker(
            location=[marker_y, marker_x],
            radius=FATAL_MARKER_SIZE,
            color='red',
            fill=True,
            fill_color='red',
            fillOpacity=FATAL_MARKER_FILL_OPACITY,
            opacity=FATAL_MARKER_FILL_OPACITY,
            tooltip=f'{marker_dc} Dead',
            popup=marker_cn,
        )

        circ_mkr.add_to(clusters)
    # end for

    # add clustered markers to map
    clusters.add_to(folium_map)

    return None
コード例 #22
0
ファイル: markerMap.py プロジェクト: nayan2000/SIH2019
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)
コード例 #23
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")
コード例 #24
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
コード例 #25
0
    def draw(self):
        """ Gera um mapa de cluster a partir das opções enviadas """
        # http://localhost:5000/charts/cluster?from_viewconf=S&au=2927408&card_id=mapa_prev_estado_cluster&observatory=te&dimension=prevalencia&as_image=N
        chart_options = self.options.get('chart_options')
        # TODO - [REMOVE] Used just for debugging
        # options["headers"] = [
        #     {'text': 'nm_municipio', "value": 'nm_municipio'},

        #     {'text': 'te_rgt_agr_sum_vl_indicador', "value": 'te_rgt_agr_sum_vl_indicador'},
        #     {'text': 'te_rgt_api_calc_min_part', "value": 'te_rgt_api_calc_min_part'},
        #     {'text': 'te_rgt_api_calc_max_part', "value": 'te_rgt_api_calc_max_part'},
        #     {
        #         'text': 'te_rgt_api_calc_ln_norm_pos_part',
        #         "value": 'te_rgt_api_calc_ln_norm_pos_part'
        #     },

        #     {'text': 'te_res_agr_sum_vl_indicador', "value": 'te_res_agr_sum_vl_indicador'},
        #     {'text': 'te_res_api_calc_min_part', "value": 'te_res_api_calc_min_part'},
        #     {'text': 'te_res_api_calc_max_part', "value": 'te_res_api_calc_max_part'},
        #     {
        #         'text': 'te_res_api_calc_ln_norm_pos_part',
        #         "value": 'te_rgt_api_calc_ln_norm_pos_part'
        #     },

        #     {'text': 'te_nat_agr_sum_vl_indicador', "value": 'te_nat_agr_sum_vl_indicador'},
        #     {'text': 'te_nat_api_calc_min_part', "value": 'te_nat_api_calc_min_part'},
        #     {'text': 'te_nat_api_calc_max_part', "value": 'te_nat_api_calc_max_part'},
        #     {
        #         'text': 'te_nat_api_calc_ln_norm_pos_part',
        #         "value": 'te_nat_api_calc_ln_norm_pos_part'
        #     }
        # ]

        result = self.pre_draw(self.get_tooltip_data())

        grouped = self.dataframe.groupby(
            chart_options.get('layer_id', 'cd_indicador'))
        show = True  # Shows only the first layer
        for group_id, group in grouped:
            chart = MarkerCluster(
                locations=group[self.get_location_columns()].values.tolist(),
                name=ViewConfReader.get_layers_names(
                    self.options.get('headers')).get(group_id),
                show=show,
                popups=group['tooltip'].tolist())

            show = False
            chart.add_to(result)

        result = self.add_au_marker(result, self.options.get('au'))

        return self.post_adjustments(result)
コード例 #26
0
    def plot_all_data(self,
                      data,
                      loc_col,
                      ctry_col,
                      lat_col,
                      lng_col,
                      clr='blue',
                      as_cluster=True):
        """
        Create markers for all of the locational data points.

        :param data: filepath (.csv or .xlsx extension) or dataframe.
        :type data: str or DataFrame.
        :param loc_col: name of location column.
        :type loc_col: str.
        :param ctry_col: name of country column.
        :type ctry_col: str.
        :param lat_col: name of latitude column.
        :type lat_col: str.
        :param lng_col: name of longitude column.
        :type lng_col: str.
        :param clr: color of the markers.
        :type clr: str.
        :param as_cluster: indicate whether the markers will be saved in a cluster or not.
        :type as_cluster: bool.
        :return: all of the created markers.
        :rtype: list of folium.Marker if ``as_cluster=False`` or a folium.MarkerCluster if ``as_cluster=True``.
        """
        df = read_data(data, {loc_col, ctry_col, lat_col, lng_col})

        if as_cluster:
            markers = MarkerCluster()
        else:
            markers = []

        for (index, row) in df.iterrows():
            if pd.notnull(row[lat_col]) and pd.notnull(row[lng_col]):
                lat = row[lat_col]
                lng = row[lng_col]
                location = self.format_popup(row[loc_col], row[ctry_col])

                marker = self.plot_point(lat=lat,
                                         lng=lng,
                                         desc='%s, %s - (%.2f, %.2f)' %
                                         (location[0], location[1], lat, lng),
                                         clr=clr)
                if as_cluster:
                    marker.add_to(markers)
                else:
                    markers.append(marker)

        return markers
コード例 #27
0
def addTrackMarkers(m, df, cruise):
    mc = MarkerCluster(name=cruise,
                       options={
                           'spiderfyOnMaxZoom': 'False',
                           'disableClusteringAtZoom': '4'
                       })
    for i in range(len(df)):
        folium.CircleMarker(location=[df.lat[i], df.lon[i]],
                            radius=(2),
                            color='darkOrange',
                            fill=True).add_to(mc)
    mc.add_to(m)
    return m
コード例 #28
0
def gerar_mapa(request):

    ip = get('https://api.ipify.org').text
    response1 = DbIpCity.get(ip, api_key='free')
    #print(response1)
    m = folium.Map([response1.latitude, response1.longitude],
                   tiles='cartodbpositron',
                   zoom_start=5,
                   prefer_canvas=True)

    # Minimapa
    minimap = plugins.MiniMap(toggle_display=True)
    m.add_child(minimap)

    # add full screen button to map
    plugins.Fullscreen(position='topright').add_to(m)

    # Declaring points of latitude and longitude
    #my_locations = [(response1.latitude, response1.longitude),(-25.45,-49.34),(-25.45,-49.34)]
    doc_ref = db.collection('Pegasus').document(u'Exame')
    docs = doc_ref.get()
    exp = docs.to_dict()
    print(exp['Geopoints'][0])
    print(exp['Geopoints'][1])
    my_locations = [(exp['Geopoints'][0], exp['Geopoints'][1])]
    marker_cluster = MarkerCluster(my_locations)
    marker_cluster.add_to(m)

    #HeatMap(df).add_to(m)
    m.save('lab/templates/lab/mapa.html')

    table_file = open('lab/templates/lab/mapa.html')
    map_lines = table_file.readlines()
    table_file.close()

    table_file = open('lab/templates/lab/mapa.html', 'w+')
    first_lines = [
        "{% extends 'lab/base.html'%} \n",
        #"{% load static %} \n",
        "{% block content %} \n",
        "{% if user.is_authenticated %} \n"
    ]
    end_lines = ["\n{% endif %}\n", "{% endblock %}"]
    table_file.writelines(first_lines)
    table_file.writelines(map_lines)
    table_file.close()
    table_file = open('lab/templates/lab/mapa.html', 'a+')
    table_file.writelines(end_lines)
    table_file.close()

    return render(request, 'lab/mapa.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
コード例 #30
0
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