コード例 #1
0
def map_stops(feed: "Feed",
              stop_ids: Iterable[str],
              stop_style: dict = STOP_STYLE):
    """
    Return a Folium map showing the given stops of this Feed.
    If some of the given stop IDs are not found in the feed, then raise a ValueError.
    """
    # Initialize map
    my_map = fl.Map(tiles="cartodbpositron")

    # Create a feature group for the stops and add it to the map
    group = fl.FeatureGroup(name="Stops")

    # Add stops to feature group
    stops = feed.stops.loc[lambda x: x.stop_id.isin(stop_ids)].fillna("n/a")

    # Add stops with clustering
    callback = f"""\
    function (row) {{
        var imarker;
        marker = L.circleMarker(new L.LatLng(row[0], row[1]),
            {stop_style}
        );
        marker.bindPopup(
            '<b>Stop name</b>: ' + row[2] + '<br>' +
            '<b>Stop code</b>: ' + row[3] + '<br>' +
            '<b>Stop ID</b>: ' + row[4]
        );
        return marker;
    }};
    """
    fp.FastMarkerCluster(
        data=stops[[
            "stop_lat", "stop_lon", "stop_name", "stop_code", "stop_id"
        ]].values.tolist(),
        callback=callback,
        disableClusteringAtZoom=14,
    ).add_to(my_map)

    # for prop in stops.to_dict(orient="records"):
    #     # Add stop
    #     lon = prop["stop_lon"]
    #     lat = prop["stop_lat"]
    #     fl.CircleMarker(
    #         location=[lat, lon],
    #         popup=fl.Popup(hp.make_html(prop)),
    #         **stop_style,
    #     ).add_to(group)

    # group.add_to(my_map)

    # Fit map to stop bounds
    bounds = [
        (stops.stop_lat.min(), stops.stop_lon.min()),
        (stops.stop_lat.max(), stops.stop_lon.max()),
    ]
    my_map.fit_bounds(bounds, padding=[1, 1])

    return my_map
コード例 #2
0
ファイル: location.py プロジェクト: annarofl/nextSighting
def visualize_locations(df):

    folium_map = folium.Map(location=[30.1690815, -97.83705505214803],
                            zoom_start=1,
                            tiles='CartoDB dark_matter')

    plugins.FastMarkerCluster(data=list(
        zip(df['latitude'].values, df['longitude'].values))).add_to(folium_map)
    folium.LayerControl().add_to(folium_map)
    folium_map.save("loc.html")
コード例 #3
0
ファイル: routes.py プロジェクト: groovedrm/python-wiki
def map():
    map = folium.Map(location=[37.852995, -120.999986],
                     tiles='Stamen Terrain',
                     detect_retina=True,
                     prefer_canvas=True,
                     zoom_start=4)

    startLat_1 = 34.286565
    startLong_1 = -118.561021
    clusterData_1 = [retLatLong(startLat_1, startLong_1) for i in range(100)]
    plugins.FastMarkerCluster(clusterData_1).add_to(map)
    # markerCluster = folium.plugins.FastMarkerCluster(clusterData_1).add_to(map)

    map_path = app.root_path + '/' + 'static/map_test.html'
    map.save(map_path)

    return render_template('map.html')
コード例 #4
0
def test_fast_marker_cluster():
    n = 100
    np.random.seed(seed=26082009)
    data = np.array([
        np.random.uniform(low=35, high=60, size=n),  # Random latitudes.
        np.random.uniform(low=-12, high=30, size=n),  # Random longitudes.
        range(n),  # Popups.
    ]).tolist()
    m = folium.Map([45., 3.], zoom_start=4)
    mc = plugins.FastMarkerCluster(data, callback=None)
    m.add_child(mc)
    m._repr_html_()

    out = m._parent.render()

    # We verify that imports
    assert ('<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.'
            'markercluster/1.0.0/leaflet.markercluster.js"></script>') in out
    assert ('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/'
            'libs/leaflet.markercluster/1.0.0/MarkerCluster.css" />') in out
    assert ('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/'
            'libs/leaflet.markercluster/1.0.0/MarkerCluster.Default.css" />'
            ) in out

    # Verify the script part is okay.
    tmpl = Template("""
        {% macro script(this, kwargs) %}
        (function() {
            var data = {{this._data}};
            var map = {{this._parent.get_name()}};
            var cluster = L.markerClusterGroup();
            {{this._callback}}

            for (var i = 0; i < data.length; i++) {
                var row = data[i];
                var marker = callback(row, popup='names');
                marker.addTo(cluster);
            }

            cluster.addTo(map);
        })();
        {% endmacro %}
    """)

    assert ''.join(tmpl.render(this=mc).split()) in ''.join(out.split())
コード例 #5
0
    data=treedens
    # first value is key in the dataframe, second is the data to display
    ,
    columns=['neighbourhood_name', 'treepersqkm']
    # name of key in json file
    ,
    key_on='feature.properties.name',
    fill_color='BuPu',
    legend_name='# of trees per sq. km',
    highlight=True,
    name='Neighbourhood Tree Density')

