コード例 #1
0
ファイル: base.py プロジェクト: IHackPy/pyntxos
def make_and_save_map(filename):

    m = folium.Map(location=[43.2590929, -2.9244257], zoom_start=20)

    tooltip = "Click me!"

    with open(filename, 'r') as file_:
        data = json.load(file_)['data']

    for i in data:
        folium.Marker(
            [i["latitude"], i["longitude"]],
            popup=f"<i>{i['name']}</i>\n{i['address']}",
            tooltip=tooltip,
        ).add_to(m)

    for n in range(len(data) - 1):
        folium.ColorLine(
            [
                (data[n]["latitude"], data[n]["longitude"]),
                (data[n + 1]["latitude"], data[n + 1]["longitude"]),
            ],
            [1],
            weight=3,
            colormap=["green", "red"],
        ).add_to(m)

    return m
コード例 #2
0
def Display_itinerary(Itinerary):
    if Itinerary == False:
        return None

    # Create map of Paris and add departure and arrival points
    Map = folium.Map(location=[48.852347, 2.3181518], zoom_start=12)
    folium.Marker(coordinates_dict[Itinerary[0][0]], tooltip = "Départ : {} à {}".format(display_dict[Itinerary[0][0]], convert_hour(Itinerary[0][3])), \
                    icon=folium.Icon(icon='home')).add_to(Map)
    folium.Marker(coordinates_dict[Itinerary[-1][1]], tooltip = "Arrivée : {} à {}".format(display_dict[Itinerary[-1][1]], convert_hour(Itinerary[-1][3])), \
                    icon = folium.Icon(icon='flag')).add_to(Map)

    # Display itinerary
    coordinates_list = []
    colors_list = []
    color = 1
    for t in Itinerary:
        coordinates_list.append(coordinates_dict[t[0]])
        if display_dict[t[0]] == display_dict[t[1]]:  # Change of line
            color += 1
            #connecting point
            folium.Marker(coordinates_dict[t[1]], \
                        tooltip = "{} / Changement - Ligne {}, Direction {}".format(display_dict[t[1]], display_line(t[1]), display_direction(t[1]), convert_hour(t[3])), \
                        icon = folium.Icon(icon = 'transfer')).add_to(Map)
        colors_list.append(color)

    coordinates_list.append(coordinates_dict[t[1]])
    folium.ColorLine(coordinates_list,
                     colors=colors_list,
                     weight=10,
                     opacity=1).add_to(Map)
    Map.save('Itinerary.html')
コード例 #3
0
def plot_speed(gpx_file, csv_file):
    ''' must include ZEROS in the plotting!! '''
    segments = extract_segments(gpx_file)
    df, stats, zeros = create_df(csv_file)
    speed = df['Speed (km/h)'].map(float)
    rolling_ave = np.convolve(speed, np.ones((10, )) / 10, mode='valid')

    centerY = np.mean([c[0] for c in segments])
    centerX = np.mean([c[1] for c in segments])

    min_col = rolling_ave.min()
    max_col = rolling_ave.max()

    colormap = linear.viridis.scale(min_col, max_col)

    base = folium.Map(location=(centerY, centerX),
                      tiles='cartoDBpositron',
                      width='100%',
                      height='100%')

    folium.ColorLine(positions=segments,
                     colors=rolling_ave,
                     colormap=colormap,
                     weight=4).add_to(base)

    colormap.caption = 'Km/h'
    colormap.add_to(base)

    return base
コード例 #4
0
ファイル: test_features.py プロジェクト: zoeyherm/folium
def test_color_line():
    m = Map([22.5, 22.5], zoom_start=3)
    color_line = folium.ColorLine([[0, 0], [0, 45], [45, 45], [45, 0], [0, 0]],
                                  [0, 1, 2, 3],
                                  colormap=['b', 'g', 'y', 'r'],
                                  nb_steps=4,
                                  weight=10,
                                  opacity=1)
    m.add_child(color_line)
    m._repr_html_()
