Example #1
0
def ajouterMarkers(map, markers, donnees):
    couleurChaud = "orange"
    couleurFroid = "blue"
    iconChaud = "fire"
    iconFroid = "cloud"
    for marker in markers:
        nom, latitude, longitude, station = marker['Nom'], marker['Latitude'], marker['Longitude'], marker['numer_sta']
        position = float(marker["Latitude"])
        positionLong = float(marker["Longitude"])
        if position > 18 and positionLong > -56:
            donneesUneStation = csv.filtrerLigne(donnees,'numer_sta', station) 
            if len(donneesUneStation) > 0:
                donneesUneStation = conversion(donneesUneStation)
                moyenneStation = moyenne(donneesUneStation)
                fichierJson = templateJson(donneesUneStation, nom, moyenneStation )
                if moyenneStation >= moyenneGlobale:
                    couleur = couleurChaud
                    icon = iconChaud
                else:
                    couleur = couleurFroid
                    icon = iconFroid
                icon = folium.Icon(icon=icon, color = couleur)
                popup = folium.Popup().add_child(folium.VegaLite(fichierJson), name = nom)
                folium.Marker(location=[latitude,longitude],
                    popup = popup,
                    icon = icon
                ).add_to(map)
            else:
                print("pas  de donées pour la station {}".format(nom))
            
            print("Station: {} - lat, long [{},{}] - temp. moy. : {}".format(nom, latitude, longitude, moyenneStation))
Example #2
0
def make_marker(df, country, lat, lon, dataset):

    cc = altair.Chart(df).mark_bar().encode(
        x='dateRep',
        y=dataset,
    )

    marker = folium.Marker(location=[lat, lon],
                           popup=folium.Popup(max_width=400).add_child(
                               folium.VegaLite(cc.to_json(),
                                               width=400,
                                               height=250)))

    return marker
Example #3
0
def addChartMarker(
        chartJson,
        CountyState,
        map,
        opacity=1.0):  # 1. Any other parameters? 2. May want to break this up
    lati, longi = geoCode(CountyState)
    newChart = folium.VegaLite(chartJson, width=600, height=400)
    newPopup = folium.Popup(max_width=600)
    newChart.add_to(newPopup)
    newMarker = folium.Marker(location=[lati, longi],
                              opacity=opacity,
                              popup=newPopup,
                              tooltip=CountyState)
    newMarker.add_to(map)
    return True  # maybe void or something else
Example #4
0
def add_places(the_map, places):
    """Add the given places to the given map."""
    markers = []
    for place in places:
        chart = read_json_file(
            CHART_DIR.joinpath(CHART_FILE.format(place['name'])))
        info = read_json_file(
            FORECAST_DIR.joinpath(FORECAST_FILE.format(place['name'])))
        color = 'red' if info['will-it-rain'] else 'green'
        popup = folium.Popup(max_width=500).add_child(
            folium.VegaLite(chart, width=500, height=250), )
        marker = folium.Marker(location=[place['lat'], place['lon']],
                               popup=popup,
                               icon=folium.Icon(icon='cloud', color=color))
        marker.add_to(the_map)
        markers.append(marker)
    return markers
Example #5
0
            alt.X("Year:Q",
                  bin=alt.Bin(
                      extent=[min(dane['Year'] - 1),
                              max(dane['Year'] + 1)],
                      step=1),
                  axis=alt.Axis(format='.0f')),
            y='Value:Q',
            color=alt.Color(
                'Balance', scale=alt.Scale(
                    range=['black', 'red', "blue"]))).configure_axisX(
                        labelAngle=90)
    vis1 = chart.to_json()
    plots.append(vis1)

#ADD MARKER
data = pd.read_csv('glacier_point.csv')
for i in range(0, len(data)):
    for plot in plots:
        m.add_child(
            CircleMarker(location=[data['x'][i], data['y'][i]],
                         popup=(folium.Popup(max_width=1000).add_child(
                             folium.VegaLite(plots[i]))),
                         fill_opacity=0.3,
                         color="darkblue",
                         fill_color=('white'),
                         marker="o",
                         markersize=16,
                         markeredgewidth=1))

