예제 #1
1
def test_polyline_popups():
    m = Map([43,-100], zoom_start=4)
    features.PolyLine([[40,-80],[45,-80]], popup="PolyLine").add_to(m)
    features.PolyLine([[40,-90],[45,-90]], popup=Popup("PolyLine")).add_to(m)
    features.MultiPolyLine([[[40,-110],[45,-110]]], popup="MultiPolyLine").add_to(m)
    features.MultiPolyLine([[[40,-120],[45,-120]]], popup=Popup("MultiPolyLine")).add_to(m)
    m._repr_html_()
예제 #2
0
def create_map(df_collisions, df_stations, boroughs):
    geo_map = Map(location=[40.74527, -73.988573], tiles=None, zoom_start=12, control_scale=True)
    close_distance = 200  # meters

    # collisions
    TileLayer('Stamen Terrain', name='Collision Data').add_to(geo_map)
    for borough in boroughs:
        feature_group = FeatureGroup(name=borough.capitalize())
        marker_cluster = MarkerCluster().add_to(feature_group)
        df_collisions[df_collisions['borough'] == borough].apply(
            lambda r: Marker(
                location=[r['latitude'], r['longitude']],
                tooltip=f"{r['cyclist_injured'] + r['cyclist_killed']} cyclists injured/killed",
                icon=Icon(color='darkblue', icon='exclamation-circle', prefix='fa')).add_to(marker_cluster),
            axis=1)
        feature_group.add_to(geo_map)

    # bike stations
    quartiles = df_stations['close_collisions'].quantile([0.25, 0.5, 0.75]).tolist()
    feature_group = FeatureGroup(name='Bike Stations')
    df_stations.apply(lambda r: CircleMarker(
        location=(r['latitude'], r['longitude']),
        radius=2,
        color=get_color(r['close_collisions'], quartiles),
        tooltip=f"Bike Station {int(r['id'])}:  {int(r['close_collisions'])} collisions within {close_distance}m",
        fill=True).add_to(feature_group), axis=1)
    feature_group.add_to(geo_map)

    LayerControl(collapsed=False).add_to(geo_map)
    geo_map.save('templates/map.html')
예제 #3
0
파일: map.py 프로젝트: dobraga/get_listings
    def create_map(data):
        if not data:
            raise PreventUpdate

        df = pd.DataFrame(data)
        qtd_sem_latlon = df[["address_lat",
                             "address_lon"]].isna().max(axis=1).sum()
        df = df.dropna(subset=["address_lat", "address_lon"])

        map = Map(
            location=df[["address_lat", "address_lon"]].mean().values,
            height="89%",
            tiles=
            "https://{s}.tile.openstreetmap.de/tiles/osmde/{z}/{x}/{y}.png",
            attr="toner-bcg",
        )

        marker_cluster = MarkerCluster().add_to(map)

        for _, row in df.iterrows():
            Marker(
                location=[row["address_lat"], row["address_lon"]],
                popup=box(**row),
            ).add_to(marker_cluster)

        return f"{qtd_sem_latlon} imóveis sem latitude ou longitude", map._repr_html_(
        )
    def visualize_map(self, df, theme=None):

        dark_attr = "https://cartodb-basemaps-{s}.global.ssl.fastly.net/dark_all/{z}/{x}/{y}.png"
        positron_attr = "https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png"
        osm_attr = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        if theme == 'dark':
            map = Map(location=[34.0522, -118.2437],
                      control_scale=True,
                      zoom_start=12,
                      attr=dark_attr,
                      tiles="cartodbdark_matter")
        elif theme == 'positron':
            map = Map(location=[34.0522, -118.2437],
                      control_scale=True,
                      zoom_start=12,
                      attr=positron_attr,
                      tiles="cartodbpositron")
        else:
            map = Map(location=[34.0522, -118.2437],
                      control_scale=True,
                      zoom_start=12,
                      attr=osm_attr,
                      tiles="openstreetmap")

        cluster = MarkerCluster().add_to(map)

        locations = df[['latitudes', 'longitudes']].values.tolist()

        for point in range(len(locations)):
            Marker(locations[point],
                   popup=df['listing_name'][point]).add_to(cluster)

        return map
예제 #5
0
 def __init__(self, lat, lon, **kwargs):
     # two coords point
     self.lat = lat
     self.lon = lon
     self.save_location = kwargs.pop('save', 'template/map.html')
     self.file = self.save_location.split('/')[-1]
     self.maps = Map(location=[self.lat, self.lon], **kwargs)
