# cmap needs normalized data
#style_n_times = lambda x: {'color': rgb2hex(cmap((x['properties']['n_times']-cmin_n_times)/(cmax_n_times-cmin_n_times))), 'weight': 5} 
style_n_times = lambda x: {'color': rgb2hex(cmap((min(cmax_n_times,x['properties']['n_times'])   -cmin_n_times)/(cmax_n_times-cmin_n_times))), 'weight': 5} 
tooltip_n_times = folium.features.GeoJsonTooltip(fields=['n_times'], aliases=['n_times'])


#fmap = folium.Map(location = [53.545612, -113.490067], zoom_start= 10.5)
#fmap = folium.Map(location=[37.862606, -121.978372], tiles='Stamen Terrain', zoom_start=11, control_scale=True)
fmap = folium.Map(location=[37.862606, -121.978372], tiles='Stamen Terrain', zoom_start=13, control_scale=True)

# set up Folium map
#fmap = folium.Map(tiles = None, prefer_canvas=True, disable_3d=True)
#fmap = folium.Map(tiles='Stamen Terrain', prefer_canvas=True, disable_3d=True)
#fmap = folium.Map(tiles='Stamen Terrain', name='Terrain Map', location=[34.862606, -121.978372], zoom_start=10) 
# folium.TileLayer(tiles = 'Stamen Terrain', name='Terrain Map', show=True).add_to(fmap)
folium.TileLayer(tiles = 'CartoDB dark_matter', name='CartoDB', show=False).add_to(fmap)
folium.TileLayer(tiles = 'OpenStreetMap', name='OpenStreetMap', show=False).add_to(fmap)
cmap = cm.get_cmap('jet') # matplotlib colormap
print('appending features to map ')

# add heatmap
#folium.GeoJson(geojson_data_track,   style_function=style_track, name='track', show=True, smooth_factor=3.0).add_to(fmap)
folium.GeoJson(geojson_data_n_times, style_function=style_n_times, tooltip=tooltip_n_times, name='n_times', show=True, smooth_factor=3.0).add_to(fmap)
# add th
for n in range(0, n_th, 1):
    #folium.Marker([th_lat[n], th_lon[n]]).add_to(fmap)
    #folium.Marker([th_lat[n], th_lon[n]], fill_color='#43d9de', radius=8).add_to(fmap)
    folium.Marker([th_lat[n], th_lon[n]], fill_color='#43d9de', radius=4).add_to(fmap)
    # popup=df_counters['Name'][point], icon=folium.Icon(color='darkblue', icon_color='white', icon='male', angle=0, prefix='fa')).add_to(marker_cluster)

# add recent tracks        
Example #2
0
    def generate_html(nilpop, filepath):
        mymap = folium.Map(location=[40.715, -73.905], zoom_start=10.5, tiles=None)
        folium.TileLayer(
            "CartoDB positron", name="Districts Type HeatMap", control=False
        ).add_to(mymap)

        highlight_function = lambda x: {
            "fillColor": "#000000",
            "color": "#000000",
            "fillOpacity": 0.50,
            "weight": 0.1,
        }

        colorscale = branca.colormap.linear.YlOrRd_09.scale(0, 5e1)

        def style_function(feature):
            employed = nilpop.get(
                feature["properties"]["person_business_density"], None
            )
            #     nilpop['person_business_density']
            return {
                "fillOpacity": 0.4,
                "weight": 0,
                "fillColor": "#black" if employed is None else colorscale(employed),
                "color": "#000000",
                "fillOpacity": 0.1,
                "weight": 0.0,
            }

        mymap.choropleth(
            geo_data=nilpop,
            name="Choropleth",
            data=nilpop,
            columns=["ID_DISTICT", "person_business_density"],
            key_on="feature.properties.ID_DISTICT",
            fill_color="PuRd",
            nan_fill_color="white",
            # threshold_scale=myscale,
            # bins=colorscale,
            fill_opacity=1,
            line_opacity=0.2,
            legend_name="Person Business Density",
            smooth_factor=0,
        )

        NIL = folium.features.GeoJson(
            nilpop,
            style_function=style_function,
            control=False,
            highlight_function=highlight_function,
            tooltip=folium.features.GeoJsonTooltip(
                fields=[
                    "ID_DISTICT",
                    "NAME_DISTICT",
                    "population",
                    "area",
                    "type",
                    "quantity",
                    "person_business_density",
                ],
                aliases=[
                    "District Code: ",
                    "District Name: ",
                    "Dictrict population: ",
                    "District Area:",
                    "Type of Business",
                    "quantity",
                    "Person/Business density: ",
                ],
                style=(
                    "background-color: white; color: #333333; font-family: arial; font-size: 13px; padding: 10px;"
                ),
            ),
        )

        mymap.add_child(NIL)
        mymap.keep_in_front(NIL)
        folium.LayerControl().add_to(mymap)

        with open(filepath, "w+"):
            print(f"Creating file...  {filepath}")

        mymap.save(outfile=filepath)
Example #3
0
def folium_map(geojson_to_overlay,
               layer_name,
               location,
               style_function=None,
               tiles='Stamen Terrain',
               zoom_start=16,
               show_layer_control=True,
               width='100%',
               height='75%',
               attr=None,
               map_zoom=18,
               max_zoom=20,
               tms=False,
               zoom_beyond_max=None,
               base_tiles='OpenStreetMap',
               opacity=1):
    m = folium.Map(location=location,
                   zoom_start=zoom_start,
                   width=width,
                   height=height,
                   max_zoom=map_zoom,
                   tiles=base_tiles)
    tiles = folium.TileLayer(tiles=tiles,
                             attr=attr,
                             name=attr,
                             max_zoom=max_zoom)
    if tms is True:
        options = json.loads(tiles.options)
        options.update({'tms': True})
        tiles.options = json.dumps(options, sort_keys=True, indent=2)
        tiles._template = jinja2.Template(u"""
        {% macro script(this, kwargs) %}
            var {{this.get_name()}} = L.tileLayer(
                '{{this.tiles}}',
                {{ this.options }}
                ).addTo({{this._parent.get_name()}});
        {% endmacro %}
        """)
    if zoom_beyond_max is not None:
        options = json.loads(tiles.options)
        options.update({'maxNativeZoom': zoom_beyond_max, 'maxZoom': max_zoom})
        tiles.options = json.dumps(options, sort_keys=True, indent=2)
        tiles._template = jinja2.Template(u"""
        {% macro script(this, kwargs) %}
            var {{this.get_name()}} = L.tileLayer(
                '{{this.tiles}}',
                {{ this.options }}
                ).addTo({{this._parent.get_name()}});
        {% endmacro %}
        """)
    if opacity < 1:
        options = json.loads(tiles.options)
        options.update({'opacity': opacity})
        tiles.options = json.dumps(options, sort_keys=True, indent=2)
        tiles._template = jinja2.Template(u"""
        {% macro script(this, kwargs) %}
            var {{this.get_name()}} = L.tileLayer(
                '{{this.tiles}}',
                {{ this.options }}
                ).addTo({{this._parent.get_name()}});
        {% endmacro %}
        """)

    tiles.add_to(m)
    if style_function is not None:
        gj = folium.GeoJson(geojson_to_overlay,
                            overlay=True,
                            name=layer_name,
                            style_function=style_function)
    else:
        gj = folium.GeoJson(geojson_to_overlay, overlay=True, name=layer_name)
    gj.add_to(m)

    if show_layer_control is True:
        folium.LayerControl().add_to(m)

    return m
import ee
import folium
from folium import plugins

ee.Initialize()