m.save('isbre.html')
Example #6
0
def create_map(stations: StationsType, tereno_stations: StationsType,
               dist: int):
    m = folium.Map(location=compute_center_coordinate(stations), tiles=None)
    folium.TileLayer("Stamen Toner", name="Stamen Toner").add_to(m)
    folium.TileLayer("Stamen Terrain", name="Stamen Terrain").add_to(m)
    folium.TileLayer("Stamen Watercolor", name="Stamen Watercolor").add_to(m)
    folium.TileLayer("OpenStreetMap", name="OpenStreetMap").add_to(m)

    feature_group_tereno = folium.FeatureGroup("TERENO Sites")
    feature_group_dwd = folium.FeatureGroup("DWD Sites", control=False)

    define_kit_marker().add_to(m)

    for station in tereno_stations:
        folium.Marker(
            (station["geo_lat"], station["geo_lon"]),
            tooltip=f"{station['name']} (TERENO)",
            icon=folium.Icon(color="green", icon="info-sign"),
        ).add_to(feature_group_tereno)

    # dwd stations
    for station in stations:
        dummy_df = pd.DataFrame({
            "a": range(100),
            "b": np.cumsum(np.random.normal(0, 0.1, 100))
        })

        folium.Marker(
            (station["geo_lat"], station["geo_lon"]),
            tooltip=f"{station['name']} (id:{station['station_id']})",
            # popup = f"{station['name']} (id:{station['station_id']})",
            popup=folium.Popup(max_width=300).add_child(
                folium.VegaLite(create_chart(dummy_df), width=300,
                                height=100)),
            icon=folium.Icon(color="red", icon="info-sign"),
        ).add_to(feature_group_dwd)

    # distance circle
    folium.Circle(
        radius=dist * 1000,
        location=(ifu["geo_lat"], ifu["geo_lon"]),
        dash_array="5",
        tooltip=f"{dist} km to IFU",
        color="crimson",
        fill=False,
    ).add_to(m)

    # fit bounds
    bounds = compute_bounds(stations)
    m.fit_bounds(bounds)

    feature_group_tereno.add_to(m)
    feature_group_dwd.add_to(m)
    folium.LayerControl(collapsed=True).add_to(m)

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

    return m
Example #7
0
def to_html(path='./',tag='schism'):

    logger.info('create html file for reporting')
    
    m = pyPoseidon.read_model(path + tag +'_model.json')
    m.get_data(online=True)

    d = m.data.Dataset

    vmin = d.elev.min().compute()
    vmax = d.elev.max().compute()

    x = d.SCHISM_hgrid_node_x.values
    y = d.SCHISM_hgrid_node_y.values
    tri = d.SCHISM_hgrid_face_nodes.values

    nodes = pd.DataFrame({'lon':x,'lat':y})
    tria = pd.DataFrame(tri ,columns=['a','b','c'])

    tria['ap'] = tria.apply(lambda x : nodes.loc[x.a,['lon','lat']].values,axis=1)
    tria['bp'] = tria.apply(lambda x : nodes.loc[x.b,['lon','lat']].values,axis=1)
    tria['cp'] = tria.apply(lambda x : nodes.loc[x.c,['lon','lat']].values,axis=1)

    tria['geometry'] =  tria.apply(
         lambda x : shapely.geometry.Polygon([x.ap,x.bp,x.cp]),axis=1)

   
    colormap = branca.colormap.LinearColormap(['green', 'yellow', 'red'], vmin=vmin.values, vmax=vmax.values)
    colormap.caption = 'Elevation'
      
    # geopandas
    gf_ = gp.GeoDataFrame(tria, crs={'init' :'epsg:4326'})    

    gf_ = gf_.drop(['a','b','c','ap','bp','cp'], axis=1)
    

    
    colormap = branca.colormap.LinearColormap(['green', 'yellow', 'red'], vmin=vmin.values, vmax=vmax.values)
    colormap.caption = 'Elevation'


    # MAXH
    mh = d.elev.max('time').values
        
    tria['value'] = tria.apply(lambda x : np.mean([mh[x.a],mh[x.b],mh[x.c]]),axis=1)

    gf_ = gp.GeoDataFrame(tria, crs={'init' :'epsg:4326'})    

    gf_ = gf_.drop(['a','b','c','ap','bp','cp'], axis=1)


    maxh = folium.GeoJson(
    gf_,
    style_function=lambda x: {
        "fillColor": colormap(x['properties']['value']),
        'weight':0,
        "fillOpacity": 1
    },
    )

    maxh.layer_name = 'Maximum Elevation'

    # GRID

    
    g = folium.GeoJson(
    gf_,
    style_function=lambda x: {
        "fillColor": "transparent",
        "color": "black",
        'weight':.2


        },
    )

    g.layer_name = 'Grid'

    #VALIDATION
    
    tgs = m.data.obs.locations.loc[m.data.obs.locations.Group=='TD UNESCO']
    
    points = tgs[['lat','lon']].values
    
    mlat,mlon = points.mean(axis=0)
    
    tg = m.data.obs.data
    tg.index.levels[1].name = 'date'
    tg.index.levels[0].name = 'location'
    tg = tg.drop(['Level m','Tide m'],axis=1)
    tg.columns=['height']

    toponames = tgs.Name.to_list()
    toponames = [x.strip(' ') for x in toponames]
    
    st = m.data.time_series.to_dataframe()
    st.index.levels[1].name = 'date'
    st.index.levels[0].name = 'location'
    st.columns=['height']
    st.index = st.index.set_levels(m.data.obs.locations.Name.str.strip(' '), level=0)
    st = st.loc[toponames]    

    mc = plugins.MarkerCluster()
    for name,latlon in zip(toponames,points):
        popup = folium.Popup()
        tg_ = tg.loc[name.strip(' ')]
        st_ = st.loc[name.strip(' ')]
        if tg_.shape[0] <= 1:
            tg_ = st_.copy()
            tg_.height = 0
        s = source(tg_,st_)
        gr = graph(s, name)
        vis = gr.to_json()
        folium.VegaLite(vis, height=350, width=750).add_to(popup)
        mc.add_child(folium.Marker(latlon, popup=popup))
    
    mc.layer_name = 'Validation'
    
    #FINAL MAP
    
    Map = folium.Map(location=(mlat, mlon), tiles='OpenStreetMap', date=m.date.__str__(), zoom_start=5)
    
    plugins.Fullscreen(
    position='topleft',
    title='Expand me',
    title_cancel='Exit me',
    force_separate_button=True
    ).add_to(Map)

    Map.add_child(maxh)
    Map.add_child(g)
    Map.add_child(mc)
    Map.add_child(folium.map.LayerControl())
    Map.add_child(colormap)


    Map.save(path + 'report.html')
    
    logger.info('... saved')
    
    return
    