예제 #6
0
def getMap():

    # initialize the map to the starting location and add starting location
    # this library will base location off user IP address. It works locally, but
    # not once the app is deployed (different IP address)
    g = geocoder.ip('me')
    start_coords = g.latlng
    themap = Map(location=start_coords, tiles="OpenStreetMap", zoom_start=15)
    folium.Marker(location=start_coords,
                  popup='Your Location',
                  icon=folium.Icon(color='red', icon='hi')).add_to(themap)

    # get nearby restaurant data
    startloc = str(start_coords[0]) + "," + str(start_coords[1])
    df = getRestaurantData(startloc)
    data = cleanDataframe(df)

    # add restaurants to the map
    for (y, x) in data.iterrows():
        loc = []
        loc.append(x['latitude'])
        loc.append(x['longitude'])
        color = "green"
        if (x['rating'] < 4.0):
            color = "orange"
        popup_text = "{}<br> Cuisine: {}<br> Average Rating: {}<br> Number of Reviews: {}"
        popup_text = popup_text.format(x["name"], x["descriptors"],
                                       x["rating"], x['review_count'])
        themap.add_child(
            Marker(location=loc,
                   popup=popup_text,
                   icon=folium.Icon(color=color)))
    return themap._repr_html_()
예제 #7
0
class Mapper:
	def __init__(self, targets: list):
		self.targets = targets
		self._generate_map()

	def _get_coordinates(self, target) -> list:
		url = F"http://ip-api.com/json/{target}?fields=lat,lon"
		resp = get(url)
		resp_json = loads(resp.text)
		latitude, longitude = resp_json["lat"], resp_json["lon"]
		return [latitude, longitude]

	def _generate_map(self):
		# creating map
		self.m = Map(location=[0,0], zoom_start=3)	

	def add_target_marker(self, target):
		# adding marker to map
		Marker(
			location=self._get_coordinates(target),
			popup=target,
			icon=Icon()	
		).add_to(self.m)

	def save(self):
		# save to html file
		self.m.save("./map.html")
		print(bold(blue("Map saved to file:")), "./map.html")
예제 #8
0
def draw_map_once_function_call():
    # df = pd.read_csv("vac.csv")
    # df = pd.read_csv("vac210315.csv")
    # df = pd.read_csv("csv/vac210331.csv")
    df = pd.read_csv("csv/test.csv")

    m = Map(location=[36.5053542, 127.7043419], zoom_start=8)
    marker_cluster = MarkerCluster().add_to(m)
    addr_list = []
    for idx in range(len(df)):
        addr_list.append(df.loc[idx, "address"])

    # but one call func not multiple call
    # lon_list, lat_list = getLatLng_list(addr_list)

    for idx, addr in enumerate(addr_list):
        location_name = df.loc[idx, "location_name"]
        telephone = df.loc[idx, "telephone"]
        print(telephone)
        latitude = df.loc[idx, "latitude"]
        longitude = df.loc[idx, "longitude"]
        iframe = location_name + ":<br> " + addr + ": <br> " + telephone
        print(idx, ": ", iframe)
        popup = folium.Popup(iframe, min_width=200, max_width=200)
        Marker(location=[latitude, longitude],
               popup=popup,
               tooltip=location_name,
               icon=Icon(color='green', icon='flag')).add_to(marker_cluster)
    account_info = get_apikey("Account", "secret.json")
    return render_template(template_name_or_list="index.html",
                           map=m._repr_html_(),
                           account_info=account_info)
예제 #9
0
파일: geomap.py 프로젝트: dfirsec/check_rep
def multi_map(input_file):
    os.chdir(geomap_root)

    # Check if Geolite file exists
    geolite_check()

    file_path = os.path.abspath(os.pardir)
    input_file = f"{file_path}/{input_file}"
    with open(input_file) as f:
        line = [line.strip() for line in f.readlines()]
        ip_map = Map([40, -5], tiles="OpenStreetMap", zoom_start=3)
        try:
            geo_reader = geoip2.database.Reader("GeoLite2-City.mmdb")
            for addr in line:
                response = geo_reader.city(addr)
                if response.location:
                    logger.success(f"[+] Mapping {addr}")
                    lat = response.location.latitude
                    lon = response.location.longitude
                    Marker([lat, lon], popup=addr).add_to(ip_map)
                    ip_map.save("multi_map.html")
        except ValueError as err:
            print(f"[error] {err}")
        except geoip2.errors.AddressNotFoundError:
            logger.warning("[-] Address is not in the geoip database.")
        except FileNotFoundError:
            geolite_check()
예제 #10
0
    def _add_layer(cls, map_object: Map,
                   layer_document: MapLayerDocument) -> None:
        """
        Create layer on a Folium Map. Method creates layer and adjusts it based on configuration. The layer is
        appended to the provided Folium Map.

        :param map_object: (Map) map object to create layer on

        :param layer_document: (MapLayerDocument) layer document configuration object.

        :return: None
        """
        model = layer_document.model
        latitude_column = layer_document.latitude
        longtitude_column = layer_document.longtitude

        axis = model.axis
        axis_label = axis.name or axis.data_field
        feature_group = FeatureGroup(name=axis_label)

        data_source = layer_document.data_source
        for row in data_source.itertuples():
            latitude = getattr(row, latitude_column.data_field)
            longtitude = getattr(row, longtitude_column.data_field)
            value = getattr(row, axis.data_field)

            coordinates = [latitude, longtitude]
            # model.figure.size *= 5
            marker = cls._create_marker(layer_value=str(value),
                                        coordinates=coordinates,
                                        layer_figure=model.figure)
            feature_group.add_child(marker)

        map_object.add_child(feature_group)