# Add custom basemaps to folium
basemaps = {
    'Google Maps':
    folium.TileLayer(
        tiles='https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
        attr='Google',
        name='Google Maps',
        overlay=True,
        control=True),
    'Google Satellite':
    folium.TileLayer(
        tiles='https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',
        attr='Google',
        name='Google Satellite',
        overlay=True,
        control=True),
    'Google Terrain':
    folium.TileLayer(
        tiles='https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',
        attr='Google',
        name='Google Terrain',
        overlay=True,
        control=True),
    'Google Satellite Hybrid':
    folium.TileLayer(
Example #5
0
# pour avoir le nbr par catégorie. à faire
# with open(
#     "communes-ile-de-france_fleurs_4",
# ) as f:
#     data_fleurs = json.load(f, encoding="utf-8")
# print(len(data_fleurs["features"]))

# création map centrée sur Paris
m = folium.Map(
    location=[48.7, 2.3],
    zoom_start=9,
    tiles=None,
)

folium.TileLayer("CartoDB positron", name="Light Map", control=False).add_to(m)

# define the color of the Geojon data (https://leafletjs.com/reference-1.6.0.html#path-option)
colorlist = ["#f6eff7", "#bdc9e1", "#67a9cf", "#1c9099", "#016c59"]


def style_function(number):
    return lambda x: {
        "color": colorlist[number],
        "fillOpacity": 0.5,
        "weight": 0.1,
    }


highlight_function = lambda x: {
    "fillColor": "#000000",
Example #6
0
    text = folium.Html(text, script=True)
    return folium.Popup(text, max_width=2650)


# In[20]:

import folium
from folium.plugins import MarkerCluster, HeatMap, Fullscreen
from folium import plugins

tiles_url = 'https://{s}.basemaps.cartocdn.com/rastertiles/voyager/{z}/{x}/{y}{r}.png'
attrb = '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors &copy; <a href="https://carto.com/attributions">CARTO</a>'
m = folium.Map(tiles=None)

folium.TileLayer(tiles_url,
                 attr=attrb,
                 name='Mapeo Asociados Toluca',
                 show=True).add_to(m)

folium.Marker(destination, icon=folium.Icon(color='red')).add_to(m)

for i in range(len(graph.edges)):
    for j in range(len(graph.edges)):
        if graph.edges[i, j] != np.inf:
            node = graph.node[i]
            nd = graph.node[j]
            text = f'<p>{format_distance(graph.edges[i,j])}</p>'
            text = folium.Html(text, script=True)
            popup = folium.Popup(text, max_width=2650)
            popup = create_edge_table(graph, i, j)
            folium.PolyLine([[node.x, node.y], [nd.x, nd.y]],
                            popup=popup,
Example #7
0
import pandas as pd
import folium
import folium.plugins
import re

df = pd.read_csv('poltava.csv', sep=';', encoding='cp1251')
df1 = pd.read_csv('poltava_geo.csv', sep=";")
map1 = folium.Map([df1.iloc[0][0], df1.iloc[0][1]], zoom_start=9)
dark = folium.FeatureGroup(name="darkness")
fg = [
    folium.FeatureGroup(name=str(i + 1) + " марта", overlay=False)
    for i in range(30)
]
folium.TileLayer('openstreetmap', overlay=True).add_to(map1)
sh = df1.shape[0]
s = pd.Series(range(len(df1)), index=pd.MultiIndex.from_arrays(df1.values.T))
s = s.sort_index()

i = 0
while i < sh:
    strok = '<table border=1>'
    idx = s[df1.iloc[i][0], df1.iloc[i][1]]
    s1 = re.match(r'[\d]*', str(df.iloc[i][0]))

    for j in idx.values:
        s2 = re.match(r'[\d]*', str(df.iloc[j][0]))
        #print(s1[0], s2[0])
        if s1[0] == s2[0]:
            strok += '<tr><td>' + str(df.iloc[j][0]) + '</td><td>' + str(
                df.iloc[j][1]) + '</td><td>' + str(
                    df.iloc[j][2]) + '</td></tr>'
Example #8
0
# Read in shapefile as a GeoDataframe
streets = gpd.read_file(MAP_FP + 'inter_and_non_int.shp')

# Set the projection as EPSG:3857 since the shapefile didn't export with one
streets.crs = {'init': 'epsg:3857'}

# Then reproject to EPSG:4326 to match what Leaflet uses
streets = streets.to_crs({'init': 'epsg:4326'})

### Make map

# First create basemap
boston_map = folium.Map([42.3601, -71.0589],
                        tiles='Cartodb dark_matter',
                        zoom_start=12)
folium.TileLayer('Cartodb Positron').add_to(boston_map)

# Create style function to color segments based on their risk score
color_scale = cm.linear.YlOrRd.scale(0, 1)
#color_scale = cm.linear.YlOrRd.scale(streets_w_risk[args.colname].min(),
#                                     streets_w_risk[args.colname].max())

# Plot model predictions as separate layers
for model in match:
    predictions = process_data(model[1], model[2])
    add_layer(predictions, model[0], model[2], boston_map)

# Add control to toggle between model layers
folium.LayerControl(position='bottomright').add_to(boston_map)

# Finally, add legend
Example #9
0
def show(request):
    map = folium.Map(  #tiles='Stamen Terrain',
        width=1000,
        height=500,
        location=[19.869777, 75.339153],
        zoom_start=14)

    folium.TileLayer('openstreetmap').add_to(map)
    #folium.TileLayer('StamenTerrain').add_to(map)
    #not working properly , only work if mention in folium.Map()
    folium.TileLayer('stamentoner').add_to(map)
    folium.TileLayer('stamenwatercolor').add_to(map)
    folium.TileLayer('cartodbpositron').add_to(map)
    folium.TileLayer('cartodbdark_matter').add_to(map)

    folium.LayerControl(collapsed=False).add_to(map)
    #above line will add layers in map(i.e radio button to choose different tiles)

    folium.Marker(location=[19.873038, 75.328386],
                  popup="<strong>Kranti Chowk</strong>",
                  tooltip="click here for more info").add_to(map)
    #above will display marker on given location

    locationbluecir = [19.852510, 75.319102]
    bluecircleicon = folium.features.CustomIcon(os.path.join(
        BASE_DIR, 'foliumapp\static\circle.png'),
                                                icon_size=(15, 15))
    popupblucircle = "<strong>GetStarted</strong>"
    folium.Marker(location=locationbluecir,
                  tooltip='current location',
                  popup=popupblucircle,
                  icon=bluecircleicon).add_to(map)

    #above code display bluecircle png in given location as Marker

    locationgeca = [19.867789, 75.323893]
    gecaicon = folium.features.CustomIcon(os.path.join(
        BASE_DIR, 'foliumapp\static\geca.png'),
                                          icon_size=(55, 25))
    popupgeca = "<strong>Government College of Engineering Aurangabad</strong>"
    folium.Marker(location=locationgeca,
                  tooltip='G.E.C.A',
                  popup=popupgeca,
                  icon=gecaicon).add_to(map)

    #above code will display image as marker in Map

    #path coordinates to display in map
    points = [[19.872914, 75.328454], [19.871240, 75.327725],
              [19.870392, 75.327117], [19.867116, 75.318938],
              [19.864513, 75.317179], [19.862750, 75.315335],
              [19.860746, 75.311260], [19.861250, 75.308000],
              [19.861210, 75.307249], [19.860988, 75.306799],
              [19.859474, 75.305340], [19.856353, 75.303506],
              [19.854859, 75.302240], [19.852009, 75.319458]]

    folium.PolyLine(points, color="blue", weight=3.5, opacity=1).add_to(map)
    #it will display highlighted path in blue color

    for each in points:
        folium.Marker(location=each, tooltip=each).add_to(map)
    #it will point Marker on the given points

    map.save("map.html")
    #save the map object

    context = {
        'my_map': map._repr_html_()
    }  #{'my_map': map} change to {'my_map': map._repr_html_()}
    #display map on html page

    return render(request, 'map.html', context)
Example #10
0
marker = folium.features.Marker([df_cd.iloc[5, 0], df_cd.iloc[5, 1]],
                                icon=folium.Icon(color='white',
                                                 icon='bicycle',
                                                 icon_color="orange",
                                                 prefix='fa')).add_to(m)
graph_popup.add_to(marker)
marker.add_to(m)

# Linking markers
my_Polygone = folium.Polygon(locations=df_cd,
                             weight=4,
                             color='yellow',
                             opacity=1)
m.add_child(my_Polygone)

folium.TileLayer(tiles='Stamen Terrain', name='Stamen Terrain',
                 show=True).add_to(m)
folium.TileLayer(tiles='cartodb positron', name='cartodb positron',
                 show=True).add_to(m)
folium.TileLayer(tiles="stamentonerbackground",
                 name="stamentoner background",
                 show=True).add_to(m)

# Add a title

title_html = '''
             <h3 align="center" style="color:purple;background-color:#2AAE67;font-size:210%"> <b>Montpellier's bicycle counters</b> </h3>
             '''
m.get_root().html.add_child(folium.Element(title_html))

folium.LayerControl().add_to(m)
# MAGIC 
# MAGIC __Using a sample here for visualization__

# COMMAND ----------

heatmap_sample = points_df.sample(0.001)
heatmap_sample.count()

# COMMAND ----------

import folium
from folium import plugins

points = heatmap_sample.toPandas()[['latitude', 'longitude']]
nyc = folium.Map([40.75466940037548,-73.98365020751953], zoom_start=11, width='80%', height='100%')
folium.TileLayer('Stamen Toner').add_to(nyc)
nyc.add_child(plugins.HeatMap(points.to_numpy(), radius=12))
nyc

# COMMAND ----------

# MAGIC %md ## Geoscan

# COMMAND ----------

geoscan_sample = points_df.sample(0.00035)
geosscan_sample_count = geoscan_sample.count()
print("geosscan_sample_count: ", geosscan_sample_count)

# COMMAND ----------
Example #12
0
# find the row of the house which has the highest price
maxpr=df.loc[df['price'].idxmax()]

# define a function to draw a basemap easily
def generateBaseMap(default_location=[47.5112, -122.257], default_zoom_start=9.4):
    base_map = folium.Map(location=default_location, control_scale=True, zoom_start=default_zoom_start)
    return base_map

df_copy = df.copy()
# select a zipcode for the heatmap
#set(df['zipcode'])
#df_copy = df[df['zipcode']==98001].copy()
df_copy['count'] = 1
basemap = generateBaseMap()
# add carton position map
folium.TileLayer('cartodbpositron').add_to(basemap)
s=folium.FeatureGroup(name='icon').add_to(basemap)
# add a marker for the house which has the highest price
folium.Marker([maxpr['lat'], maxpr['long']],popup='Highest Price: $'+str(format(maxpr['price'],'.0f')),
              icon=folium.Icon(color='green')).add_to(s)
# add heatmap
HeatMap(data=df_copy[['lat','long','count']].groupby(['lat','long']).sum().reset_index().values.tolist(),
        radius=8,max_zoom=13,name='Heat Map').add_to(basemap)
folium.LayerControl(collapsed=False).add_to(basemap)
basemap
features = ['price','bedrooms','bathrooms','sqft_living','sqft_lot','floors','waterfront',
            'view','condition','grade','sqft_above','sqft_basement','yr_built','yr_renovated',
            'zipcode','lat','long','sqft_living15','sqft_lot15']

mask = np.zeros_like(df[features].corr(), dtype=np.bool) 
mask[np.triu_indices_from(mask)] = True 
Example #13
0
def to_map(df, output='all', downscale=5, basemap='hybrid', zoom=9):
    """
    Display RGB on an interactive map.
    Description
    ----------
    Display xarray.Dataset as RGB in a folium map with multiple false color composites and basemap options.
    Parameters
    ----------
    df: xarray.Dataset
        dataset with multiple time steps, including bands "red","green","blue","nir", and "swir1".
    output: string ("all","veg","agri","rgb","water")
        options for displaying false color composite. Values can be either "all" for all combinations, "veg" for 
        vegetation (NIR, Red, Green), "argi" for agriculture (SWIR1, NIR, Blue), "rgb" for true color composite (Red, 
        Green, Blue), and "water" for water (NIR, SWIR1, Red). Defult = "all".
    downscale: float
        a floating number > 1 for downscale image resolution. Default = 5.
    basemap: string ("all","google","terrain","hybrid","esri")
        the type of basemap to be included in the folium map. Values can be either "google" for Google map, "terrain" for 
        Google Terrain, "hybrid" for Google Satellite Hybrid, "esri" for ESRI Satellite basemap, and "all" for all 
        basemap.
    Returns
    -------
    map: Folium Map
        Folium map with scene displayed as RGB images with layer control.
    """

    #error catching
    assert isinstance(df, xr.Dataset), "Input has to be a xarray.Dataset."

    try:
        df.red
        df.green
        df.blue
        df.nir
        df.swir1
    except Exception:
        print("RGB/NIR/SWIR1 bands not found.")

    r_band = df.red.isel(time=0).values
    g_band = df.green.isel(time=0).values
    b_band = df.blue.isel(time=0).values
    nir = df.nir.isel(time=0).values
    swir1 = df.swir1.isel(time=0).values
    stack = np.dstack((r_band, g_band, b_band, nir, swir1))

    #create RGB 3D array
    rgb = processing(df, stack, 0, 1, 2)
    veg = processing(df, stack, 3, 0, 1)
    agri = processing(df, stack, 4, 3, 2)
    water = processing(df, stack, 3, 4, 0)

    #boundary of the image on the map
    min_lon = df.longitude.min().values.astype(np.float) + 0.0
    max_lon = df.longitude.max().values.astype(np.float) + 0.0
    min_lat = df.latitude.min().values.astype(np.float) + 0.0
    max_lat = df.latitude.max().values.astype(np.float) + 0.0

    #create basemap for folium
    basemaps = {
        'Google Maps':
        folium.TileLayer(
            tiles='https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}',
            attr='Google',
            name='Basemap: Google Maps',
            overlay=True,
            control=True),
        'Google Satellite':
        folium.TileLayer(
            tiles='https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}',
            attr='Google',
            name='Basemap: Google Satellite',
            overlay=True,
            control=True),
        'Google Terrain':
        folium.TileLayer(
            tiles='https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}',
            attr='Google',
            name='Basemap: Google Terrain',
            overlay=True,
            control=True),
        'Google Satellite Hybrid':
        folium.TileLayer(
            tiles='https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}',
            attr='Google',
            name='Basemap: Google Satellite Hybrid',
            overlay=True,
            control=True),
        'Esri Satellite':
        folium.TileLayer(
            tiles=
            'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
            attr='Esri',
            name='Basemap: Esri Satellite',
            overlay=True,
            control=True)
    }

    #display layers on map
    map_ = folium.Map(location=[(min_lat + max_lat) / 2,
                                (min_lon + max_lon) / 2],
                      zoom_start=zoom)
    if basemap == 'all':
        basemaps['Esri Satellite'].add_to(map_)
        basemaps['Google Maps'].add_to(map_)
        basemaps['Google Terrain'].add_to(map_)
        basemaps['Google Satellite Hybrid'].add_to(map_)
    elif basemap == 'hybrid':
        basemaps['Google Satellite Hybrid'].add_to(map_)
    elif basemap == 'terrain':
        basemaps['Google Terrain'].add_to(map_)
    elif basemap == 'google':
        basemaps['Google Maps'].add_to(map_)
    elif basemap == 'esri':
        basemaps['Esri Satellite'].add_to(map_)
    else:
        print(
            "Invalid value for basemap argument: Please input 'esri','google','terrain', or 'hybrid'."
        )

    if downscale == "auto":
        factor = len(df.latitude) * len(df.longitude) / 2000000
        rgb = cv2.resize(rgb.astype('float32'),
                         dsize=(math.ceil(len(df.latitude) / factor),
                                math.ceil(len(df.longitude) / factor)),
                         interpolation=cv2.INTER_CUBIC)
        veg = cv2.resize(veg.astype('float32'),
                         dsize=(math.ceil(len(df.latitude) / factor),
                                math.ceil(len(df.longitude) / factor)),
                         interpolation=cv2.INTER_CUBIC)
        agri = cv2.resize(agri.astype('float32'),
                          dsize=(math.ceil(len(df.latitude) / factor),
                                 math.ceil(len(df.longitude) / factor)),
                          interpolation=cv2.INTER_CUBIC)
        water = cv2.resize(water.astype('float32'),
                           dsize=(math.ceil(len(df.latitude) / factor),
                                  math.ceil(len(df.longitude) / factor)),
                           interpolation=cv2.INTER_CUBIC)

    elif downscale != 0:
        assert downscale > 0
        rgb = cv2.resize(rgb.astype('float32'),
                         dsize=(math.ceil(len(df.latitude) / downscale),
                                math.ceil(len(df.longitude) / downscale)),
                         interpolation=cv2.INTER_CUBIC)
        veg = cv2.resize(veg.astype('float32'),
                         dsize=(math.ceil(len(df.latitude) / downscale),
                                math.ceil(len(df.longitude) / downscale)),
                         interpolation=cv2.INTER_CUBIC)
        agri = cv2.resize(agri.astype('float32'),
                          dsize=(math.ceil(len(df.latitude) / downscale),
                                 math.ceil(len(df.longitude) / downscale)),
                          interpolation=cv2.INTER_CUBIC)
        water = cv2.resize(water.astype('float32'),
                           dsize=(math.ceil(len(df.latitude) / downscale),
                                  math.ceil(len(df.longitude) / downscale)),
                           interpolation=cv2.INTER_CUBIC)

    else:
        print("Please input downscale argument larger than 0.")

    if output == "all":
        try:
            folium.raster_layers.ImageOverlay(
                rgb, [[min_lat, min_lon], [max_lat, max_lon]],
                name='RGB').add_to(map_)
            folium.raster_layers.ImageOverlay(
                veg, [[min_lat, min_lon], [max_lat, max_lon]],
                name='Vegetation').add_to(map_)
            folium.raster_layers.ImageOverlay(
                agri, [[min_lat, min_lon], [max_lat, max_lon]],
                name='Agriculture').add_to(map_)
            folium.raster_layers.ImageOverlay(
                water, [[min_lat, min_lon], [max_lat, max_lon]],
                name='Water').add_to(map_)

        except Exception:
            print("Unexpected Error for image overlay.")

    elif output == "rgb":
        folium.raster_layers.ImageOverlay(
            rgb, [[min_lat, min_lon], [max_lat, max_lon]],
            name='RGB').add_to(map_)
    elif output == "veg":
        folium.raster_layers.ImageOverlay(
            veg, [[min_lat, min_lon], [max_lat, max_lon]],
            name='Vegetation').add_to(map_)
    elif output == "agri":
        folium.raster_layers.ImageOverlay(
            agri, [[min_lat, min_lon], [max_lat, max_lon]],
            name='Agriculture').add_to(map_)
    elif output == "water":
        folium.raster_layers.ImageOverlay(
            water, [[min_lat, min_lon], [max_lat, max_lon]],
            name='Water').add_to(map_)
    else:
        print("The input output argument is invalid ({}). \
        Please use 'all', 'rgb', 'veg', 'agri', or 'water'.".format(output))

    folium.LayerControl().add_to(map_)
    return map_
Example #14
0
def meetup_output():
    geolocator = Nominatim()

    user_add = request.args.get('address')
    user_date = request.args.get('date')
    #  user_time = request.args.get('time')
    user_cost = request.args.get('cost')
    the_result = ''
    try:
        in_loc = geolocator.geocode(user_add, timeout=None)
        in_latlon = (in_loc.latitude, in_loc.longitude)
    except:
        the_result = 'Your address is invalid'
        return render_template("nooutput.html", the_result=the_result)
    try:
        float(user_cost)
        evt_query = "SELECT * FROM event_table,newsearch_table WHERE event_table.evt_id=newsearch_table.evt_id AND event_table.fee<=%s AND newsearch_table.e_score>0" % user_cost
    except:
        the_result = 'Cost input is invalid'
        return render_template("nooutput.html", the_result=the_result)
    query_results = pd.read_sql_query(evt_query, con)
    #Event web sites
    evt_urls = query_results['evt_url']
    print len(evt_urls)
    #Event and group names
    event_name = query_results['evt_name']
    nsim_els = query_results['e_score']
    nsim_gls = query_results['g_score']

    #Date and time
    evt_time = [str(i).strip() for i in query_results['date']]
    time_tostr = '%Y-%m-%d'
    epoch_time = numpy.array(
        [time.mktime(time.strptime(i, time_tostr)) for i in evt_time])
    user_base_epoch_time = -1
    try:
        user_base_epoch_time = time.mktime(time.strptime(
            user_date, time_tostr))
    except:
        the_result = 'Date input is invalid'
        return render_template("nooutput.html", the_result=the_result)
    hours = numpy.array([int(i[1:3]) for i in query_results['time']])
    minutes = numpy.array([int(i[4:6]) for i in query_results['time']])
    #user_hours = int(user_time[:2])
    #user_minutes = int(user_time[3:])
    epoch_time = epoch_time + 3600 * hours + 60 * minutes
    user_epoch_time = user_base_epoch_time
    times = [(i - user_epoch_time) for i in epoch_time]

    #Distance
    db_latlons = zip(query_results["lat"], query_results["lon"])
    distances = [vincenty(in_latlon, j).kilometers for j in db_latlons]

    #Get times for walkable and bikeable distances on the input day
    walk_time_dist_url_list = set([
        (i, j, k, l, m, n, o)
        for i, j, k, l, m, n, o in zip(times, distances, evt_urls, nsim_els,
                                       nsim_gls, event_name, db_latlons)
        if j < 1.7 and i > 0 and (i + user_epoch_time) <
        (user_base_epoch_time + 24 * 3600)
    ])
    bike_time_dist_url_list = set([
        (i, j, k, l, m, n, o)
        for i, j, k, l, m, n, o in zip(times, distances, evt_urls, nsim_els,
                                       nsim_gls, event_name, db_latlons)
        if j > 1.7 and j < 5 and i > 0 and (i + user_epoch_time) <
        (user_base_epoch_time + 24 * 3600)
    ])
    walk_time_dist_url_list = list(walk_time_dist_url_list)
    bike_time_dist_url_list = list(bike_time_dist_url_list)
    walk_time_dist_url_list.sort(key=lambda x: x[4], reverse=True)
    bike_time_dist_url_list.sort(key=lambda x: x[4], reverse=True)
    #  walk_time_dist_url_list.sort(key=lambda x: x[3])
    #  bike_time_dist_url_list.sort(key=lambda x: x[3])
    walk_time_dist_url_list = walk_time_dist_url_list[:10]
    bike_time_dist_url_list = bike_time_dist_url_list[:10]
    print 'Groups', len(walk_time_dist_url_list), len(bike_time_dist_url_list)
    walk_time_dist_url_list.sort(key=lambda x: x[3], reverse=True)
    bike_time_dist_url_list.sort(key=lambda x: x[3], reverse=True)
    walk_time_dist_url_list = walk_time_dist_url_list[:5]
    bike_time_dist_url_list = bike_time_dist_url_list[:5]
    #Map the events
    import branca, folium
    map_osm = folium.Map(location=[in_latlon[0], in_latlon[1]],
                         zoom_start=12,
                         width=500,
                         height=500)
    #map_osm.simple_marker([in_latlon[0],in_latlon[1]], popup='Your Location',marker_color='red')
    icon = folium.Icon(color='red', icon='home', prefix='fa')
    folium.Marker([in_latlon[0], in_latlon[1]], icon=icon).add_to(map_osm)

    #Get url, distance and time of soonest events
    walkables = len(walk_time_dist_url_list)
    bikeables = len(bike_time_dist_url_list)
    print 'Result:', walkables, bikeables
    if (walkables == 0 and bikeables == 0):
        the_result = 'No walkable or bikeable events matching your criteria'
        return render_template("nooutput.html", the_result=the_result)
    else:
        #Sort by nerdiness of group name
        #walk_time_dist_url_list.sort(key=lambda x: x[4],reverse=True)
        #bike_time_dist_url_list.sort(key=lambda x: x[4],reverse=True)
        #Keep top 10% most nerdy events, making sure to keep at least 1
        #if(walkables>10):
        #  walk_time_dist_url_list = walk_time_dist_url_list[:(walkables/10)]
        #if(bikeables>10):
        #  bike_time_dist_url_list = bike_time_dist_url_list[:(bikeables/10)]
        #Sort by nerdiness of event name
        walk_urls = []
        walk_names = []
        walk_dists = []
        walk_times = []
        walk_stars = []

        bike_urls = []
        bike_names = []
        bike_dists = []
        bike_times = []
        bike_stars = []
        if (walkables > 0):
            #rand_walk = random.choice(walk_time_dist_url_list)
            for w in walk_time_dist_url_list:
                print 'Walk', w[3]
                #print w
                cur_stars = get_stars(w[3])
                walk_stars.append(get_stars(w[3]))
                walk_urls.append(str(w[2]).strip())
                cur_url = str(w[2]).strip()
                first_name = str(w[5]).rstrip()
                cur_name = first_name.decode('utf-8')
                walk_names.append(first_name.decode('utf-8'))
                walk_dists.append('%.2f' % w[1])
                cur_dist = '%.2f' % w[1]
                walk_times.append(
                    time.strftime('%Y-%m-%d %H:%M:%S',
                                  time.localtime(w[0] + user_epoch_time)))
                cur_time = time.strftime(
                    '%Y-%m-%d %H:%M:%S',
                    time.localtime(w[0] + user_epoch_time))

                marker_html = """<p>""" + cur_stars + """-</p>""" + """<a href=""" + cur_url + """>""" + cur_name + """</a><p>at """ + cur_time + """, within """ + cur_dist + """ kilometers.</p>"""
                iframe = branca.element.IFrame(html=marker_html,
                                               width=300,
                                               height=50)
                popup = folium.Popup(iframe)
                icon = folium.Icon(color='blue', icon='blind', prefix='fa')
                folium.Marker([w[6][0], w[6][1]], popup=popup,
                              icon=icon).add_to(map_osm)
        else:
            first_url = 'www.meetup.com'
            first_name = 'No events'
            first_dist = '0'
            first_time = '24:00'

        if (bikeables > 0):
            #rand_bike = random.choice(bike_time_dist_url_list)
            for b in bike_time_dist_url_list:
                print 'Bike', b[3]
                cur_stars = get_stars(b[3])
                bike_stars.append(get_stars(b[3]))
                cur_url = str(b[2]).strip()
                bike_urls.append(str(b[2]).strip())
                sec_name = str(b[5]).rstrip()
                cur_name = sec_name.decode('utf-8')
                bike_names.append(sec_name.decode('utf-8'))
                cur_dist = '%.2f' % b[1]
                bike_dists.append('%.2f' % b[1])
                cur_time = time.strftime(
                    '%Y-%m-%d %H:%M:%S',
                    time.localtime(b[0] + user_epoch_time))
                bike_times.append(
                    time.strftime('%Y-%m-%d, %H:%M:%S',
                                  time.localtime(b[0] + user_epoch_time)))

                marker_html = """<p>""" + cur_stars + """-</p>""" + """<a href=""" + cur_url + """>""" + cur_name + """</a><p>at """ + cur_time + """, within """ + cur_dist + """ kilometers.</p>"""
                #marker_html="""
                #<a href=""" + cur_url+""">"""+cur_name+"""</a><p>at """ +cur_time+ """, within """ +cur_dist+""" kilometers.</p>
                #"""
                icon = folium.Icon(color='green', icon='bicycle', prefix='fa')
                iframe = branca.element.IFrame(html=marker_html,
                                               width=300,
                                               height=50)
                popup = folium.Popup(iframe)
                folium.Marker([b[6][0], b[6][1]], popup=popup,
                              icon=icon).add_to(map_osm)
        else:
            sec_url = 'www.meetup.com'
            sec_name = 'No events'
            sec_dist = '0'
            sec_time = '24:00'

    folium.TileLayer('cartodbdark_matter').add_to(map_osm)
    tmp_rand = random.choice(xrange(1, 99999))
    map_osm.create_map(path='flaskexample/templates/osm-%s.html' % (tmp_rand))

    if (the_result == ''):
        #return render_template("output.html", first_name=first_name,sec_name=sec_name,first_url=first_url, sec_url=sec_url,first_dist=first_dist,sec_dist=sec_dist,first_time=first_time,sec_time=sec_time)
        return render_template("output.html",
                               tmp_rand=tmp_rand,
                               walk_stars=walk_stars,
                               bike_stars=bike_stars,
                               walkables=walkables,
                               bikeables=bikeables,
                               walk_urls=walk_urls,
                               bike_urls=bike_urls,
                               walk_names=walk_names,
                               bike_names=bike_names,
                               walk_dists=walk_dists,
                               bike_dists=bike_dists,
                               walk_times=walk_times,
                               bike_times=bike_times)
    else:
        # Should never happen now
        return render_template("nooutput.html", the_result=the_result)
Example #15
0
"""
import os
import ee
import folium
from folium import plugins
from .common import *
from .conversion import *
from .legends import builtin_legends


# More WMS basemaps can be found at https://viewer.nationalmap.gov/services/
ee_basemaps = {
    "ROADMAP": folium.TileLayer(
        tiles="https://mt1.google.com/vt/lyrs=m&x={x}&y={y}&z={z}",
        attr="Google",
        name="Google Maps",
        overlay=True,
        control=True,
    ),
    "SATELLITE": folium.TileLayer(
        tiles="https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}",
        attr="Google",
        name="Google Satellite",
        overlay=True,
        control=True,
    ),
    "TERRAIN": folium.TileLayer(
        tiles="https://mt1.google.com/vt/lyrs=p&x={x}&y={y}&z={z}",
        attr="Google",
        name="Google Terrain",
        overlay=True,
    mask = qa.bitwiseAnd(cloudShadowBitMask).eq(0).And(
        qa.bitwiseAnd(cloudsBitMask).eq(0))
    return image.updateMask(mask).select(bands).divide(10000)


#%%
# The image input data is a 2018 cloud-masked median composite.
image = l8sr.filterDate('2018-01-01', '2018-12-31').map(maskL8sr).median()

#%%
# Use folium to visualize the imagery.
mapid = image.getMapId({'bands': ['B4', 'B3', 'B2'], 'min': 0, 'max': 0.3})
map = folium.Map(location=[38., -122.5])
folium.TileLayer(
    tiles=EE_TILES.format(**mapid),
    attr='Google Earth Engine',
    overlay=True,
    name='median composite',
).add_to(map)
map.add_child(folium.LayerControl())
map

#%%
# Change the following two lines to use your own training data.
labels = ee.FeatureCollection('projects/google/demo_landcover_labels')
label = 'landcover'

#%%
# Sample the image at the points and add a random column.
sample = image.sampleRegions(collection=labels, properties=[label],
                             scale=30).randomColumn()
Example #17
0
def poc_polar(hotspot, chals):

    H = Hotspots()
    haddr = hotspot['address']
    hlat, hlng = hotspot['lat'], hotspot['lng']
    hname = hotspot['name']

    if os.path.exists(hname):
        files = glob(hname + '\\*')
        for file in files:
            os.remove(file)
    else:
        os.mkdir(hname)

    wl = {}  #witnesslist
    rl = {
    }  #received list of hotspots(hotspot of intereset has been witness to these or received from them)
    c = 299792458

    for chal in chals:  # loop through challenges

        for p in chal['path']:  #path?

            if p['challengee'] == haddr:  # handles cases where hotspot of interest is transmitting
                for w in p[
                        'witnesses']:  #loop through witnesses so we can get rssi at each location challenge received
                    #print('witness',w)
                    lat = H.get_hotspot_by_addr(w['gateway'])['lat']
                    lng = H.get_hotspot_by_addr(w['gateway'])['lng']
                    name = H.get_hotspot_by_addr(w['gateway'])['name']
                    dist_km, heading = utils.haversine_km(hlat,
                                                          hlng,
                                                          lat,
                                                          lng,
                                                          return_heading=True)

                    fspl = 20 * log10((dist_km + 0.01) * 1000) + 20 * log10(
                        915000000) + 20 * log10(4 * pi / c) - 27

                    try:
                        wl[w['gateway']]['lat'] = lat
                        wl[w['gateway']]['lng'] = lng
                        wl[w['gateway']]['rssi'].append(w['signal'])
                    except KeyError:
                        wl[w['gateway']] = {
                            'rssi': [
                                w['signal'],
                            ],
                            'dist_km': dist_km,
                            'heading': heading,
                            'fspl': fspl,
                            'lat': lat,
                            'lng': lng,
                            'name': name
                        }
            else:  # hotspot of interest is not transmitting but may be a witness
                challengee = p['challengee']
                name = H.get_hotspot_by_addr(challengee)['name']
                for w in p['witnesses']:
                    if w['gateway'] != haddr:
                        continue
                    #print('transmitter ', name)
                    #print('witness ', H.get_hotspot_by_addr(w['gateway'])['name']) # hotspot of interest was a witness

                    lat = H.get_hotspot_by_addr(challengee)['lat']
                    lng = H.get_hotspot_by_addr(challengee)['lng']
                    #name=H.get_hotspot_by_addr(w['gateway'])['name']
                    dist_km, heading = utils.haversine_km(hlat,
                                                          hlng,
                                                          lat,
                                                          lng,
                                                          return_heading=True)

                    fspl = 20 * log10((dist_km + 0.01) * 1000) + 20 * log10(
                        915000000) + 20 * log10(4 * pi / c) - 27

                    try:
                        rl[challengee]['lat'] = lat
                        rl[challengee]['lng'] = lng
                        rl[challengee]['rssi'].append(w['signal'])
                    except KeyError:
                        rl[challengee] = {
                            'rssi': [
                                w['signal'],
                            ],
                            'dist_km': dist_km,
                            'heading': heading,
                            'fspl': fspl,
                            'lat': lat,
                            'lng': lng,
                            'name': name
                        }

    #print('rl:',rl)
    ratios = [1.0] * 16
    rratios = [1.0] * 16
    N = len(ratios) - 1
    angles = []
    rangles = []
    #angles = [n / float(N) *2 *pi for n in range(N+1)]
    angles = list(np.arange(0.0, 2 * np.pi + (2 * np.pi / N), 2 * np.pi / N))
    rangles = list(np.arange(0.0, 2 * np.pi + (2 * np.pi / N), 2 * np.pi / N))
    #print(angles,len(angles))
    #print(ratios,len(ratios))

    markers = []
    encoded = {}
    rencoded = {}
    for w in wl:  #for witness in witnesslist
        #print(wl[w])
        mean_rssi = sum(wl[w]['rssi']) / len(wl[w]['rssi'])
        ratio = wl[w]['fspl'] / mean_rssi * (-1)
        if ratio > 3.0:
            ratio = 3.0
        elif ratio < -3.0:
            ratio = -3.0
        ratios.append(ratio)
        angles.append(wl[w]['heading'] * pi / 180)

        #markers.append(folium.Marker([wl[w]['lat'],wl[w]['lng']],popup=wl[w]['name']))
        markers.append([[wl[w]['lat'], wl[w]['lng']], wl[w]['name']])

        # the histogram of the data
        #unique=set(wl[w]['rssi'])
        #num_unique=len(unique)

        n, bins, patches = plt.hist(
            wl[w]['rssi'], 10)  #, density=True, facecolor='g', alpha=0.75,)
        plt.xlabel('RSSI(dB)')
        plt.ylabel('Count(Number of Packets)')
        wit = str(wl[w]['name'])
        plt.title('Packets from ' + hname + ' measured at ' + wit)
        #plt.text(60, .025, r'$\mu=100,\ \sigma=15$')
        #plt.xlim(40, 160)
        #plt.ylim(0, 0.03)
        plt.grid(True)
        #plt.show()
        strFile = str(wl[w]['name']) + '.jpg'
        strWitness = str(wl[w]['name'])

        if os.path.isfile(strFile):
            #print('remove')
            os.remove(strFile)  # Opt.: os.system("rm "+strFile)
        plt.savefig(hname + '//' + strFile)
        encoded[strWitness] = base64.b64encode(
            open(hname + '//' + strFile, 'rb').read())
        plt.close()

    for w in rl:  #for witness in witnesslist
        #print(rl[w])
        mean_rssi = sum(rl[w]['rssi']) / len(rl[w]['rssi'])
        rratio = rl[w]['fspl'] / mean_rssi * (-1)
        if rratio > 3.0:
            rratio = 3.0
        elif rratio < -3.0:
            rratio = -3.0
        rratios.append(rratio)
        rangles.append(rl[w]['heading'] * pi / 180)

        #markers.append([[wl[w]['lat'],wl[w]['lng']],wl[w]['name']])

        n, bins, patches = plt.hist(
            rl[w]['rssi'], 10)  #, density=True, facecolor='g', alpha=0.75,)
        plt.xlabel('RSSI(dB)')
        plt.ylabel('Count(Number of Packets)')
        wit = str(rl[w]['name'])
        plt.title('Packets from ' + wit + ' measured at ' + hname)

        plt.grid(True)
        #plt.show()
        strFile = 'rrr' + str(rl[w]['name']) + '.jpg'
        strWitness = str(rl[w]['name'])

        if os.path.isfile(strFile):
            #print('remove')
            os.remove(strFile)  # Opt.: os.system("rm "+strFile)
        plt.savefig(hname + '//' + strFile)
        rencoded[strWitness] = base64.b64encode(
            open(hname + '//' + strFile, 'rb').read())
        plt.close()

    # create polar chart
    angles, ratios = zip(*sorted(zip(angles, ratios)))
    rangles, rratios = zip(*sorted(zip(rangles, rratios)))
    angles, ratios = (list(t) for t in zip(*sorted(zip(angles, ratios))))
    rangles, rratios = (list(t) for t in zip(*sorted(zip(rangles, rratios))))

    fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)
    #ax.set_rmax(3)
    #ax.set_rmin(-3)
    ax.set_ylim(-3, 3)
    ax.plot(angles,
            ratios,
            marker='^',
            linestyle='solid',
            color='tomato',
            linewidth=2,
            markersize=5,
            label='Transmitting')  #markerfacecolor='m', markeredgecolor='k',
    ax.plot(rangles,
            rratios,
            marker='v',
            linestyle='solid',
            color='dodgerblue',
            linewidth=1,
            markersize=5,
            label='Receiving')  #, markerfacecolor='m', markeredgecolor='k'
    ax.legend(bbox_to_anchor=(0, 1),
              fancybox=True,
              framealpha=0,
              loc="lower left",
              facecolor='#000000')
    plt.xlabel('FSPL/RSSI')

    plt.savefig(hname + '//' + hname + '.png', transparent=True)
    #plt.show()

    # add polar chart as a custom icon in map
    m = folium.Map([hlat, hlng],
                   tiles='stamentoner',
                   zoom_start=18,
                   control_scale=True,
                   max_zoom=20)
    polargroup = folium.FeatureGroup(name='Polar Plot')

    icon = folium.features.CustomIcon(icon_image=hname + '//' +
                                      hotspot['name'] + '.png',
                                      icon_size=(640, 480))
    marker = folium.Marker([hlat, hlng], popup=hotspot['name'], icon=icon)
    polargroup.add_child(marker)

    # add witness markers
    hsgroup = folium.FeatureGroup(name='Witnesses')
    hsgroup.add_child(folium.Marker([hlat, hlng], popup=hotspot['name']))
    # add the witness markers
    for marker in markers:
        #html = '<img src="data:image/jpg;base64,{}">'.format
        html = '<p><img src="data:image/jpg;base64,{}" alt="" width=640 height=480 /></p> \
               <p><img src="data:image/jpg;base64,{}" alt="" width=640 height=480 /></p>'.format

        #print('marker',marker)
        try:
            iframe = IFrame(html(encoded[marker[1]].decode('UTF-8'),
                                 rencoded[marker[1]].decode('UTF-8')),
                            width=640 + 25,
                            height=960 + 40)
            popup = folium.Popup(iframe, max_width=2650)
            mark = folium.Marker(marker[0], popup=popup)
            hsgroup.add_child(mark)
        except KeyError:  # this means this witness never heard from us so there is no marker for it
            pass  # not sure where to put the receive packet histogram so just ignore for now

    radius = 0.01
    center = Point(hlat, hlng)
    circle = center.buffer(radius)  # Degrees Radius
    gjcircle = shapely.geometry.mapping(circle)
    circle = center.buffer(radius * 25)  # Degrees Radius
    gjcircle8 = shapely.geometry.mapping(circle)

    dcgroup = folium.FeatureGroup(name='Distance Circles', show=False)
    radius = 0.01
    center = Point(hlat, hlng)
    circle = center.buffer(radius)  # Degrees Radius
    gjcircle = shapely.geometry.mapping(circle)
    circle = gjcircle['coordinates'][0]
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=300,
                              popup='300m',
                              tooltip='300m')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=1000,
                              popup='1km',
                              tooltip='1km')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=2000,
                              popup='2km',
                              tooltip='2km')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=3000,
                              name='circles',
                              popup='3km',
                              tooltip='3km')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=4000,
                              popup='4km',
                              tooltip='4km')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=5000,
                              popup='5km',
                              tooltip='5km')
    dcgroup.add_child(my_Circle)
    my_Circle = folium.Circle(location=[hlat, hlng],
                              radius=10000,
                              popup='10km',
                              tooltip='10km')
    dcgroup.add_child(my_Circle)

    h3colorgroup = folium.FeatureGroup(name='h3 Hexagon Grid Color Fill',
                                       show=False)
    style = {'fillColor': '#f5f5f5', 'lineColor': '#ffffbf'}
    #polygon = folium.GeoJson(gjson, style_function = lambda x: style).add_to(m)

    h3group = folium.FeatureGroup(name='h3 r11 Hex Grid', show=False)
    h3namegroup = folium.FeatureGroup(name='h3 r11 Hex Grid Names', show=False)
    h3fillgroup = folium.FeatureGroup(name='h3 r11 Hex Grid Color Fill',
                                      show=True)
    h3r8namegroup = folium.FeatureGroup(name='h3 r8 Hex Grid Names',
                                        show=False)
    h3r8group = folium.FeatureGroup(name='h3 r8 Hex Grid', show=False)
    hexagons = list(h3.polyfill(gjcircle, 11))
    hexagons8 = list(h3.polyfill(gjcircle8, 8))
    polylines = []

    lat = []
    lng = []
    i = 0
    #print('hexagon',hexagons[0])
    #print(dir(h3))
    home_hex = h3.geo_to_h3(hlat, hlng, 11)
    a = h3.k_ring(home_hex, 7)
    for h in a:
        gjhex = h3.h3_to_geo_boundary(h, geo_json=True)
        gjhex = geometry.Polygon(gjhex)
        mean_rsrp = -60
        folium.GeoJson(
            gjhex,
            style_function=lambda x, mean_rsrp=mean_rsrp: {
                'fillColor': map_color_rsrp(mean_rsrp),
                'color': map_color_rsrp(mean_rsrp),
                'weight': 1,
                'fillOpacity': 0.5
            },
            #tooltip='tooltip'
        ).add_to(h3fillgroup)

    for hex in hexagons:
        p2 = h3.h3_to_geo(hex)
        #p2 = [45.3311, -121.7113]
        folium.Marker(
            p2,
            name='hex_names',
            icon=DivIcon(
                #icon_size=(150,36),
                #icon_anchor=(35,-45),
                icon_anchor=(35, 0),
                html='<div style="font-size: 6pt; color : black">' + str(hex) +
                '</div>',
            )).add_to(h3namegroup)
        #m.add_child(folium.CircleMarker(p2, radius=15))

        polygons = h3.h3_set_to_multi_polygon([hex], geo_json=False)
        # flatten polygons into loops.
        outlines = [loop for polygon in polygons for loop in polygon]
        polyline = [outline + [outline[0]] for outline in outlines][0]
        lat.extend(map(lambda v: v[0], polyline))
        lng.extend(map(lambda v: v[1], polyline))
        polylines.append(polyline)

    for polyline in polylines:
        my_PolyLine = folium.PolyLine(locations=polyline,
                                      weight=1,
                                      color='blue')
        h3group.add_child(my_PolyLine)

    polylines = []

    lat = []
    lng = []
    #polylines8 = []
    for hex in hexagons8:
        p2 = h3.h3_to_geo(hex)
        folium.Marker(
            p2,
            name='hex_names',
            icon=DivIcon(
                #icon_size=(150,36),
                #icon_anchor=(35,-45),
                icon_anchor=(35, 0),
                html='<div style="font-size: 8pt; color : black">' + str(hex) +
                '</div>',
            )).add_to(h3r8namegroup)

        polygons = h3.h3_set_to_multi_polygon([hex], geo_json=False)
        # flatten polygons into loops.
        outlines = [loop for polygon in polygons for loop in polygon]
        polyline = [outline + [outline[0]] for outline in outlines][0]
        lat.extend(map(lambda v: v[0], polyline))
        lng.extend(map(lambda v: v[1], polyline))
        polylines.append(polyline)

    for polyline in polylines:
        my_PolyLine = folium.PolyLine(locations=polyline,
                                      weight=1,
                                      color='blue')
        h3r8group.add_child(my_PolyLine)

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

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

    polargroup.add_to(m)  #polar plot
    hsgroup.add_to(m)  #hotspots
    dcgroup.add_to(m)  #distance circles
    h3group.add_to(m)
    h3namegroup.add_to(m)
    h3fillgroup.add_to(m)
    m.keep_in_front(h3group)
    h3r8group.add_to(m)
    h3r8namegroup.add_to(m)

    # add the layer control
    folium.LayerControl(collapsed=False).add_to(m)
    m.save(hname + '//' + hname + '_map.html')
Example #18
0
def make_crashmap()->None:
    '''
    crashmap: generates a webpage holding a leaflet / folium map
    '''
    global folium_map
    global map_div
    global hdr_txt
    global script_txt

    start_coords = (-26.52, 153.09)
    folium_map = folium.Map(
        tiles=None,
        location=start_coords,
        zoom_start=13,
        width='80%',
        height='80%',
        control_scale=True,
    )

    # support two basemaps
    folium.TileLayer(tiles='OpenStreetMap', name='Open Street Map', show=True).add_to(
        folium_map
    )

    folium.TileLayer(tiles='stamentoner', name='Black/White Map', show=False).add_to(
        folium_map
    )


    # add un-clustered markers layer
    add_markers(folium_map)

    # add the clustered fatal crash markers layer
    add_clusters(folium_map)

    # add heat map layer
    add_heat_map(folium_map)

    # add control to pick basemap, layers to show
    folium.LayerControl().add_to(folium_map)


    # Extract the components of the web map

    #
    #  The HTML to create a <div> and <iframe> to hold the map
    #
    #  The header text to get styles, scripts, etc
    #
    #  The scripts needed to run

    # first, force map to render as HTML, for us to dissect
    _ = folium_map._repr_html_()

    # get definition of map in body
    map_div = Markup(folium_map.get_root().html.render())

    # html to be included in header
    hdr_txt = Markup(folium_map.get_root().header.render())

    # html to be included in <script>
    script_txt = Markup(folium_map.get_root().script.render())

    return None
def crear_mapa(filtro, viajes, edad, motivo, estrato, dia, habil, horita,
               count):
    viajes = filtracion(filtro, viajes, edad, motivo, estrato, dia, habil,
                        horita)
    df = viajes.copy()
    df = df[[
        'ZAT_ORIGEN', 'ZAT_DESTINO', 'longitude_o', 'latitude_o',
        'longitude_d', 'latitude_d'
    ]]
    if count.empty:
        mapa = folium.Map(location=[4.6471, -74.0906],
                          tiles="openstreetmap",
                          zoom_start=11)
        folium.TileLayer('cartodbdark_matter').add_to(mapa)
    elif len(count) <= 50:
        df = pd.merge(count,
                      df,
                      how='inner',
                      right_on=['ZAT_ORIGEN', 'ZAT_DESTINO'],
                      left_on=['ZAT Origen', 'ZAT Destino'])
        dp = pd.DataFrame(df[[
            'ZAT_ORIGEN', 'ZAT_DESTINO', 'longitude_o', 'latitude_o',
            'longitude_d', 'latitude_d', 'Frecuencia de Viajes'
        ]])
        dp = dp.drop_duplicates(['ZAT_ORIGEN', 'ZAT_DESTINO'], keep='first')
        dp['llave'] = list(zip(dp['ZAT_ORIGEN'], dp['ZAT_DESTINO']))
        dp['or'] = list(zip(dp['longitude_o'], dp['latitude_o']))
        dp['de'] = list(zip(dp['longitude_d'], dp['latitude_d']))
        dp['coords'] = list(zip(dp['or'], dp['de']))
        dp = dp[['llave', 'coords']]
        dp = dp.reset_index()
        dp = dp.set_index('llave').to_dict()
        dp = dp['coords']
        mapa = folium.Map(location=[4.6471, -74.0906],
                          tiles="openstreetmap",
                          zoom_start=11)
        folium.TileLayer('cartodbdark_matter').add_to(mapa)
        for k, v in dp.items():
            popup1 = str(k[0])
            popup2 = str(k[1])
            popup = "Origen: {} <br> Destino: {}"
            popup = popup.format(popup1, popup2)
            icon_url = "https://png.pngtree.com/svg/20170126/my_personal_page_center_area_28538.png"
            icon = folium.features.CustomIcon(icon_url, icon_size=(38, 40))
            folium.Marker(v[0], popup=popup, icon=icon).add_to(mapa)
        for k, v in dp.items():
            tup = (k[1], k[0])
            if tup in dp.keys():
                popup1 = str(k[0])
                popup2 = str(k[1])
                popup = "Origen: {} <br> Destino: {}"
                popup = popup.format(popup1, popup2)
                icon_url = "https://png.pngtree.com/svg/20170126/my_personal_page_center_area_28538.png"
                icon = folium.features.CustomIcon(icon_url, icon_size=(38, 40))
                folium.Marker(v[0], popup=popup, icon=icon).add_to(mapa)
            else:
                popup1 = str(k[0])
                popup2 = str(k[1])
                popup = "Origen: {} <br> Destino: {}"
                popup = popup.format(popup1, popup2)
                icon_url = 'https://cdn2.iconfinder.com/data/icons/flat-style-svg-icons-part-1/512/location_marker_pin-512.png'
                icon = folium.features.CustomIcon(icon_url, icon_size=(38, 40))
                folium.Marker(v[1], popup=popup, icon=icon).add_to(mapa)
        for k, v in dp.items():
            if k[1] == k[0]:
                next
            else:
                peso = (df.loc[(df['ZAT_ORIGEN'] == k[0]) &
                               (df['ZAT_DESTINO'] == k[1]),
                               'Frecuencia de Viajes'])
                peso = np.mean(peso)
                folium.PolyLine((v[0], v[1]),
                                color="green",
                                popup=str(peso),
                                weight=(peso),
                                fill_opacity=1).add_to(mapa)
        for k, v in dp.items():
            tup = (k[1], k[0])
            if tup in dp.keys():
                if k[1] == k[0]:
                    next
                else:
                    peso = (df.loc[(df['ZAT_ORIGEN'] == k[0]) &
                                   (df['ZAT_DESTINO'] == k[1]),
                                   'Frecuencia de Viajes'])
                    peso = np.mean(peso)
                    folium.PolyLine((v[0], v[1]),
                                    color="red",
                                    popup=str(peso),
                                    weight=(peso),
                                    fill_opacity=1).add_to(mapa)
            else:
                next
    else:
        next
    folium.LayerControl().add_to(mapa)
    mapa.save('mapa.html')
Example #20
0
import csv
import os
from werkzeug import secure_filename
from flask import Flask, request, jsonify, render_template, send_file, make_response  #import main Flask class and request object
import json

app = Flask(__name__)  #create the Flask app
pp = pprint.PrettyPrinter(indent=4)

choropleth_map = folium.Map(location=[19.080800, 72.986576],
                            zoom_start=11,
                            tiles="openstreetmap")
folium_map = folium.Map(location=[19.076037, 72.877211],
                        zoom_start=13,
                        tiles="openstreetmap")
folium.TileLayer('CartoDB dark_matter').add_to(folium_map)
folium.TileLayer('stamenterrain').add_to(folium_map)
folium.TileLayer('stamentoner').add_to(folium_map)
folium.TileLayer('stamenwatercolor').add_to(folium_map)
folium.TileLayer('cartodbpositron').add_to(folium_map)
folium.LayerControl().add_to(folium_map)

geo_json_data = json.load(open('templates/BMC_Wards.geojson'))
geo_lis = [x['properties']['name'] for x in geo_json_data['features']]
ward_dict = {}
for each in geo_lis:
    ward_dict[each] = random.random()

ward_df = pd.DataFrame(list(ward_dict.items()))
ward_df.columns = ['ward', 'Water Reuse score']
ward_df.to_csv("templates/ward.csv", index=False)
Example #21
0
        icon=folium.Icon(
            color='darkgreen',
            icon_color='#45B39D',  # cores personalizaveis com html
            icon='leaf',  # icon font awesome ou bootstrap glyphicons
            prefix='fa')).add_to(m_expo)

suape = folium.CircleMarker(location=[-8.3944, -34.9741],
                            popup='Porto de Suape',
                            tooltip='Porto de Suape',
                            icon=folium.Icon(color='red')).add_to(m_expo)

itaqui = folium.CircleMarker(location=[-2.5776, -44.3673],
                             popup='Porto de Itaqui',
                             tooltip='Porto de Itaqui',
                             icon=folium.Icon(color='red')).add_to(m_expo)

pecem = folium.CircleMarker(location=[-3.5495, -38.8108],
                            popup='Porto de Pécem',
                            tooltip='Porto de Pécem',
                            icon=folium.Icon(color='red')).add_to(m_expo)

folium.TileLayer('openstreetmap').add_to(m_expo)
folium.TileLayer('stamentoner').add_to(m_expo)
folium.TileLayer('stamenterrain').add_to(m_expo)

folium.TileLayer('cartodbpositron').add_to(m_expo)

folium.LayerControl().add_to(m_expo)

m_expo.save('mapa.html')
import folium
from branca.colormap import linear
from voivodenship_dz_c import dict_dz_c

mapa = folium.Map(width=800,
                  height=600,
                  zoom_start=5.5,
                  location=[52, 19],
                  tiles='Mapbox Bright')  # dzięki temu są 4 tile:
folium.TileLayer('stamentoner').add_to(
    mapa)  # mapbox_bright wygląda obiecujaco oraz to ostatnie
folium.TileLayer('stamenwatercolor').add_to(
    mapa)  # stamenwatercolor wygląda cool, ale jest troszkę useless
folium.TileLayer('cartodbpositron').add_to(
    mapa)  # brak mi takich bez nazw państwa :(

voivodenship_json = "geo_voi.json"
colour_map = linear.RdPu.to_step(10)

folium.GeoJson(
    powiaty_geojson,
    name='geojson',
    style_function=lambda feature: {
        'fillColor': colour_map(dict_dz_c[feature['properties']['VARNAME_1']]
                                ),  # koloruje „stany”
        'color': '#000',  # kolor granic
        'weight': 0,  # grubosć granic
        'stroke': True,
        'fillOpacity': 1,  # !przezroczystość wypełnienia c'nie
    },
).add_to(mapa)
Example #23
0
def plot_layer_by_year(county, map_sink):
    """
    with specified county
    """

    # read data
    df = pd.read_csv('../data/crash-merged/2013.csv')
    accWA = folium.Map([df.lat.median(), df.lon.median()],
                       tiles='',
                       prefer_canvas=True,
                       zoom_start=8)
    folium.TileLayer('cartodbpositron', name='bright').add_to(accWA)

    # add tile layer
    folium.TileLayer('cartodbpositron', name='bright').add_to(accWA)
    folium.TileLayer('CartoDB dark_matter', name='dark').add_to(accWA)

    # create crash layer
    crashes = []
    for year in range(2013, 2018):

        df = pd.read_csv('../data/crash-merged/{}.csv'.format(year))
        df = df[df.COUNTY == county]

        # individual crashes
        yrCrash = folium.FeatureGroup(name=str(year) + '_Crashes', show=False)
        crashes.append(yrCrash)
        accWA.add_child(crashes[-1])

        # add crashe events to their layers
        for _, row in df.iterrows():

            assert row.COUNTY == county
            # define circle color by severity
            if row.REPORT == 2:
                # injury
                cirleColor = "#007849"
            elif row.REPORT == 3:
                # fatal
                cirleColor = 'red'
            else:
                # just property damage
                cirleColor = 'steelblue'

            # define circle radius by severity
            if row.REPORT == 1:
                # property
                cirleRadius = 4
            elif row.REPORT == 2:
                # injury
                cirleRadius = 8
            else:
                # fatal
                cirleRadius = 12
            # cirlRadius = max(row['# INJ'], row['# FAT']) * 3

            folium.CircleMarker(
                [row.lat, row.lon],
                radius=cirleRadius,
                popup=folium.Popup("{}, {}".format(row.FORM_REPT_NO,
                                                   severity_dict[row.REPORT]),
                                   max_width=150),
                # fill_color="#3db7e4",
                color='black',
                weight=0.2,
                fill_color=cirleColor,
                fill=True,
                fill_opacity=0.2).add_to(crashes[-1])

    # add layer control
    folium.LayerControl().add_to(accWA)

    # save map
    accWA.save(map_sink)

    return accWA
Example #24
0
def stats(request):

    country_geo = os.path.join(os.getcwd(), 'countries.geo.json')

    url = "https://api.covid19api.com/summary"

    response = requests.request("GET", url)
    response_dict = response.json()

    df = json_normalize(response_dict['Countries'])
    df.to_csv('covid_data3.csv', index=False)

    covid_data = pd.read_csv('covid_data3.csv')
    confirmed_cases = covid_data['TotalConfirmed'].sum()

    # --------- Oman Total Cases ---------

    for i in range(1, len(response_dict['Countries'])):
        if response_dict['Countries'][i]['Country'] == "Oman":
            index = i

    urlconf = "https://api.covid19api.com/country/Oman/status/confirmed/live"
    responseconf = requests.request("GET", urlconf)

    lineconf = responseconf.json()
    latest = len(lineconf) - 1

    # Context variables to be passed to HTML

    confirmed = lineconf[latest]['Cases']
    deaths = response_dict['Countries'][index]['TotalDeaths']
    recovered1 = response_dict['Countries'][index]['TotalRecovered']

    new_confirmed = response_dict['Countries'][index]['NewConfirmed']
    new_deaths = response_dict['Countries'][index]['NewDeaths']
    new_recovered = response_dict['Countries'][index]['NewRecovered']

    # ----- Comparison Top 3 COVID Affected Countries -------

    top = sorted(response_dict['Countries'],
                 key=lambda x: x['TotalConfirmed'],
                 reverse=True)[:4]

    countries_top3 = []
    cases_top3 = []

    for i in range(0, len(top)):

        countries_top3.append(top[i]['Country'])
        cases_top3.append(top[i]['TotalConfirmed'])

    #-------- GCC Countries -----

    top = sorted(response_dict['Countries'],
                 key=lambda x: x['TotalConfirmed'],
                 reverse=True)

    gcc = [
        'Saudi Arabia', 'Kuwait', 'United Arab Emirates', 'Qatar', 'Bahrain',
        'Oman'
    ]
    gcc_names = []
    gcc_cases = []
    for i in range(1, len(top)):
        if top[i]['Country'] in gcc:
            gcc_names.append(top[i]['Country'])
            gcc_cases.append(top[i]['TotalConfirmed'])

    # -------- Oman Trend --------
    url = "https://api.covid19api.com/country/Oman/status/confirmed/live"

    response = requests.request("GET", url)
    line_dict = response.json()

    dates = []
    cases = []

    for i in range(0, len(line_dict)):

        datestring = line_dict[i]['Date']
        date = datestring.split("T")
        dates.append(date[0])
        cases.append(line_dict[i]['Cases'])

        if (i == (len(line_dict) - 1)):

            dou = date[0]
            tou = date[1]
# ------- Multi Line Trend Charts --------- #

    trendurl = "https://pomber.github.io/covid19/timeseries.json"
    trend = requests.request("GET", trendurl)
    trend_dict = trend.json()

    countries = []
    values = []
    for key, value in trend_dict.items():
        countries.append(key)
        values.append(value)

    recovery = []

    country_length = len(countries)
    val_length = len(values[1])

    for i in range(0, country_length):
        recovery.append([])
        for j in range(0, val_length):
            rec = values[i][j]['recovered']
            conf = values[i][j]['confirmed']

            if conf == 0:
                recovery[i].append(0)
            else:
                # print(i," ",j)
                # print("Rec : ",rec)
                # print("Confirmed : ",confirmed)
                percent = round((float(rec) / conf) * 100, 2)
                # print("Percent : ",percent,"\n\n\n\n")
                recovery[i].append(percent)

    lineplot_names = [
        'Oman', 'United Arab Emirates', 'Spain', 'China', 'Italy', 'US'
    ]
    indices = []

    for i in range(0, 6):

        if lineplot_names[i] in countries:

            indices.append(countries.index(lineplot_names[i]))

    # countrydate=[]

    # for i in range (0,len(values[0])):

    #     countrydate.append(values[0][i]['date'])

    oman_recovery = recovery[indices[0]]
    uae_recovery = recovery[indices[1]]
    spain_recovery = recovery[indices[2]]
    china_recovery = recovery[indices[3]]
    italy_recovery = recovery[indices[4]]
    us_recovery = recovery[indices[5]]

    # ----- Growth Chart -------

    # gcc=['Saudi Arabia', 'Kuwait', 'United Arab Emirates', 'Qatar', 'Bahrain', 'Oman']
    gcc_indices = []

    for i in range(0, 6):
        if gcc[i] in countries:
            gcc_indices.append(countries.index(gcc[i]))

    Saudi_growth = []
    Kuwait_growth = []
    UAE_growth = []
    Qatar_growth = []
    Bahrain_growth = []
    Oman_growth = []

    for i in range(0, len(values[12])):

        Saudi_growth.append(values[gcc_indices[0]][i]['confirmed'])
        Kuwait_growth.append(values[gcc_indices[1]][i]['confirmed'])
        UAE_growth.append(values[gcc_indices[2]][i]['confirmed'])
        Qatar_growth.append(values[gcc_indices[3]][i]['confirmed'])
        Bahrain_growth.append(values[gcc_indices[4]][i]['confirmed'])
        Oman_growth.append(values[gcc_indices[5]][i]['confirmed'])

    # ------- Choropleths --------#

    # Total Confirmed Cases

    m = folium.Map(tiles="cartodbpositron",
                   max_bounds=True,
                   no_wrap=True,
                   min_zoom=2,
                   max_zoom=18,
                   location=[21.4735, 55.9754],
                   zoom_start=6)

    folium.Choropleth(
        geo_data=country_geo,
        name='choropleth',
        data=covid_data,
        columns=['Country', 'TotalConfirmed'],
        key_on='feature.properties.name',
        fill_color='Reds',
        fill_opacity=0.7,
        line_opacity=0.2,
        nan_fill_color='white',
        legend_name='COVID Confirmed',
    ).add_to(m)

    folium.TileLayer('cartodbdark_matter').add_to(m)
    map_html = m._repr_html_()

    # Total Deaths

    death = folium.Map(tiles="cartodbpositron",
                       max_bounds=True,
                       no_wrap=True,
                       min_zoom=2,
                       max_zoom=18,
                       location=[21.4735, 55.9754],
                       zoom_start=6)

    folium.Choropleth(
        geo_data=country_geo,
        name='choropleth',
        data=covid_data,
        columns=['Country', 'TotalDeaths'],
        key_on='feature.properties.name',
        fill_color='Reds',
        fill_opacity=0.7,
        line_opacity=0.2,
        nan_fill_color='white',
        legend_name='COVID Deaths',
    ).add_to(death)

    folium.TileLayer('cartodbdark_matter').add_to(death)
    death_html = death._repr_html_()

    # Recovered

    recovered = folium.Map(tiles="cartodbpositron",
                           max_bounds=True,
                           no_wrap=True,
                           min_zoom=2,
                           max_zoom=18,
                           location=[21.4735, 55.9754],
                           zoom_start=6)

    folium.Choropleth(
        geo_data=country_geo,
        name='choropleth',
        data=covid_data,
        columns=['Country', 'TotalRecovered'],
        key_on='feature.properties.name',
        fill_color='Greens',
        fill_opacity=0.7,
        line_opacity=0.2,
        nan_fill_color='white',
        legend_name='COVID Recovered',
    ).add_to(recovered)

    folium.TileLayer('cartodbdark_matter').add_to(recovered)
    recovered_html = recovered._repr_html_()

    context = {
        'map_html': map_html,
        'death_html': death_html,
        'recovered_html': recovered_html,
        'confirmed_cases': confirmed_cases,
        'confirmed': confirmed,
        'deaths': deaths,
        'recovered1': recovered1,
        'new_confirmed': new_confirmed,
        'new_deaths': new_deaths,
        'new_recovered': new_recovered,
        'countries_top3': countries_top3,
        'cases_top3': cases_top3,
        'gcc_names': gcc_names,
        'gcc_cases': gcc_cases,
        'dates': dates,
        'cases': cases,
        'spain_recovery': spain_recovery,
        'oman_recovery': oman_recovery,
        'uae_recovery': uae_recovery,
        'china_recovery': china_recovery,
        'italy_recovery': italy_recovery,
        'us_recovery': us_recovery,
        'Saudi_growth': Saudi_growth,
        'Kuwait_growth': Kuwait_growth,
        'UAE_growth': UAE_growth,
        'Bahrain_growth': Bahrain_growth,
        'Qatar_growth': Qatar_growth,
        'Oman_growth': Oman_growth,
        'dou': dou,
        'tou': tou
    }

    return render(request, 'pages/stats.html', context)
Example #25
0
import folium
from folium import plugins
import os
import pandas as pd


data = pd.read_csv('../datasets/longitudeFixed.csv')

m = folium.Map(location=[25, 24], zoom_start=3,)
folium.TileLayer('openstreetmap').add_to(m)
folium.TileLayer('Stamen Terrain').add_to(m)
folium.LayerControl(collapsed=False).add_to(m)

plugins.Fullscreen(
    position='topright',
    title='Expand me',
    title_cancel='Exit me',
    force_separate_button=True
).add_to(m)

minimap = plugins.MiniMap()
m.add_child(minimap)

points = []

for index, row in data.iterrows():
    time = row['date']
    latitude = row['latitude']
    longitude = row['longitude']
    popup = '<p>' + str(time) + '</p>'
    coordinates = [longitude, latitude]
Example #26
0
location = geolocator.geocode(address)
latitude = location.latitude
longitude = location.longitude
print('The geographical coordinate of Comunitat Valenciana are {}, {}.'.format(latitude, longitude))

### Generacion del mapa


# En primero lugar, se genera el mapa centrado en las coordenadas indicadas y con un zoom inicial definido. Se indica que no anyada tiles inicialmente, asi podremos tener control de todo lo que se incluye en el mapa. Despues se le anyade la tile layer "Light Map" `CartoDB positron`, porque es de libre acceso y muy aseptica a nivel visual. Ademas, se incluye un plugin para poder visualizar el mapa a pantalla completa.



# create a plain world map Mapbox Bright ,'CartoDB positron'
m = folium.Map(location=[latitude, longitude], zoom_start=8, tiles=None) 
folium.TileLayer(tiles='OpenStreetMap',name="Light Map",control=False).add_to(m)

plugins.Fullscreen(
    position='topright',
    title='Expand me',
    title_cancel='Exit me',
    force_separate_button=True
).add_to(m)


# Se anyade la capa del mapa coropletico, que se colorea en funcion de una determinada variable. Para cada campo se incluye una explicacion.


df2=df.set_index('DPTOCRC')['n_CR'].to_dict()

color_scale = LinearColormap(['yellow','red'], vmin = min(df2.values()),
Example #27
0
import folium

m = folium.Map(location=[-19.5736261, -44.0365116],
               zoom_start=5,
               tiles='Stamen Terrain')

# gerencias tiles
folium.TileLayer('openstreetmap').add_to(m)
folium.TileLayer('stamentoner').add_to(m)
folium.TileLayer('stamenterrain').add_to(m)
folium.TileLayer('stamenterrain').add_to(m)
folium.TileLayer('Mapbox Control Room').add_to(m)
folium.LayerControl().add_to(m)

# add long e lat click
m.add_child(folium.LatLngPopup())

# add marker click
m.add_child(folium.ClickForMarker(popup="Waypoint"))

m.save('mapa_index.html')
Example #28
0
def plot_map(holes, render_holes=True, popup_size=(3, 3)):
    """Plot a leaflet map from holes with popup hole plots.

    Parameters
    ----------
    holes : holes object
    render_holes : bool
        Render popup diagrams for holes
    popup_size : tuple
        size in inches of popup figure

    Returns
    -------
    map_fig : folium map object
    """
    holes_filtered = []
    first_system = False
    if len(holes) == 0:
        raise ValueError("Can't plot empty holes -object.")
    for hole in holes:
        if hasattr(hole, "header") and hasattr(hole.header, "XY"):
            if "X" in hole.header.XY and "Y" in hole.header.XY:
                holes_filtered.append(hole)
                coord_system = hole.fileheader.KJ["Coordinate system"]
                coord_system = coord_string_fix(coord_system)
                if re.search(r"^EPSG:\d+$", coord_system, re.IGNORECASE):
                    input_epsg = coord_system
                elif coord_system in EPSG_SYSTEMS:
                    input_epsg = EPSG_SYSTEMS[coord_system]
                else:
                    msg = "Coordinate system {} is not implemented"
                    msg = msg.format(coord_system)
                    raise NotImplementedError(msg)
                if not first_system:
                    first_system = coord_system
                else:
                    if not first_system == coord_system:
                        raise ValueError(
                            "Coordinate system is not uniform in holes -object"
                        )
    holes_filtered = Holes(holes_filtered)

    x_all, y_all = [], []
    for i in holes_filtered:
        x_all.append(i.header["XY"]["X"])
        y_all.append(i.header["XY"]["Y"])

    x, y = np.mean(x_all), np.mean(y_all)
    x, y = project_points(x, y, input_epsg)
    max_zoom = 22
    map_fig = folium.Map(
        location=[x, y],
        zoom_start=14,
        max_zoom=22,
        prefer_canvas=True,
        control_scale=True,
        tiles=None,
    )
    folium.TileLayer("OpenStreetMap", maxNativeZoom=19,
                     maxZoom=max_zoom).add_to(map_fig)
    folium.TileLayer("Stamen Terrain", maxNativeZoom=18,
                     maxZoom=max_zoom).add_to(map_fig)
    folium.TileLayer("CartoDB positron", maxNativeZoom=18,
                     maxZoom=max_zoom).add_to(map_fig)
    esri_url = ("https://server.arcgisonline.com/ArcGIS/rest/services/" +
                "World_Imagery/MapServer/tile/{z}/{y}/{x}")
    folium.TileLayer(
        tiles=esri_url,
        attr="Esri",
        name="Esri Satellite",
        overlay=False,
        control=True,
        maxNativeZoom=18,
        maxZoom=max_zoom,
    ).add_to(map_fig)
    mml_url_perus = "http://tiles.kartat.kapsi.fi/peruskartta/{z}/{x}/{y}.jpg"
    mml_url_orto = "http://tiles.kartat.kapsi.fi/ortokuva/{z}/{x}/{y}.jpg"
    folium.TileLayer(
        tiles=mml_url_perus,
        attr="MML",
        name="MML peruskartta",
        overlay=False,
        control=True,
        maxNativeZoom=18,
        maxZoom=max_zoom,
    ).add_to(map_fig)
    folium.TileLayer(
        tiles=mml_url_orto,
        attr="MML",
        name="MML ilmakuva",
        overlay=False,
        control=True,
        maxNativeZoom=18,
        maxZoom=max_zoom,
    ).add_to(map_fig)

    gtk_url = (
        "http://gtkdata.gtk.fi/arcgis/services/Rajapinnat/GTK_Maapera_WMS/MapServer/WMSServer?"
    )
    folium.WmsTileLayer(
        name="GTK Maaperäkartta",
        url=gtk_url,
        fmt="image/png",
        layers=["maapera_100k_kerrostumat_ja_muodostumat"
                ],  # "maapera_200k_maalajit"
        show=False,
        transparent=True,
        opacity=0.5,
    ).add_to(map_fig)

    folium.WmsTileLayer(
        name="GTK Sulfaattimaat",
        url=gtk_url,
        fmt="image/png",
        layers=["happamat_sulfaattimaat_250k_alueet"],
        show=False,
        transparent=True,
        opacity=0.5,
    ).add_to(map_fig)

    sw_bounds = project_points(min(x_all), min(y_all), input_epsg)
    ne_bounds = project_points(max(x_all), max(y_all), input_epsg)

    map_fig.fit_bounds([sw_bounds, ne_bounds])

    cluster = MarkerCluster(
        control=False,
        options=dict(animate=True,
                     maxClusterRadius=15,
                     showCoverageOnHover=False,
                     disableClusteringAtZoom=20),
    ).add_to(map_fig)
    map_fig.add_child(cluster)
    hole_clusters = {}
    colors = [
        "red",
        "blue",
        "green",
        "purple",
        "orange",
        "darkred",
        "lightred",
        "darkblue",
        "darkgreen",
        "cadetblue",
        "darkpurple",
        "pink",
        "lightblue",
        "lightgreen",
    ]
    colors = cycle(colors)
    clust_icon_kwargs = {}
    for color, key in zip(colors, holes_filtered.value_counts().keys()):
        hole_clusters[key] = folium.plugins.FeatureGroupSubGroup(
            cluster, name=ABBREVIATIONS[key], show=True)
        clust_icon_kwargs[key] = dict(color=color, icon="")
        map_fig.add_child(hole_clusters[key])

    for i, hole in enumerate(holes_filtered):
        x, y = [hole.header.XY["X"], hole.header.XY["Y"]]
        x, y = project_points(x, y, input_epsg)

        if hasattr(hole.header,
                   "TT") and "Survey abbreviation" in hole.header["TT"]:
            key = hole.header["TT"]["Survey abbreviation"]
        else:
            key = "Missing survey abbreviation"
        if render_holes and key != "Missing survey abbreviation":
            try:
                hole_svg = plot_hole(hole, output="svg", figsize=popup_size)
                popup = folium.Popup(hole_svg)
                icon = get_icon(key, clust_icon_kwargs)
                folium.Marker(location=[x, y], popup=popup,
                              icon=icon).add_to(hole_clusters[key])

            except (NotImplementedError, KeyError, TypeError):
                icon = get_icon(key, clust_icon_kwargs)
                folium.Marker(
                    location=[x, y],
                    popup=ABBREVIATIONS[key] + " " + str(i),
                    icon=icon,
                ).add_to(hole_clusters[key])
        else:
            icon = get_icon(key, clust_icon_kwargs)
            folium.Marker(
                location=[x, y],
                popup=ABBREVIATIONS[key] + " " + str(i),
                icon=icon,
            ).add_to(hole_clusters[key])

    folium.LayerControl().add_to(map_fig)
    MeasureControl(
        secondary_length_unit="",
        secondary_area_unit="",
        activeColor="#aecfeb",
        completedColor="#73b9f5",
    ).add_to(map_fig)
    fmtr = "function(num) {return L.Util.formatNum(num, 7) + ' º ';};"
    MousePosition(
        position="topright",
        separator=" | ",
        prefix="WGS84 ",
        lat_formatter=fmtr,
        lng_formatter=fmtr,
    ).add_to(map_fig)
    return map_fig
Example #29
0
import folium
import os
import pandas as pd

g_map= 'https://mt1.google.com/vt/lyrs=y&x={x}&y={y}&z={z}'

m = folium.Map(location=[10.7905, 78.7047], zoom_start=7,
               tiles=g_map,
               attr='Google Map')
folium.TileLayer('Mapbox Control Room').add_to(m)
folium.TileLayer('openstreetmap').add_to(m)
folium.TileLayer('Mapbox Bright').add_to(m)
folium.Marker([13.0827, 79.8707], popup=folium.Popup('<a href="map1.html" target="blank"><strong>Chennai</strong></a>'),icon=folium.Icon(icon='star')).add_to(m)


tn = os.path.join('tn_json.json')
rice = pd.read_csv('paddy.csv')

folium.Choropleth(
    geo_data= tn,
    name='Rice Production',
    data=rice,
    columns=['District', 'Area'],
    key_on='feature.properties.Dist_Name',
    fill_color='BuGn',
    fill_opacity=0.4,
    line_opacity=0.9,
    legend_name='Area in Hectares'
).add_to(m)
folium.LayerControl().add_to(m)
m.save('tn.html')
Example #30
0
import folium
import folium
import pandas as pd
import os
#
# states = os.path.join('india_state.json')
# state_data = pd.read_csv('rice_prod.csv')

m = folium.Map(location=[22.5937, 78.9629], zoom_start=5)

folium.TileLayer('MapQuestOpenAerial').add_to(m)

folium.LayerControl().add_to(m)

m.save('sat_view.html')

#http://www.google.cn/maps/vt?lyrs=s@189&gl=cn&x={x}&y={y}&z={z}

# folium.Choropleth(
#     geo_data=states,
#     name='Production',
#     data=state_data,
#     columns=['State', 'Avg_rice'],
#     key_on='feature.properties.NAME_1',
#     fill_color='YlGn',
#     fill_opacity=0.7,
#     line_opacity=0.9,
#     legend_name='Production Rate (%)'
# ).add_to(m)