Example #8
0
    nitrates['data'] = Data_nitrates[Data_nitrates.code_station == i]
    nitrates['title'] = 'Pollution en nitrates'

    selenium = {}
    selenium['data'] = Data_selenium[Data_selenium.code_station == i]
    selenium['title'] = 'Pollution en sélénium'

    atrazine = {}
    atrazine['data'] = Data_atrazine[Data_atrazine.code_station == i]
    atrazine['title'] = 'Pollution en atrazine'

    polluants = [nitrates, selenium, atrazine]
    charts = []

    for j in range(len(polluants)):
        charts.append(alt.Chart(polluants[j]['data'])\
        .mark_line()\
        .encode(alt.X('date_prelevement:T', timeUnit = 'yearmonth', title = 'Date du prélèvement'), alt.Y('resultat:Q', title = 'Quantité en mg/L'), alt.Color('libelle_parametre')).properties(width=200,height=100,title=polluants[j]['title']))

    Chart = alt.vconcat(charts[0], charts[1], charts[2])
    vis1 = Chart.to_json()

    # Etape 3: Création d'un marqueur avec les données en popup
    folium.Marker(location=location,
                  popup=folium.Popup(max_width=750).add_child(
                      folium.VegaLite(vis1, width=390, height=500)),
                  tooltip=tooltip,
                  icon=folium.Icon(icon='tint', color='darkblue')).add_to(m)

# Generate Map
m.save('map_pollution_eau_77.html')
Example #9
0
    for i in countryoutlines:
        if str(i[32:35]) == coloredemissions[country]["ISO"]:
            outline = i[0:len(i) - 2]
            break
    if outline:
        #On definit la couche geoJSON et sa couleur
        colored_country = folium.Choropleth(
            outline,
            name=coloredemissions[country]["ISO"],
            fill_color=coloredemissions[country]["Color"],
            fill_opacity=0.8)
        #On definit le graphique Vega qui sera associe au pays
        graph = JSONtemplate(bycountryemissions,
                             coloredemissions[country]["ISO"])
        #On definit le popup qui sera ajoute au pays
        popup = folium.Popup().add_child(folium.VegaLite(graph))
        #On ajoute le popup a la couche geoJSON
        popup.add_to(colored_country)
        #On ajoute la couche geoJSON sur la carte
        colored_country.add_to(m)
    print(coloredemissions[country]["Color"])
    print(coloredemissions[country]["ISO"] + " ADDED")
print("Choropleth: GENERATED")
#folium.GeoJson(
#    countries,
#    name = "geojson"
#).add_to(m)
'''
folium.Choropleth(
    geo_data=countries,
    name="choropleth",