コード例 #5
0
    def make_map(self, save_path):
        '''
        This function uses folium to create a distribution map
        :param save_path: Path to save the map
        :return: None
        '''
        self.logger.debug("Making map with cellsite distribution")
        map = folium.Map(location=[17.777612, 83.250768],
                         titles="OpenStreetMap",
                         zoom_start=12)

        for region in self.tower_distribution.values():
            users = region['users']
            base_station = region['base_station']
            cell_sites = region['cell_sites']
            color = next(self.colors)

            for user in users:
                user_marker = folium.Circle(location=user,
                                            radius=0.25,
                                            color=color,
                                            fill=True,
                                            fill_color=color,
                                            tooltip="user")
                map.add_child(user_marker)

            for cell_site in cell_sites:
                cell_site_marker = folium.Marker(location=cell_site,
                                                 icon=folium.Icon(
                                                     icon="tower",
                                                     color="darkblue"))
                map.add_child(cell_site_marker)

                cell_site_circle = folium.Circle(location=cell_site,
                                                 radius=800,
                                                 color=color,
                                                 fill=True,
                                                 tooltip="Cellsite")
                map.add_child(cell_site_circle)

                backhaul_line = folium.ColorLine(positions=(base_station,
                                                            cell_site),
                                                 colors=[0],
                                                 colormap=[color, "black"],
                                                 weight=2,
                                                 tooltip="Backhaul")
                map.add_child(backhaul_line)

            base_station_marker = folium.Marker(location=base_station,
                                                icon=folium.Icon(
                                                    icon="home",
                                                    color="orange"))
            map.add_child(base_station_marker)

        map.save(save_path)
コード例 #6
0
def add_to_map(lat_lon, ratio, world_map):
    minima = min(ratio)
    maxima = max(ratio)
    test = cm.LinearColormap(['red', 'blue'], vmin=minima, vmax=maxima)
    colorline = folium.ColorLine(lat_lon,
                                 ratio,
                                 colormap=test,
                                 nb_steps=len(lat_lon),
                                 weight=4,
                                 opacity=1)
    world_map.add_child(colorline)
コード例 #7
0
def make_and_save_map(data, num_restaurants=None, phone_number=False):

    m = folium.Map(location=[43.2590929, -2.9244257])  # , zoom_start=20)

    tooltip = "Click me!"

    if num_restaurants:
        if not isinstance(num_restaurants, int):
            raise ValueError("`num_restaurants` must be integer or None!")

    if isinstance(num_restaurants, int):
        if num_restaurants < 1:
            raise ValueError("`num_restaurants` must be at least 1!")

    if num_restaurants:
        data = data[:num_restaurants]

    popup = "<i>{name}</i>\n{address}"
    if phone_number:
        popup += "\n+34 {number}"

    for i in data:
        folium.Marker(
            [i["latitude"], i["longitude"]],
            popup=popup.format(
                name=i["name"],
                address=i["address"],
                number=i["telephone"].replace(" ", ""),
            ),
            tooltip=tooltip,
        ).add_to(m)

    for n in range(len(data) - 1):
        folium.ColorLine(
            [
                (data[n]["latitude"], data[n]["longitude"]),
                (data[n + 1]["latitude"], data[n + 1]["longitude"]),
            ],
            [1],
            weight=3,
            colormap=["green", "red"],
        ).add_to(m)
    m.fit_bounds(
        [
            [min([i["latitude"] for i in data]), min([i["longitude"] for i in data])],
            [max([i["latitude"] for i in data]), max([i["longitude"] for i in data])],
        ]
    )

    return m