예제 #11
0
def heatmap(gdf, location, gradient=None):
    """
    This is a function that creates a heatmap.
    Parameters
    ----------
    gdf (geodata frame) : GeoDataFrame
    location (list): latitude and longitude  of central map location (e.g. NYC = [40.693943, -74.025])
    gradient (dict) (default:None): option to change the gradient, useful when combining other heatmaps

    Returns
    -------
    a heatmap of where a specific class of data is _ by sensor
    """

    emptymap = Map(location=location, zoom_start=12)

    # create heatmap
    hm = HeatMap(
        list(zip(gdf.latitude.values, gdf.longitude.values)),
        min_opacity=0.2,
        radius=10,
        blur=13,
        gradient=gradient,
        max_zoom=1,
    )
    # add heatmap layer to empty layer
    emptymap.add_child(hm)
    return emptymap
예제 #12
0
    def as_map(self, img_name=None):

        if img_name == None:
            coord_index = self.meta_keys.index('GPS')
            coord_list = [
                self.metadata[key][coord_index][0:2] + [key]
                for key in self.metadata.keys()
            ]
            print(coord_list)

            cood_t = list(map(list, zip(*coord_list)))
            center = [(max(cood_t[0]) + min(cood_t[0])) / 2,
                      (max(cood_t[1]) + min(cood_t[1])) / 2]

            print(center)
            print(coord_list)

            img_map = Map(
                location=center,
                zoom_start=13,
                width='100%',
                height='100%',
                tiles='https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
                attr='Google')

            for x, y, img in coord_list:
                Marker(location=[x, y], popup='', tooltip=img).add_to(img_map)

            return (img_map._repr_html_())

        return ('')
예제 #13
0
def map_api_call():
    url = "https://api.odcloud.kr/api/15077586/v1/centers?page=1&perPage=300&serviceKey=" + get_apikey(
        "serviceKey", "secret.json")

    result = requests.get(url=url)
    json_result = json.loads(str(result.text))

    m = Map(location=[36.5053542, 127.7043419], zoom_start=8)
    marker_cluster = MarkerCluster().add_to(m)

    for idx in range(json_result["currentCount"]):
        address = json_result["data"][idx]["address"]
        centerName = json_result["data"][idx]["centerName"]
        facilityName = json_result["data"][idx]["facilityName"]
        lat = json_result["data"][idx]["lat"]
        lng = json_result["data"][idx]["lng"]
        iframe = centerName + ": <br> " + facilityName + ":<br> " + address
        popup = folium.Popup(iframe, min_width=200, max_width=200)
        Marker(location=[lat, lng],
               popup=popup,
               tooltip=centerName + " : " + facilityName,
               icon=Icon(color='green', icon='flag')).add_to(marker_cluster)
    account_info = get_apikey("Account", "secret.json")
    return render_template(template_name_or_list="index.html",
                           map=m._repr_html_(),
                           account_info=account_info)
예제 #14
0
    def create_map(self):
        _map = Map(tiles="cartodbpositron")
        geos = self.get_geos()
        max_lat, max_lon, min_lat, min_lon = get_min_max_ll(geos)

        geos = [(i, numpy.log(j + 1) / (self.tree.get_node_height(k) + 1), k)
                for i, j, k in geos]
        mx, mn = max([j for i, j, k in geos]), min([j for i, j, k in geos])
        geos = [(i, (j - mn) / (mx - mn), k) for i, j, k in geos]

        for points, count, h in sorted(geos, key=lambda x: x[1]):
            tooltip = f"hex: {h}"
            polygon = Polygon(locations=points,
                              tooltip=tooltip,
                              fill=True,
                              color=cm.linear.OrRd_03.rgb_hex_str(count),
                              fill_color=cm.linear.OrRd_03.rgb_hex_str(count),
                              fill_opacity=0.3,
                              weight=3,
                              opacity=0.4)
            polygon.add_to(_map)

        _map.fit_bounds([[min_lat, min_lon], [max_lat, max_lon]])

        return _map
