Python folium.Map() Examples

The following are 18 code examples of folium.Map(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module folium , or try the search function .
Example #1
Source File: drawer.py    From chinese_province_city_area_mapper with MIT License 7 votes vote down vote up
def draw_locations(locations, file_path):
    """
    基于folium生成地域分布的热力图的html文件.
    :param locations: 样本的省市区, pandas的dataframe类型.
    :param file_path: 生成的html文件的路径.
    """
    _base_input_check(locations)
    import folium
    from folium.plugins import HeatMap
    # 注意判断key是否存在
    heatData = []
    for map_key in zip(locations["省"], locations["市"], locations["区"]):
        if latlng.get(map_key):
            lat_lon = latlng.get(map_key)
            heatData.append([float(lat_lon[0]), float(lat_lon[1]), 1])
    # 绘制Map,开始缩放程度是5倍
    map_osm = folium.Map(location=[35, 110], zoom_start=5)
    # 将热力图添加到前面建立的map里
    HeatMap(heatData).add_to(map_osm)
    # 保存为html文件
    map_osm.save(file_path) 
Example #2
Source File: visualization.py    From GridCal with GNU General Public License v3.0 7 votes vote down vote up
def get_base_map(location, zoom_start=5):
    """
    Get map with all the base defined layers
    :param location: (lat, lon)
    :param zoom_start: integer
    :return: map, marker_layer
    """

    my_map = folium.Map(location=location, zoom_start=zoom_start)

    # add possible tiles
    folium.TileLayer('cartodbpositron').add_to(my_map)
    folium.TileLayer('cartodbdark_matter').add_to(my_map)
    folium.TileLayer('openstreetmap').add_to(my_map)
    folium.TileLayer('Mapbox Bright').add_to(my_map)
    folium.TileLayer('stamentoner').add_to(my_map)

    # add markers layer
    marker_cluster = MarkerCluster().add_to(my_map)

    # add the layer control
    folium.LayerControl().add_to(my_map)

    return my_map, marker_cluster 
Example #3
Source File: plot.py    From predictatops with MIT License 7 votes vote down vote up
def makeMap_1(no_zeros_df):
    m5 = folium.Map(center2, tiles="Stamen Toner", zoom_start=zoom2)
    list_df_for_map = no_zeros_df.values.tolist()

    for row in list_df_for_map[0:]:
        print(
            "location = ",
            row[1:3],
            " and depth is",
            row[12:13][0],
            " and UWI is ",
            row[3:4][0],
        )
        folium.CircleMarker(
            location=row[1:3],
            radius=2,
            color=depth_color(row[13:14][0]),
            fill=True,
            #     popup=folium.Popup(str(row[9:10][0])+ " & depth Top McMurray=", parse_html=True)
            #     popup=folium.Popup(str(row[9:10][0]+ ", depth Top McMurray="+str(row[15:16][0])), parse_html=True)
        ).add_to(m5)
    return m5 
Example #4
Source File: visualization.py    From PyMove with MIT License 6 votes vote down vote up
def save_map(
    move_data, filename, tiles=TILES[0], label_id=TRAJ_ID, cmap='tab20', return_map=False
):
    """
    Save a visualization in a map in a new file.

    Parameters
    ----------
    move_data : pymove.core.MoveDataFrameAbstract subclass.
        Input trajectory data.
    filename : String
        Represents the filename.
    tiles : String
        Represents the type_ of tile that will be used on the map.
    label_id : String
        Represents column name of trajectory id.
    cmap: String
        Represents the Colormap.

    """

    map_ = folium.Map(tiles=tiles)
    map_.fit_bounds(
        [
            [move_data[LATITUDE].min(), move_data[LONGITUDE].min()],
            [move_data[LATITUDE].max(), move_data[LONGITUDE].max()],
        ]
    )

    ids = move_data[label_id].unique()
    cmap_ = plt.cm.get_cmap(cmap)
    num = cmap_.N

    for id_ in ids:
        id_index = np.where(ids == id_)[0][0]
        move_df = move_data[move_data[label_id] == id_]
        points_ = [
            (point[0], point[1])
            for point in move_df[[LATITUDE, LONGITUDE]].values
        ]
        color_ = cmap_hex_color(cmap_, (id_index % num))
        folium.PolyLine(points_, weight=3, color=color_).add_to(map_)
    map_.save(filename)

    if return_map:
        return map_ 
Example #5
Source File: gis_dialogue.py    From GridCal with GNU General Public License v3.0 6 votes vote down vote up
def generate_blank_map_html(lon_avg, lat_avg):
        """
        Generate a blank HTML map file
        :param lon_avg: center longitude
        :param lat_avg: center latitude
        :return: file name
        """
        my_map = folium.Map(location=[lon_avg, lat_avg], zoom_start=5)

        gc_path = get_create_gridcal_folder()

        path = os.path.join(gc_path, 'map.html')

        my_map.save(path)

        return path 
Example #6
Source File: listing4_3.py    From osgeopy-code with MIT License 5 votes vote down vote up
def make_map(state_name, json_fn, html_fn, **kwargs):
    """Make a folium map."""
    geom = get_state_geom(state_name)
    save_state_gauges(json_fn, get_bbox(geom))
    fmap = folium.Map(location=get_center(geom), **kwargs)
    fmap.geo_json(geo_path=json_fn)
    fmap.create_map(path=html_fn)


# Top-level code. Don't forget to change the directory. The if-statement
# makes it so that the next two lines of code only run if this script is
# being run as a stand-alone script. This way you can import this file
# into listing 4.4 and this part won't run, but you'll have access to all
# of the above functions. 
Example #7
Source File: geotweet.py    From GeoTweet with MIT License 5 votes vote down vote up
def search_zone_map():
    cont = 0
    places = api.geo_search(query=ZONE, granularity="country")
    place_id = places[0].id
    tweets = api.search(q="place:%s" % place_id,count=number)
    for tweet in tweets:
        print "------------------------------------------------"
        printout("[NAME:]   ", GREEN)
        print tweet.user.name.encode('utf-8')
        printout("[ALIAS:]   ", BLUE)
        print "@" + tweet.user.screen_name.encode('utf-8')
        printout("[TWEET:] ", YELLOW)
        print " " + tweet.text.encode('utf-8')
        printout("[GEOLOCATION:]   ", MAGENTA)
        print tweet.geo['coordinates']
        location = geolocator.reverse(tweet.geo['coordinates'],timeout=20)
        printout("[ADDRESS:]   ", CYAN)
        print location.address.encode('utf-8')
        if cont == 0:
                map_1 = folium.Map(location=tweet.geo['coordinates'], zoom_start=4, width=1800, height =1200)
                cont = cont + 1
        else:
            cont = cont + 1
            map_1.simple_marker(location=tweet.geo['coordinates'],popup=tweet.user.screen_name.encode('utf-8'))   
            location = geolocator.reverse(tweet.geo['coordinates'],timeout=20)
    if MAPS == "y":
        map_1.create_map(path='maps.html')
    else:
        sys.exit(2)
    credit() 
Example #8
Source File: geotweet.py    From GeoTweet with MIT License 5 votes vote down vote up
def timeline_user():
    cont = 0
    user = api.user_timeline(screen_name, count=number)
    for tweet in user:
        print "----------------------------------------------"
        printout("[TWEET:] ", YELLOW)
        print " " + tweet.text.encode('utf-8')
        printout("[SOURCE:] ", GREEN)
        print tweet.source.encode('utf-8')
        printout("[DATE:] ", RED)
        print tweet.created_at
        printout("[RT:] ", BLUE)
        print tweet.retweet_count
        printout("[FAV:] ", WHITE)
        print tweet.favorite_count
        if tweet.geo == None:
            printout("[GEOLOCATION:]   ", MAGENTA)
            print tweet.geo
        else:
            printout("[GEOLOCATION:]   ", MAGENTA)
            print tweet.geo['coordinates']
            location = geolocator.reverse(tweet.geo['coordinates'],timeout=20)
            printout("[ADDRESS:]   ", CYAN)
            print location.address.encode('utf-8')
            if cont == 0:
                map_1 = folium.Map(location=tweet.geo['coordinates'], zoom_start=4, width=1800, height =1200)
                cont = cont + 1
            else:
                cont = cont + 1
                map_1.simple_marker(location=tweet.geo['coordinates'],popup=tweet.text.encode('utf-8'))   
                location = geolocator.reverse(tweet.geo['coordinates'],timeout=20)
    if MAPS == "y":
        map_1.create_map(path='maps_user.html')
    credit() 
Example #9
Source File: app.py    From folium-demo with MIT License 5 votes vote down vote up
def tracker():
  loc = geocoder.osm(app.vars.get('location'))
  if loc.lat is not None and loc.lng is not None:
    latlng = [loc.lat, loc.lng]
  else:
    return redirect('/geoerror.html')
  
  # insist on a valid map config
  map_path = app.vars.get("map_path")
  if not map_path:
    return redirect('/error.html')
  if app.vars.get("cache") == "yes" and Path(map_path).exists():
    return render_template('display.html')
  else:
    bus_map = folium.Map(location=latlng, zoom_start=15)
    bus_map.add_child(folium.Marker(location=latlng,
                                    popup=escape_apostrophes(loc.address),
                                    icon=folium.Icon(color='blue')))

    # Call API for bus locations
    bus_list = get_buses(loc.lat, loc.lng, app.vars['radius'])

    for bus in bus_list:
      route_id = bus.get('RouteID')
      trip_headsign = escape_apostrophes(bus.get('TripHeadsign'))
      folium.features.RegularPolygonMarker(location = [bus['Lat'], bus['Lon']],
                                           popup = f"Route {route_id} to {trip_headsign}",
                                           number_of_sides = 3,
                                           radius = 15,
                                           weight = 1,
                                           fill_opacity = 0.8,
                                           rotation = 30).add_to(bus_map)
  
    bus_map.save(map_path)
    return render_template('display.html')
  pass 
Example #10
Source File: geo_heatmap.py    From geo-heatmap with MIT License 5 votes vote down vote up
def generateMap(self, settings):
        """Generates the heatmap.
        
        Arguments:
            settings {dict} -- The settings for the heatmap.
        
        Returns:
            Map -- The Heatmap.
        """
        tiles = settings["tiles"]
        zoom_start = settings["zoom_start"]
        radius = settings["radius"]
        blur = settings["blur"]
        min_opacity = settings["min_opacity"]
        max_zoom = settings["max_zoom"]
        
        map_data = [(coords[0], coords[1], magnitude)
                    for coords, magnitude in self.coordinates.items()]

        # Generate map
        m = folium.Map(location=self.max_coordinates,
                       zoom_start=zoom_start,
                       tiles=tiles)

        # Generate heat map
        heatmap = HeatMap(map_data,
                          max_val=self.max_magnitude,
                          min_opacity=min_opacity,
                          radius=radius,
                          blur=blur,
                          max_zoom=max_zoom)

        m.add_child(heatmap)
        return m 
Example #11
Source File: gps_map_marker.py    From BerePi with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def plot_on_map(data, _index):

    resolution, width, height = 75, 7, 3
    lat, lon = (sangil_gwangju_lat_limit[0]/2 + sangil_gwangju_lat_limit[1]/2 ,
        sangil_gwangju_lon_limit[0]/2 + sangil_gwangju_lon_limit[1]/2)

    map = folium.Map(location=[lat, lon], zoom_start=12)
    Color = mcolors.CSS4_COLORS.values()
    countcar = 0

    for i in _index:
        countcar += 1
        print str(data[2][i])+'번 차량 지도에 그리는 중....'
        for j in range(0, len(data[0][i])):

            if j == 0:
                folium.Marker(location=[float(data[0][i][j]), float(data[1][i][j])],
                    icon=folium.Icon(color='red'),
                    popup=data[2][i]+'start').add_to(map)
            elif j == len(data[0][i]) - 1:
                folium.Marker(location=[float(data[0][i][j]), float(data[1][i][j])],
                    icon=folium.Icon(color='blue'),popup=data[2][i]+'end').add_to(map)

            folium.CircleMarker(location=[float(data[0][i][j]), float(data[1][i][j])],
                radius=20, line_color=Color[countcar],fill_color=Color[countcar],
                fill_opacity=0.1)

        folium.CircleMarker(location=[sangil_gwangju_lat_limit[1], sangil_gwangju_lon_limit[0]],
            radius=100, line_color='black',
            fill_color='black', fill_opacity=1)

        folium.CircleMarker(location=[sangil_gwangju_lat_limit[0], sangil_gwangju_lon_limit[1]], radius=100,
                          line_color='black', fill_color='black', fill_opacity=1)

    map.save('result.html')

    os.system('explorer.exe result.html')

    print "총 지나간 차량 : %.3s 대" % countcar 
Example #12
Source File: listing4_4.py    From osgeopy-code with MIT License 5 votes vote down vote up
def make_map(state_name, json_fn, html_fn, **kwargs):
    """Make a folium map."""
    geom = listing4_3.get_state_geom(state_name)
    listing4_3.save_state_gauges(json_fn, listing4_3.get_bbox(geom))
    fmap = folium.Map(location=listing4_3.get_center(geom), **kwargs)
    add_markers(fmap, json_fn)
    fmap.create_map(path=html_fn)


# Top-level code. Don't forget to change the directory.
# Try other options for the tiles parameter. Options are:
# 'OpenStreetMap', 'Mapbox Bright', 'Mapbox Control Room',
# 'Stamen Terrain', 'Stamen Toner' 
Example #13
Source File: visualization.py    From PyMove with MIT License 5 votes vote down vote up
def _add_trajectories_to_folium_map(
    move_data,
    items,
    base_map,
    legend=True,
    save_as_html=True,
    filename='map.html',
):
    """
    Adds a trajectory to a folium map with begin and end markers.

    Parameters
    ----------
    move_data : pymove.core.MoveDataFrameAbstract subclass.
        Input trajectory data.
    legend: boolean, default True
        Whether to add a legend to the map
    base_map : folium.folium.Map, optional, default None.
        Represents the folium map. If not informed, a new map is generated.
    save_as_html : bool, optional, default False.
        Represents if want save this visualization in a new file .html.
    filename : String, optional, default 'plot_trajectory_by_period.html'.
        Represents the file name of new file .html.

    """

    for _id, color in items:
        mv = move_data[move_data[TRAJ_ID] == _id]

        _add_begin_end_markers_to_folium_map(move_data, base_map)

        folium.PolyLine(
            mv[[LATITUDE, LONGITUDE]], color=color, weight=2.5, opacity=1
        ).add_to(base_map)

    if legend:
        add_map_legend(base_map, 'Color by user ID', items)

    if save_as_html:
        base_map.save(outfile=filename) 
Example #14
Source File: visualization.py    From PyMove with MIT License 5 votes vote down vote up
def _add_begin_end_markers_to_folium_map(move_data, base_map):
    """
    Adds a green marker to beginning of the trajectory and a red marker to the
    end of the trajectory.

    Parameters
    ----------
    move_data : pymove.core.MoveDataFrameAbstract subclass.
        Input trajectory data.
    base_map : folium.folium.Map, optional, default None.
        Represents the folium map. If not informed, a new map is generated.

    """

    folium.Marker(
        location=[move_data.iloc[0][LATITUDE], move_data.iloc[0][LONGITUDE]],
        color='green',
        clustered_marker=True,
        popup='Início',
        icon=folium.Icon(color='green', icon='info-sign'),
    ).add_to(base_map)

    folium.Marker(
        location=[move_data.iloc[-1][LATITUDE], move_data.iloc[-1][LONGITUDE]],
        color='red',
        clustered_marker=True,
        popup='Fim',
        icon=folium.Icon(color='red', icon='info-sign'),
    ).add_to(base_map) 
Example #15
Source File: visualization.py    From PyMove with MIT License 4 votes vote down vote up
def create_base_map(
    move_data,
    lat_origin=None,
    lon_origin=None,
    tile=TILES[0],
    default_zoom_start=12,
):
    """
    Generate a folium map.

    Parameters
    ----------
    move_data : pymove.core.MoveDataFrameAbstract subclass.
        Input trajectory data.
    lat_origin : float, optional, default None.
        Represents the latitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    lon_origin : float, optional, default None.
        Represents the longitude which will be the center of the map.
        If not entered, the first data from the dataset is used.
    default_zoom_start : int, optional, default 12.
        Represents the zoom which will be the center of the map.
    tile : String, optional, default 'CartoDB positron'.
        Represents the map'srs tiles.

    Returns
    -------
    folium.folium.Map.
        Represents a folium map.

    """

    if lat_origin is None and lon_origin is None:
        lat_origin = move_data.iloc[0][LATITUDE]
        lon_origin = move_data.iloc[0][LONGITUDE]
    base_map = folium.Map(
        location=[lat_origin, lon_origin],
        control_scale=True,
        zoom_start=default_zoom_start,
        tiles=tile,
    )
    return base_map 
Example #16
Source File: trajectories.py    From PyMove with MIT License 4 votes vote down vote up
def save_bbox(
        bbox_tuple, file='bbox.html', tiles=TILES[0], color='red', return_map=False
):
    """
    Save bbox as file .html using Folium.

    Parameters
    ----------
    bbox_tuple : tuple.
        Represents a bound box, that is a tuple of 4 values with the
        min and max limits of latitude e longitude.
    file : String, optional, default 'bbox.html'.
        Represents filename.
    tiles : String, optional, default 'OpenStreetMap'.
        Represents tyles'srs type_.
        Example: 'openstreetmap', 'cartodbpositron',
                'stamentoner', 'stamenterrain',
                'mapquestopen', 'MapQuest Open Aerial',
                'Mapbox Control Room' and 'Mapbox Bright'.
    color : String, optional, default 'red'.
        Represents color of lines on map.
    return_map: Boolean, optional, default False.
        Wether to return the bbox folium map.

    Examples
    --------
    >>> from pymove.trajectories import save_bbox
    >>> bbox = (22.147577, 113.54884299999999, 41.132062, 121.156224)
    >>> save_bbox(bbox, 'bbox.html')

    """

    m = folium.Map(tiles=tiles)
    m.fit_bounds(
        [[bbox_tuple[0], bbox_tuple[1]], [bbox_tuple[2], bbox_tuple[3]]]
    )
    points_ = [
        (bbox_tuple[0], bbox_tuple[1]),
        (bbox_tuple[0], bbox_tuple[3]),
        (bbox_tuple[2], bbox_tuple[3]),
        (bbox_tuple[2], bbox_tuple[1]),
        (bbox_tuple[0], bbox_tuple[1]),
    ]
    folium.PolyLine(points_, weight=3, color=color).add_to(m)
    m.save(file)
    if return_map:
        return m 
Example #17
Source File: test_folium.py    From msticpy with MIT License 4 votes vote down vote up
def test_folium_map(self):

        # Read in some data
        ip_locs_file = Path(_TEST_DATA).joinpath("ip_locs.csv")
        geo_loc_df = pd.read_csv(ip_locs_file, index_col=0)

        # Create IP and GeoLocation Entities from the dataframe
        geo_locs = list(geo_loc_df.apply(create_geo_entity, axis=1).values)
        ip_entities = list(geo_loc_df.apply(create_ip_entity, axis=1).values)

        folium_map = FoliumMap(
            width="50%", height="50%", location=(47.5982328, -122.331), zoom_start=14
        )
        self.assertIsInstance(folium_map.folium_map, folium.Map)

        for ip in ip_entities:
            ip.AdditionalData.update({"name": "test", "role": "testrole"})
        folium_map = FoliumMap(zoom_start=9)
        folium_map.add_ip_cluster(ip_entities=ip_entities, color="orange")
        ip_entities_clean = [
            ip
            for ip in ip_entities
            if ip.Location
            and ip.Location.Latitude
            and not math.isnan(ip.Location.Latitude)
            and not math.isnan(ip.Location.Longitude)
        ]
        self.assertEqual(len(ip_entities_clean), len(folium_map.locations))

        folium_map.add_ip_cluster(ip_entities=ip_entities_clean)
        folium_map.center_map()

        folium_map.add_geoloc_cluster(geo_locations=geo_locs, color="orange")
        self.assertEqual(len(ip_entities_clean) * 3, len(folium_map.locations))

        geo_tuples = geo_loc_df.apply(
            lambda x: (x.Latitude, x.Longitude), axis=1
        ).values
        folium_map.add_locations(locations=geo_tuples, color="orange")
        self.assertEqual(len(ip_entities_clean) * 4, len(folium_map.locations))

        # test centering algorithms
        center = get_center_geo_locs(geo_locs)
        self.assertAlmostEqual(center[0], 38.7095)
        self.assertAlmostEqual(center[1], -93.6112)
        center = get_center_geo_locs(geo_locs, mode="mean")
        self.assertAlmostEqual(center[0], 39.847162352941176)
        self.assertAlmostEqual(center[1], -87.36079411764706)
        center = get_center_ip_entities(ip_entities)
        self.assertAlmostEqual(center[0], 38.7095)
        self.assertAlmostEqual(center[1], -93.6112)
        hosts = []
        for ip in ip_entities:
            new_host = Host(HostName=ip.Address)
            new_host.ip = ip
            hosts.append(new_host)

        center = get_map_center(entities=hosts)
        self.assertAlmostEqual(center[0], 39.847162352941176)
        self.assertAlmostEqual(center[1], -87.36079411764706) 
Example #18
Source File: foliummap.py    From msticpy with MIT License 4 votes vote down vote up
def __init__(
        self,
        title: str = "layer1",
        zoom_start: float = 2.5,
        tiles=None,
        width: str = "100%",
        height: str = "100%",
        location: list = None,
    ):
        """
        Create an instance of the folium map.

        Parameters
        ----------
        title : str, optional
            Name of the layer (the default is 'layer1')
        zoom_start : int, optional
            The zoom level of the map (the default is 7)
        tiles : [type], optional
            Custom set of tiles or tile URL (the default is None)
        width : str, optional
            Map display width (the default is '100%')
        height : str, optional
            Map display height (the default is '100%')
        location : list, optional
            Location to center map on

        Attributes
        ----------
        folium_map : folium.Map
            The map object.

        """
        if not location:
            location = [47.67, -122.13]

        self.folium_map = folium.Map(
            zoom_start=zoom_start,
            tiles=tiles,
            width=width,
            height=height,
            location=location,
        )
        folium.TileLayer(name=title).add_to(self.folium_map)
        self.locations: List[Tuple[float, float]] = []