コード例 #8
0
def add_lines_to_map(map, pic_data, config):
    # make scalar color map
    scmap = cm.ScalarMappable(norm=mplc.Normalize(vmin=0, vmax=6),
                              cmap=cm.YlOrRd)

    speed_deq = deque(maxlen=config['hops_avg_speed'])

    used_pic_count = 0
    for pic in pic_data:
        lat, lon = get_coordinates(pic)
        curr_dtime = get_time_pic(pic)

        folium.Circle(
            radius=config['standalone_pic_size'],
            location=[lat, lon],
            color='yellow',
            fill=True,
            opacity=0.7,
        ).add_to(map)

        # once we have more than one pic on the map, start drawing lines between them
        if used_pic_count > 0:
            time_diff = get_time_diff(curr_dtime, prev_dtime)
            distance = geopy.distance.distance((lat, lon),
                                               (prev_lat, prev_lon)).km

            speed = distance / time_diff
            speed_deq.appendleft(distance / time_diff)

            # make the speed averaged over the last "hops_avg_speed" number of steps
            if len(speed_deq) == config['hops_avg_speed']:
                avg_speed = float(sum(speed_deq)) / len(speed_deq)
                speed = avg_speed

            # add line of the color
            map.add_child(
                folium.ColorLine([[lat, lon], [prev_lat, prev_lon]], [0],
                                 colormap=[
                                     mplc.to_hex([*scmap.to_rgba(speed)]),
                                     mplc.to_hex([*scmap.to_rgba(speed)])
                                 ],
                                 weight=2,
                                 opacity=1))

        prev_lat = lat
        prev_lon = lon
        prev_dtime = curr_dtime
        used_pic_count += 1
コード例 #9
0
def add_colored_line(the_map,
                     segment,
                     color_by,
                     cmap='viridis',
                     line_options=None):
    """Add segment as a colored line to a map.

    Add a line colored by some value to the given map.

    Parameters
    ----------
    the_map : object like :py:class:`folium.folium.Map`
        The map to add the segment to.
    segment : dict
        The segment to add.
    color_by : string
        This string selects what property we will color the segment
        according to.
    cmap : string
        The colormap to use for coloring.
    line_options : dict
        Extra control options for drawing the line.

    """
    zdata = segment[color_by]
    avg = 0.5 * (zdata[1:] + zdata[:-1])
    minz, maxz = min(avg), max(avg)
    uniq = len(set(zdata))
    if uniq < 10:
        levels = uniq + 1
    else:
        levels = 10
    linmap = getattr(branca.colormap.linear, cmap)
    colormap = linmap.scale(minz, maxz).to_step(levels)
    colormap.caption = RELABEL.get(color_by, color_by)
    if line_options is None:
        line_options = {'weight': 6}
    line_options['weight'] = line_options.get('weight', 6)
    line = folium.ColorLine(positions=segment['latlon'],
                            colormap=colormap,
                            colors=avg,
                            control=False,
                            **line_options)
    line.add_to(the_map)
    the_map.add_child(colormap)
コード例 #10
0
ファイル: jr_common.py プロジェクト: vxuni/jupyter_running
def make_folium_map_with_run(runt: pd.DataFrame) -> folium.Map:
    """Given a dataframe with .fit data, show run route on a map."""

    # OpenStreetMap really nice, but CartoDB Positron lighter and better for overlaid route
    map = folium.Map(location=[np.mean(runt.lat), np.mean(runt.lon)], tiles="cartodbpositron")

    folium.Marker(
        location=[runt.lat[0], runt.lon[0]],
        popup='Start',
        icon=folium.Icon(color='green')
    ).add_to(map)

    # Blues_09
    cm: branca.colormap.LinearColormap = branca.colormap.linear.Oranges_05
    cm = cm.scale(np.min(runt.cad), np.max(runt.cad))
    print(cm.vmin, cm.vmax)

    poly_line = folium.ColorLine(
        list(zip(runt.lat.values, runt.lon.values)),
        colors=runt.cad.values, colormap=cm).add_to(map)

    # https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.idxmax.html
    # True is > False, so idxmax() will return idx of first occurrence of True
    for km in range(1, int(runt.dist.max() / 1000) + 1):
        idx = (runt.dist > km * 1000).idxmax()

        idx_1km_back = (runt.dist > (runt.dist[idx] - 1000)).idxmax()

        time_per_km = runt.time[idx] - runt.time[idx_1km_back]

        info_msg = (
            f"Stats<br>"
            f"distance <b>{runt.dist[idx]}</b>"
        )

        if time_per_km is not None:
            info_msg += f"<br>1km split: <b>{time_per_km:.2f}/km</b>"

        folium.Marker((runt.lat[idx], runt.lon[idx]), popup=info_msg).add_to(map)
        prev_km_idx = idx

    map.fit_bounds(poly_line.get_bounds())

    return map