예제 #15
0
    def create_map(self):

        try:
            from folium import Map
            from folium.vector_layers import Polygon
            import branca.colormap as cm
        except ImportError:  # pragma: no cover
            logger.error('Mapping requires folium==0.10.0 to be installed, geo mapping will not work.'
                         'Install it with: pip install scikit-hts[geo]')
            return

        _map = Map(tiles="cartodbpositron")
        geos = self.get_geos()
        max_lat, max_lon, min_lat, min_lon = get_min_max_ll(geos)

        geos = [(i, numpy.log(j + 1) / (self.tree.get_node_height(k) + 1), k) for i, j, k in geos]
        mx, mn = max([j for i, j, k in geos]), min([j for i, j, k in geos])
        geos = [(i, (j - mn) / (mx - mn), k) for i, j, k in geos]

        for points, count, h in sorted(geos, key=lambda x: x[1]):
            tooltip = f"hex: {h}"
            polygon = Polygon(locations=points,
                              tooltip=tooltip,
                              fill=True,
                              color=cm.linear.OrRd_03.rgb_hex_str(count),
                              fill_color=cm.linear.OrRd_03.rgb_hex_str(count),
                              fill_opacity=0.3,
                              weight=3,
                              opacity=0.4)
            polygon.add_to(_map)

        _map.fit_bounds([[min_lat, min_lon], [max_lat, max_lon]])

        return _map
예제 #16
0
def build_heat_map(data, sample):
    heat_map = Map(**MAP_DEFAULT_START_PARAMS)
    HeatMap(data[['lat', 'long']], radius=10).add_to(heat_map)
    if 'lat' in sample.columns:
        heat_map.add_child(
            Circle(*sample[['lat', 'long']].values, radius=1.1e5))
    return heat_map
def produce_map(year):
    """
    This function generates a map of the US and displays all the data for a given year in popups and a color gradient
    """
    year_file = yearly_map(year)
    state_geo = os.path.join('data', 'us_states.json')
    state_data = pd.read_csv(year_file)
    marker_year = 'StateLonandLat'+str(year)+'.csv'
    marker_data = os.path.join('data',marker_year)
    marker_coord = pd.read_csv(marker_data)

    #establishes the center of map based on longitude and latitude
    m = Map(location=[50.246366, -110], zoom_start=4)

    #sets the color scheme, data used for legend, and legend labels
    Choropleth(geo_data=state_geo,name='choropleth',data=state_data,
        columns=['State',  'Death Rate'],
        key_on='feature.id',
        fill_color='BuPu',
        fill_opacity=0.7,
        line_opacity=0.5,
        legend_name='Average Death Rate in '+str(year)
    ).add_to(m)
    #create markers and places them within corresponding state
    for i in range(0,len(marker_coord)):
        #popup contains data about causes fo death
        popup = Popup(marker_coord.iloc[i]['state'],max_width=350)
        Marker([marker_coord.iloc[i]['lon'],marker_coord.iloc[i]['lat']], popup=popup).add_to(m)
    LayerControl().add_to(m)
    map = str(year)+'.html'
    m.save(map)
    webbrowser.open('file://'+os.path.realpath(map))