fmap_fmc = plugins.FastMarkerCluster(
    tree_vals,
    callback=callback,
    options={
        'spiderfyOnMaxZoom': False
        # will only show individual points at this zoom level or higher
        ,
        'disableClusteringAtZoom': 17,
        'chunkedLoading': True
    },
    name='Tree Locations')

fmap_chor.add_to(fmap)
fmap_fmc.add_to(fmap)
folium.LayerControl().add_to(fmap)
fmap.get_root().html.add_child(folium.Element(legend_html))

fmap.save('index.html')
コード例 #6
0
def _get_map(places):
    def style_list(lname, color):
        if color is None:
            return lname
        else:
            return f'<span style="color:{color}">{lname}</span>'

    callback = """
function (row) {
    const [lat, lon, color, tooltip, popup] = row;
    // const marker = L.marker(
    //     new L.LatLng(lat, lon),
    //     {
    //         color: color,
    //     },
    // );
    const marker = L.circleMarker(
        new L.LatLng(lat, lon),
        {radius: 7,
         color: color,
         fill: true,
         fill_color: color,
       }
    );
    marker.bindPopup(popup);
    marker.bindTooltip(tooltip, {permanent: true});
    //  TODO get url from 4sq?
    return marker;
};
"""
    params = []
    for p in places:
        tooltip = p.name + ' ' + style_list(p.lst, p.color)
        popup = '<br>'.join(p.description.splitlines())
        params.append([p.lat, p.lng, p.color, tooltip, popup])

    import folium # type: ignore
    from folium import plugins as fplugins
    fmap = folium.Map(location=LONDON) # TODO perhaps extract in my.geo or something?
    cluster = fplugins.FastMarkerCluster(
        params,
        callback=callback,
    ).add_to(fmap)
    fplugins.Fullscreen().add_to(fmap)


    legend_parts = []
    for lname, color in INTERESTING.items():
        legend_parts.append(style_list(lname, color))

    # https://medium.com/@bobhaffner/creating-a-legend-for-a-folium-map-c1e0ffc34373
    legend_html = f"""
     <div style=”position: fixed;
     bottom: 50px; left: 50px; width: 100px; height: 90px;
     border:2px solid grey; z-index:9999; font-size:14px;
     “>&nbsp; Legend: {' '.join(legend_parts)}
     </div>
     """

    fmap.get_root().html.add_child(folium.Element(legend_html))
    return fmap
コード例 #7
0
ファイル: end_points_plot.py プロジェクト: vanshc98/CE4032
import folium
from folium import plugins
import pandas as pd

from folium.plugins import FastMarkerCluster

train_data = pd.read_csv('../datasets/Plot.csv')

dummy2 = pd.DataFrame(train_data, columns=['ORIGIN_LAT', 'ORIGIN_LNG'])
dummy2 = dummy2.values  ## convert to Numpy array
d2map = folium.Map(location = [41.15767687592546, -8.615393063941816], zoom_start = 12)
plugins.FastMarkerCluster(dummy2).add_to(d2map)
d2map.save("MarkerPlot.html") 

m = folium.Map(
    location=[41.15767687592546, -8.615393063941816],
    zoom_start=12
)

stationArr = train_data[['DEST_LAT', 'DEST_LNG']].as_matrix()

m.add_child(plugins.HeatMap(stationArr, radius=15))
m.save('DestHeatMap.html')

m2 = folium.Map(
    location=[41.15767687592546, -8.615393063941816],
    zoom_start=12
)

stationArr = train_data[['ORIGIN_LAT', 'ORIGIN_LNG']].as_matrix()
コード例 #8
0
    correct_rows, correct_cols = correct_database.shape
    
    # Save Broken Coordinates into a csv file.
    Nan_broken_database.to_csv("broken_coordinates.csv")
    
    # Reverse Gepolot
    results = []
    for i in range (correct_rows):
        locations = reverse((str(correct_database.iloc[i, 0]) + "," + str(correct_database.iloc[i, 1])), language='en', exactly_one=True)
        results.append(locations)

    addresses = pd.DataFrame(results)
    addresses.to_csv("addresses_results.csv")
    
    # Pass Data to Folium Map
    plugins.FastMarkerCluster(data=list(zip(correct_database['Latitude'].values, correct_database['Longitude'].values))).add_to(folium_map)
    
    # Create Fullscreen Button
    plugins.Fullscreen(
    position="topright",
    title="Expand me",
    title_cancel="Exit me",
    force_separate_button=True
    ).add_to(folium_map)

    # Create Minimap
    minimap = plugins.MiniMap(toggle_display=toggle_minimap_display)
    folium_map.add_child(minimap)

    # Locate Control
    folium.LayerControl().add_to(folium_map)