コード例 #11
0
ファイル: main.py プロジェクト: PandaRec/metro
        kk.append(j.get_lng())
        temp_list.append(kk)
    #color_line = folium.ColorLine(temp_list, colors='blue', colormap='blue',
                                  #nb_steps=4, weight=5, opacity=0.7).add_to(map)
    color_line = folium.ColorLine(temp_list,[0],colormap=['blue','orange']).add_to(map)
"""
for i in all_stations_all_lines:
    for j in range(1,len(i)):
        lat1=i[j-1].get_lat()
        lat2=i[j].get_lat()
        lng1=i[j-1].get_lng()
        lng2=i[j].get_lng()
        color=i[j].get_color()


        color_line = folium.ColorLine([[lat1,lng1],[lat2,lng2]], [0], colormap=[i[j].get_color(), 'orange'],nb_steps=12, weight=5, opacity=0.7).add_to(map)

"""
color_line = folium.ColorLine(
        [[0, 0], [0, 45], [45, 45], [45, 0], [0, 0]],
        [0, 1, 2, 3],
        colormap=['b', 'g', 'y', 'r'],
        nb_steps=4,
        weight=10,
        opacity=1)
        """
"""
color_line = folium.ColorLine([[60.050182,30.443045],[60.034969,30.418224]],[0,1],colormap=['b','g'],nb_steps=4,
        weight=5,
        opacity=0.7)
color_line.add_to(map)
コード例 #12
0
myMap = folium.Map(location=[25.053, 121.575], zoom_start=12,
                   prefer_canvas=True, tiles="cartodbpositron")

group1 = folium.FeatureGroup(name="5 <= nums <= 100")
group2 = folium.FeatureGroup(name="101 <= nums <= 500")
group3 = folium.FeatureGroup(name="501 <= nums <= 1000")
group4 = folium.FeatureGroup(name="nums > 1000")

for k, v in info.items():
    Rent, Return = k.split(":")

    if v < 5:
        continue
    elif 5 <= v <= 100:
        group1.add_child(folium.ColorLine(convert_float([data[Rent], data[Return]]), colors=[
            0, 1], colormap=['#007799', '#007799'], opacity=0.4, weight=0.5))
    elif 101 <= v <= 500:
        group2.add_child(folium.ColorLine(convert_float([data[Rent], data[Return]]), colors=[
            0, 1], colormap=['#00AAAA', '#00AAAA'], weight=1.2))
    elif 501 <= v <= 1000:
        group3.add_child(folium.ColorLine(convert_float([data[Rent], data[Return]]), colors=[
            0, 1], colormap=['#00FFCC', '#00FFCC'], opacity=0.8, weight=1.8))
    else:
        group4.add_child(folium.ColorLine(convert_float([data[Rent], data[Return]]), colors=[
            0, 1], colormap=['#BBFF00', '#BBFF00'], weight=3))


myMap.add_child(group1)
myMap.add_child(group2)
myMap.add_child(group3)
myMap.add_child(group4)
コード例 #13
0
# In[20]:

#We can visualize the network connections in the map locating each pair of nodes that are connected
map_network = folium.Map(location=[-23.541517, -46.629454], zoom_start=12)

for i, j in enumerate(result.VenuesTips):
    e = result.Venue[i].split(',')
    if j == 1: break
    for x in range(0, j):
        e1 = pos[e[x]]
        for z in range(x + 1, j):
            e2 = pos[e[z]]
            folium.ColorLine([e1, e2],
                             colors=[0, 0, 0],
                             colormap=['b', 'black'],
                             weight=0.5,
                             opacity=0.8).add_to(map_network)
for lat, lng, venue, categ in zip(SPwinebars['Latitude'],
                                  SPwinebars['Longitude'], SPwinebars['Venue'],
                                  SPwinebars['Category']):
    label = '{}, {}'.format(venue, categ)
    label = folium.Popup(label, parse_html=True)
    folium.CircleMarker([lat, lng],
                        radius=1,
                        popup=label,
                        color='black',
                        fill=True,
                        fill_color='#3186cc',
                        fill_opacity=0.7).add_to(map_network)