예제 #18
0
def test_rectangle():
    m = Map()

    location = [[45.6, -122.8], [45.61, -122.7]]
    rectangle = Rectangle(
        bounds=location,
        popup='I am a rectangle',
        color='black',
        weight=2,
        fill_opacity=0.6,
        opacity=1,
        fill=True,
        )
    rectangle.add_to(m)

    expected_options = {
        'bubblingMouseEvents': True,
        'color': 'black',
        'dashArray': None,
        'dashOffset': None,
        'fill': True,
        'fillColor': 'black',
        'fillOpacity': 0.6,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'opacity': 1,
        'stroke': True,
        'weight': 2,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.rectangle(
    {location},
    {{
    "bubblingMouseEvents": true,
    "color": "black",
    "dashArray": null,
    "dashOffset": null,
    "fill": true,
    "fillColor": "black",
    "fillOpacity": 0.6,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "opacity": 1,
    "stroke": true,
    "weight": 2
    }}
    )
    .addTo({map});
    """.format(name=rectangle.get_name(), location=location, map=m.get_name())

    rendered = rectangle._template.module.script(rectangle)
    assert rendered.strip().split() == expected_rendered.strip().split()
    assert rectangle.get_bounds() == location
    assert json.dumps(rectangle.to_dict()) == rectangle.to_json()
    assert rectangle.options == json.dumps(expected_options, sort_keys=True, indent=2)  # noqa
예제 #19
0
def test_mulyipolyline():
    m = Map()

    locations = [[[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]],
                 [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]]]

    multipolyline = PolyLine(locations=locations, popup='MultiPolyLine')
    multipolyline.add_to(m)

    expected_options = {
        'smoothFactor': 1.0,
        'noClip': False,
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'opacity': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polyline(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations,
               name=multipolyline.get_name(),
               map=m.get_name())

    rendered = multipolyline._template.module.script(multipolyline)
    assert normalize(rendered) == normalize(expected_rendered)
    assert multipolyline.get_bounds() == get_bounds(locations)
    assert json.dumps(multipolyline.to_dict()) == multipolyline.to_json()
    assert multipolyline.options == expected_options
예제 #20
0
def generate_web_map_html(filename: str) -> None:
    map = Map(location=[48.7767982, -121.8109970])
    volcanoes_feature_group = get_volcanoes_feature_group()
    population_feature_group = get_population_feature_group()
    map.add_child(volcanoes_feature_group)
    map.add_child(population_feature_group)
    map.add_child(LayerControl())
    map.save(filename)
예제 #21
0
def get_beds():
    df = get_df()
    _map = Map(location=[41.8781, -87.6298],
               tiles='cartodbpositron',
               zoom_start=10)
    for idx, row in df.iterrows():
        Marker([row['Y'], row['X']], popup=row['HOSPITAL_NAME']).add_to(_map)
    _map.save('templates/all_beds.html')
예제 #22
0
def folium_add_map_title(title: str, folium_map: folium.Map):
  """Adds a map title"""
  html = '''
     <div style=”position: fixed;
     bottom: 50px; left: 50px; width: 100px; height: 90px;
     border:2px solid grey; z-index:9999; font-size:10pt;
     “>{}</div>'''.format(title)
  folium_map.get_root().html.add_child(folium.Element(html))
예제 #23
0
def save_map(date):
    valencia = [39.4561165311493, -0.3545661635]
    mapa = Map(location=valencia, tiles='OpenStreetMap', zoom_start=10)
    GeoJson(open('voronoi.json'), name='Diagrama de Voronoi').add_to(mapa)
    GeoJson(open('estaciones_de_recarga_' + date + '.json'),
            name='Estaciones de Recarga').add_to(mapa)
    LayerControl().add_to(mapa)
    mapa.save('valencia_' + date + '.html')
예제 #24
0
def test_polygon_marker():
    m = Map()
    locations = [[35.6636, 139.7634], [35.6629, 139.7664], [35.6663, 139.7706],
                 [35.6725, 139.7632], [35.6728, 139.7627], [35.6720, 139.7606],
                 [35.6682, 139.7588], [35.6663, 139.7627]]
    polygon = Polygon(locations=locations, popup='I am a polygon')
    polygon.add_to(m)

    expected_options = {
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'noClip': False,
        'opacity': 1.0,
        'smoothFactor': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polygon(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations, name=polygon.get_name(), map=m.get_name())

    rendered = polygon._template.module.script(polygon)
    assert _normalize(rendered) == _normalize(expected_rendered)
    assert polygon.get_bounds() == get_bounds(locations)
    assert json.dumps(polygon.to_dict()) == polygon.to_json()
    assert polygon.options == json.dumps(expected_options,
                                         sort_keys=True,
                                         indent=2)  # noqa
예제 #25
0
def test_mulyipolyline():
    m = Map()

    locations = [[[45.51, -122.68], [37.77, -122.43], [34.04, -118.2]],
                 [[40.78, -73.91], [41.83, -87.62], [32.76, -96.72]]]

    multipolyline = PolyLine(locations=locations, popup='MultiPolyLine')
    multipolyline.add_to(m)

    expected_options = {
        'smoothFactor': 1.0,
        'noClip': False,
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'opacity': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polyline(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations, name=multipolyline.get_name(), map=m.get_name())

    rendered = multipolyline._template.module.script(multipolyline)
    assert normalize(rendered) == normalize(expected_rendered)
    assert multipolyline.get_bounds() == get_bounds(locations)
    assert json.dumps(multipolyline.to_dict()) == multipolyline.to_json()
    assert multipolyline.options == expected_options
예제 #26
0
def test_marker_popups():
    m = Map()
    features.Marker([45,-180],popup='-180').add_to(m)
    features.Marker([45,-120],popup=Popup('-120')).add_to(m)
    features.RegularPolygonMarker([45,-60],popup='-60').add_to(m)
    features.RegularPolygonMarker([45,0],popup=Popup('0')).add_to(m)
    features.CircleMarker([45,60],popup='60').add_to(m)
    features.CircleMarker([45,120],popup=Popup('120')).add_to(m)
    m._repr_html_()
예제 #27
0
def test_marker_popups():
    m = Map()
    features.Marker([45, -180], popup='-180').add_to(m)
    features.Marker([45, -120], popup=Popup('-120')).add_to(m)
    features.RegularPolygonMarker([45, -60], popup='-60').add_to(m)
    features.RegularPolygonMarker([45, 0], popup=Popup('0')).add_to(m)
    features.CircleMarker([45, 60], popup='60').add_to(m)
    features.CircleMarker([45, 120], popup=Popup('120')).add_to(m)
    m._repr_html_()
 def initialize_canvass(self, center=None) -> None:
     """
     determine the center based on a given locations by finding the latitude mean and longitude mean
     """
     if self.canvass is None:
         if center is None:
             self.canvass = Map(location=self.center, zoom_start=6)
         else:
             self.canvass = Map(location=center, zoom_start=6)
예제 #29
0
def test_custom_pane_show():
    m = Map()
    pane = CustomPane('test-name', z_index=625, pointer_events=False).add_to(m)
    rendered = pane._template.module.script(this=pane, kwargs={})
    expected = """
    var {pane_name} = {map_name}.createPane("test-name");
    {pane_name}.style.zIndex = 625;
    {pane_name}.style.pointerEvents = 'none';
    """.format(pane_name=pane.get_name(), map_name=m.get_name())
    assert normalize(rendered) == normalize(expected)
예제 #30
0
def save(mape: folium.Map, path: str):
    """fct qui save et open une map"""

    assert isinstance(mape, folium.Map), "mape must a folium.Map, not {}" \
        .format(type(mape))
    assert isinstance(path, str), "path must be a str, not {}" \
        .format(type(path))

    mape.save(path)
    webbrowser.open(path)
예제 #31
0
 def _build_canvass(self, locations):
     lat_sum = 0
     lon_sum = 0
     for row in locations:
         lat_sum = lat_sum + row[0]
         lon_sum = lon_sum + row[1]
     average_lat = lat_sum / len(locations)
     average_lon = lon_sum / len(locations)
     center = [average_lat, average_lon]
     self.canvass = Map(location=center, zoom_start=6)
예제 #32
0
def test_polyline_popups():
    m = Map([43, -100], zoom_start=4)
    features.PolyLine([[40, -80], [45, -80]], popup="PolyLine").add_to(m)
    features.PolyLine([[40, -90], [45, -90]],
                      popup=Popup("PolyLine")).add_to(m)
    features.MultiPolyLine([[[40, -110], [45, -110]]],
                           popup="MultiPolyLine").add_to(m)
    features.MultiPolyLine([[[40, -120], [45, -120]]],
                           popup=Popup("MultiPolyLine")).add_to(m)
    m._repr_html_()
예제 #33
0
def test_polyline():
    m = Map()
    locations = [[40, -80], [45, -80]]
    polyline = PolyLine(locations=locations, popup='I am PolyLine')
    polyline.add_to(m)

    expected_options = {
        'smoothFactor': 1.0,
        'noClip': False,
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'opacity': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polyline(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations, name=polyline.get_name(), map=m.get_name())

    rendered = polyline._template.module.script(polyline)
    assert rendered.strip().split() == expected_rendered.strip().split()
    assert polyline.get_bounds() == get_bounds(locations)
    assert json.dumps(polyline.to_dict()) == polyline.to_json()
    assert polyline.options == json.dumps(expected_options, sort_keys=True, indent=2)  # noqa
예제 #34
0
def test_wms_service():
    m = Map([40, -100], zoom_start=4)
    url = 'http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi'
    w = features.WmsTileLayer(url,
                              name='test',
                              format='image/png',
                              layers='nexrad-n0r-900913',
                              attr=u"Weather data © 2012 IEM Nexrad",
                              transparent=True)
    w.add_to(m)
    m._repr_html_()
예제 #35
0
def test_polyline():
    m = Map()
    locations = [[40.0, -80.0], [45.0, -80.0]]
    polyline = PolyLine(locations=locations, popup='I am PolyLine')
    polyline.add_to(m)

    expected_options = {
        'smoothFactor': 1.0,
        'noClip': False,
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'opacity': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polyline(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations, name=polyline.get_name(), map=m.get_name())

    rendered = polyline._template.module.script(polyline)
    assert normalize(rendered) == normalize(expected_rendered)
    assert polyline.get_bounds() == get_bounds(locations)
    assert json.dumps(polyline.to_dict()) == polyline.to_json()
    assert polyline.options == expected_options
예제 #36
0
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_()
예제 #37
0
def test_marker_popups():
    m = Map()
    features.Marker([45, -180], popup="-180").add_to(m)
    features.Marker([45, -120], popup=Popup("-120")).add_to(m)
    features.RegularPolygonMarker([45, -60], popup="-60").add_to(m)
    features.RegularPolygonMarker([45, 0], popup=Popup("0")).add_to(m)
    features.CircleMarker([45, 60], popup="60").add_to(m)
    features.CircleMarker([45, 120], popup=Popup("120")).add_to(m)
    m._repr_html_()

    bounds = m.get_bounds()
    assert bounds == [[45, -180], [45, 120]], bounds
예제 #38
0
파일: test_map.py 프로젝트: zewdu94/folium
def test_popup_show():
    m = Map()
    popup = Popup('Some text.', show=True).add_to(m)
    rendered = popup._template.render(this=popup, kwargs={})
    expected = """
    var {popup_name} = L.popup({{maxWidth: \'300\' , autoClose: false}});
    var {html_name} = $(`<div id="{html_name}" style="width: 100.0%; height: 100.0%;">Some text.</div>`)[0];
    {popup_name}.setContent({html_name});
    {map_name}.bindPopup({popup_name}).openPopup();
    """.format(popup_name=popup.get_name(),
               html_name=list(popup.html._children.keys())[0],
               map_name=m.get_name())
    assert _normalize(rendered) == _normalize(expected)
예제 #39
0
def test_marker_popups():
    m = Map()
    folium.Marker([45, -180], popup='-180').add_to(m)
    folium.Marker([45, -120], popup=Popup('-120')).add_to(m)
    folium.RegularPolygonMarker([45, -60], popup='-60').add_to(m)
    folium.RegularPolygonMarker([45, 0], popup=Popup('0')).add_to(m)
    folium.CircleMarker([45, 60], popup='60').add_to(m)
    folium.CircleMarker([45, 120], popup=Popup('120')).add_to(m)
    folium.CircleMarker([45, 90], popup=Popup('90'), weight=0).add_to(m)
    m._repr_html_()

    bounds = m.get_bounds()
    assert bounds == [[45, -180], [45, 120]], bounds
예제 #40
0
def test_wms_service():
    m = Map([40, -100], zoom_start=4)
    url = "http://mesonet.agron.iastate.edu/cgi-bin/wms/nexrad/n0r.cgi"
    w = features.WmsTileLayer(
        url,
        name="test",
        format="image/png",
        layers="nexrad-n0r-900913",
        attr=u"Weather data © 2012 IEM Nexrad",
        transparent=True,
    )
    w.add_to(m)
    m._repr_html_()

    bounds = m.get_bounds()
    assert bounds == [[None, None], [None, None]], bounds
예제 #41
0
def make_map(bbox, **kw):
    """
    Creates a folium map instance for SECOORA.

    Examples
    --------
    >>> from folium import Map
    >>> bbox = [-87.40, 24.25, -74.70, 36.70]
    >>> m = make_map(bbox)
    >>> isinstance(m, Map)
    True

    """
    from folium import Map

    line = kw.pop('line', True)
    states = kw.pop('states', True)
    layers = kw.pop('layers', True)
    hf_radar = kw.pop('hf_radar', True)
    zoom_start = kw.pop('zoom_start', 5)
    secoora_stations = kw.pop('secoora_stations', True)

    lon, lat = np.array(bbox).reshape(2, 2).mean(axis=0)
    m = Map(width='100%', height='100%',
            location=[lat, lon], zoom_start=zoom_start)

    if hf_radar:
        url = "http://hfrnet.ucsd.edu/thredds/wms/HFRNet/USEGC/6km/hourly/RTV"
        m.add_wms_layer(wms_name="HF Radar",
                        wms_url=url,
                        wms_format="image/png",
                        wms_layers='surface_sea_water_velocity')

    if layers:
        add = 'MapServer/tile/{z}/{y}/{x}'
        base = 'http://services.arcgisonline.com/arcgis/rest/services'
        ESRI = dict(Imagery='World_Imagery/MapServer',
                    Ocean_Base='Ocean/World_Ocean_Base',
                    Topo_Map='World_Topo_Map/MapServer',
                    Street_Map='World_Street_Map/MapServer',
                    Physical_Map='World_Physical_Map/MapServer',
                    Terrain_Base='World_Terrain_Base/MapServer',
                    NatGeo_World_Map='NatGeo_World_Map/MapServer',
                    Shaded_Relief='World_Shaded_Relief/MapServer',
                    Ocean_Reference='Ocean/World_Ocean_Reference',
                    Navigation_Charts='Specialty/World_Navigation_Charts')
        for tile_name, url in ESRI.items():
            tile_url = '{}/{}/{}'.format(base, url, add)
            m.add_tile_layer(tile_name=tile_name,
                             tile_url=tile_url)

    m.add_layers_to_map()
    if line:
        # Create the map and add the bounding box line.
        kw = dict(line_color='#FF0000', line_weight=2)
        m.line(get_coordinates(bbox), **kw)
    if states:
        path = 'https://raw.githubusercontent.com/ocefpaf/secoora/factor_map/'
        path += 'notebooks/secoora.json'
        m.geo_json(geo_path=path,
                   fill_color='none', line_color='Orange')
    if secoora_stations:
        for x, y, name in zip(df['lon'], df['lat'], df['ID']):
            if not np.isnan(x) and not np.isnan(y):
                location = y, x
                popup = '<b>{}</b>'.format(name)
                kw = dict(radius=500, fill_color='#3186cc', popup=popup,
                          fill_opacity=0.2)
                m.circle_marker(location=location, **kw)
    return m
예제 #42
0
def test_rectangle():
    m = Map()

    location = [[45.6, -122.8], [45.61, -122.7]]
    rectangle = Rectangle(
        bounds=location,
        popup='I am a rectangle',
        color='black',
        weight=2,
        fill_opacity=0.6,
        opacity=1,
        fill=True,
        )
    rectangle.add_to(m)

    expected_options = {
        'bubblingMouseEvents': True,
        'color': 'black',
        'dashArray': None,
        'dashOffset': None,
        'fill': True,
        'fillColor': 'black',
        'fillOpacity': 0.6,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'noClip': False,
        'opacity': 1,
        'smoothFactor': 1.0,
        'stroke': True,
        'weight': 2,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.rectangle(
    {location},
    {{
    "bubblingMouseEvents": true,
    "color": "black",
    "dashArray": null,
    "dashOffset": null,
    "fill": true,
    "fillColor": "black",
    "fillOpacity": 0.6,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 2
    }}
    )
    .addTo({map});
    """.format(name=rectangle.get_name(), location=location, map=m.get_name())

    rendered = rectangle._template.module.script(rectangle)
    assert normalize(rendered) == normalize(expected_rendered)
    assert rectangle.get_bounds() == location
    assert json.dumps(rectangle.to_dict()) == rectangle.to_json()
    assert rectangle.options == expected_options
예제 #43
0
def test_polygon_marker():
    m = Map()
    locations = [[35.6636, 139.7634],
                 [35.6629, 139.7664],
                 [35.6663, 139.7706],
                 [35.6725, 139.7632],
                 [35.6728, 139.7627],
                 [35.6720, 139.7606],
                 [35.6682, 139.7588],
                 [35.6663, 139.7627]]
    polygon = Polygon(locations=locations, popup='I am a polygon')
    polygon.add_to(m)

    expected_options = {
        'bubblingMouseEvents': True,
        'color': '#3388ff',
        'dashArray': None,
        'dashOffset': None,
        'fill': False,
        'fillColor': '#3388ff',
        'fillOpacity': 0.2,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'noClip': False,
        'opacity': 1.0,
        'smoothFactor': 1.0,
        'stroke': True,
        'weight': 3,
    }

    m._repr_html_()
    expected_rendered = """
    var {name} = L.polygon(
    {locations},
    {{
    "bubblingMouseEvents": true,
    "color": "#3388ff",
    "dashArray": null,
    "dashOffset": null,
    "fill": false,
    "fillColor": "#3388ff",
    "fillOpacity": 0.2,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "noClip": false,
    "opacity": 1.0,
    "smoothFactor": 1.0,
    "stroke": true,
    "weight": 3
    }}
    )
    .addTo({map});
    """.format(locations=locations, name=polygon.get_name(), map=m.get_name())

    rendered = polygon._template.module.script(polygon)
    assert normalize(rendered) == normalize(expected_rendered)
    assert polygon.get_bounds() == get_bounds(locations)
    assert json.dumps(polygon.to_dict()) == polygon.to_json()
    assert polygon.options == expected_options
예제 #44
0
def test_circle_marker():
    m = Map()
    radius = 50
    popup = 'I am {} pixels'.format(radius)
    location = [-27.55, -48.8]

    circle_marker = CircleMarker(
        location=location,
        radius=radius,
        color='black',
        weight=2,
        fill_opacity=0.6,
        opacity=1,
        fill=True,
        popup=popup,
    )
    circle_marker.add_to(m)

    options = {
        'bubblingMouseEvents': True,
        'color': 'black',
        'dashArray': None,
        'dashOffset': None,
        'fill': True,
        'fillColor': 'black',
        'fillOpacity': 0.6,
        'fillRule': 'evenodd',
        'lineCap': 'round',
        'lineJoin': 'round',
        'opacity': 1,
        'radius': radius,
        'stroke': True,
        'weight': 2,
    }

    m._repr_html_()
    expected_bounds = [location, location]
    expected_rendered = """
    var {name} = L.circleMarker(
    {location},
    {{
    "bubblingMouseEvents": true,
    "color": "black",
    "dashArray": null,
    "dashOffset": null,
    "fill": true,
    "fillColor": "black",
    "fillOpacity": 0.6,
    "fillRule": "evenodd",
    "lineCap": "round",
    "lineJoin": "round",
    "opacity": 1,
    "radius": {radius},
    "stroke": true,
    "weight": 2
    }}
    )
    .addTo({map});
    """.format(name=circle_marker.get_name(), location=location, radius=radius, map=m.get_name())  # noqa

    rendered = circle_marker._template.module.script(circle_marker)
    assert normalize(rendered) == normalize(expected_rendered)
    assert circle_marker.get_bounds() == expected_bounds
    assert json.dumps(circle_marker.to_dict()) == circle_marker.to_json()
    assert circle_marker.location == location
    assert circle_marker.options == options
예제 #45
0
파일: main.py 프로젝트: Paradoxeuh/pyMetro
from folium import Map

map_osm = Map(location=[45.5236, -122.6750], tiles='Stamen Toner', zoom_start=13, max_zoom=14, min_zoom=10,
              min_lat=45.4, max_lat=45.6, min_long=-122.7, max_long=-122.5)
map_osm.create_map(path='osm.html')