Esempio n. 1
0
# fit id
for i in range(2449):
    ans_Id[i] = i+1
# for d in (range(100)):      #測試資料筆數
#      for m in (range(50)):  #找是在哪列
#             if lon_min[list1[m]-1]<lon[d] and lon[d]<lon_max[list2[m]-1] and lat_min[list1[m]-1]<lat[d] and lat[d]<lat_max[list2[m]-1]:
#                 for n in range(list1[m],list2[m]+1): #找是在該列的哪個
#                     if lon_min[n-1]<lon[d] and lon[d]<lon_max[n-1] and lat_min[n-1]<lat[d] and lat[d]<lat_max[n-1]:
#                         ans_Id[d]=Id[n]-1
taichungmap_1x1 = taichungmap_1x1.merge(all_point_data_mix, on='Id')
taichungmap_1x1['PM2.5']=taichungmap_1x1['PM2.5'].round()

#==================================================================================================
#folium

fmap=folium.Map(location=[24.2,120.9], zoom_start=10.5)
fmap.choropleth(
                geo_data=taichungmap_1x1,
                name='pm2.5',
                columns=['Id', 'PM2.5'],
                key_on='feature.properties.Id',
                data=all_point_data_mix,
                #threshold_scale=[],
                fill_color='BuGn',
                legend_name='pm2.5',
                line_opacity=0.5,
                fill_opacity=0.8
                )
#fmap.choropleth(
 #               geo_data=taichung,
 #               name='taichung',
Esempio n. 2
0
import folium

# we can get cordinates of the place by google map
# open google map and then right click and then chose what's there?
map = folium.Map(
    location=[38.8, -99.09], zoom_start=6,
    tiles="Mapbox Bright")  # pass a list of cordinate of the location
map
Esempio n. 3
0
if you are running this notebook for this first time or if you are getting an authentication error.  
'''

# %%
# ee.Authenticate()
ee.Initialize()

# %%
'''
## Create an interactive map 
This step creates an interactive map using [folium](https://github.com/python-visualization/folium). The default basemap is the OpenStreetMap. Additional basemaps can be added using the `Map.setOptions()` function. 
The optional basemaps can be `ROADMAP`, `SATELLITE`, `HYBRID`, `TERRAIN`, or `ESRI`.
'''

# %%
Map = folium.Map(location=[40, -100], zoom_start=4)
Map.setOptions('HYBRID')

# %%
'''
## Add Earth Engine Python script 

'''

# %%
# Compute the trend of nighttime lights from DMSP.


# Add a band containing image date as years since 1990.
def createTimeBand(img):
    year = img.date().difference(ee.Date('1990-01-01'), 'year')
Esempio n. 4
0
def index():

	ny_coords = (40.7128, -74.0060)
	census_tracts = r'census_t.geojson'
	census_income = pd.read_csv('census_income.csv')

	colormap = linear.RdBu_06.scale(
    census_income['2013-2017'].min(),
    census_income['2013-2017'].max())
	print(colormap(31966.2255623417))

	census_income_dict = census_income.set_index('Census Tract')['2013-2017'].to_dict()
	print(census_income_dict[36061016001])
	print(census_income['2013-2017'].max())

	print(census_income[:5])
	#sqf_data = r'sqf_cleaned.csv'
	#sqf_data = pd.read_csv('sqf_cleaned.csv')
	#school_districts = r'untitled.json'

	#stop_and_frisk_file = os.path.join('/Users/rajdas/Downloads/', 'sqf-2018.csv')
	#stop_and_frisk_full_data = pd.read_csv('sqf-2018.csv')

	#school_demographic_data_full = pd.read_csv('nyc_school_demographics.csv')
	#school_demographic_data = school_demographic_data_full[school_demographic_data_full['Year'] == '2018-19']

	#school_demographic_data[['# Black']] = school_demographic_data[['# Black']].apply(pd.to_numeric, errors='coerce')

	#print("pls " + (school_demographic_data[school_demographic_data['Administrative District'] == '01']).to_string())
	#print("pls??")

	#print (sqf_data[:5])

	m = folium.Map(location=ny_coords, tiles="Stamen Toner", zoom_start=13)

	#colormap = linear.YlGn_09.scale(
    #sqf_data.SQF.min(),
    #sqf_data.SQF.max())

	#print(colormap(5.0))

	#sqf_dict = sqf_data.set_index('Precinct')['SQF']

	#print(sqf_dict[0])

	#color_dict = {key: colormap(sqf_dict[key]) for key in sqf_dict.keys()}

	folium.GeoJson(
	    census_tracts,
	    style_function=lambda feature: {
	        'fillColor': colormap(census_income_dict[int(feature['properties']['geoid'])]),
	        #'threshold_scale': [20000, 50000, 100000, 150000],
	        'fill_opacity':0.7,
	        
	        'weight': 1,
	        #'dashArray': '5, 5'
	    }
	).add_to(m)

	folium.LayerControl().add_to(m)

	'''
	folium.GeoJson(
	    census_tracts,
	    style_function=lambda feature: {
	        'fillColor': 'red' if feature['properties']['geoid'] == '36085990100' else '#ffffff',
	        'color': 'gray',
	        'weight': 2,
	        'dashArray': '5, 5'
	    }
	).add_to(m)
	

	folium.LayerControl().add_to(m)
	'''

	'''folium.Choropleth(
	    geo_data=census_tracts,
	    data=census_income,
	    columns=['Census Tract', '2013-2017'],
	    key_on='feature.properties.geoid',
	    fill_color='Reds',
	).add_to(m)'''
	

	'''folium.Choropleth(
	    geo_data=precincts,
	    fill_color='YlOrRd', 
	    fill_opacity=0.7, 
	    line_opacity=0.2,
	    #threshold_scale = [0,0.25,0.5,0.75, 1],
	    data = sqf_data,
	    key_on='feature.properties.precinct',
	    columns = ['Precinct', 'SQF']
	).add_to(m)'''


	'''folium.Choropleth(
	    geo_data=school_districts,
	    fill_color='YlOrRd', 
	    fill_opacity=0.7, 
	    line_opacity=0.2,
	    threshold_scale = [0,0.25,0.5,0.75, 1],
	    data = school_demographic_data,
	    key_on='feature.properties.school_dist',
	    columns = ['Administrative District', '# Black']
	    #legend_name='Immigration to Canada'
	).add_to(m)'''
	
	m.save('templates/map.html')

	response = make_response(render_template("map.html"))
	return response
Esempio n. 5
0
rows = ds.RasterYSize
xmin = geotransform[0]
ymax = geotransform[3]
xmax = xmin + cols * geotransform[1]
ymin = ymax + rows * geotransform[5]
centerx = (xmin + xmax) / 2
centery = (ymin + ymax) / 2

#Raster convert to array in numpy
bands = ds.RasterCount
band = ds.GetRasterBand(1)
dataimage = band.ReadAsArray(0, 0, cols, rows)

#Visualization in folium
map = folium.Map(location=[centery, centerx],
                 zoom_start=7,
                 tiles='Stamen Terrain')
raster_layers.ImageOverlay(
    image=dataimage,
    bounds=[[ymin, xmin], [ymax, xmax]],
    colormap=lambda x: (0, 0, 0, x),  #R,G,B,alpha
    #if I want white background then R,G,B is 1,1,1
).add_to(map)

saildrone_path = folium.PolyLine(locations=[[68, -168], [69, 1 - 164],
                                            [71, -162], [72, -156]],
                                 color='red')  #assume the path of Saildrone
saildrone_path.add_to(map)  #put the path into map

startplot = features.Marker([68, -168])
startplotpp = folium.Popup('saildrone_start')
Esempio n. 6
0
SF['PdDistrictCode'] = SF['PdDistrict'].apply(
    lambda row: pd_districts_levels[row])

# print(SF.describe())


# plt.scatter(SF['X'], SF['Y'], c=SF['PdDistrictCode'])
# plt.show()

districts = np.unique(SF['PdDistrict'])
print(list(colors.cnames.values())[0:len(districts)])

color_dict = dict(
    zip(districts, list(colors.cnames.values())[0:-1:len(districts)]))
print(color_dict)

# Create map
map_osm = folium.Map(location=[SF['Y'].mean(), SF['X'].mean()], zoom_start=12)
plotEvery = 50
obs = list(zip(SF['Y'], SF['X'], SF['PdDistrict']))

for el in obs[0:-1:plotEvery]:

    folium.CircleMarker(el[0:2], color=color_dict[el[2]],
                        fill_color=el[2], radius=10).add_to(map_osm)





# print(map_osm)
Esempio n. 7
0
lat = list(data["Latitude"])
lon = list(data["Longitude"])
name = list(data["City"])
SNo = list(data["SNo"])


def color_producer(SNo):
    if SNo < 11:
        return 'green'
    elif 11 <= SNo < 22:
        return 'red'
    else:
        return 'blue'


map = folium.Map(location=[22.5, 84.2], zoom_start=6, tiles="Mapbox Bright")
fgv = folium.FeatureGroup(name="Cities")
for lt, ln, nm, sn in zip(lat, lon, name, SNo):
    fgv.add_child(
        folium.CircleMarker(location=[lt, ln],
                            radius=6,
                            popup=nm,
                            fill_color=color_producer(sn),
                            color='grey',
                            fill_opacity=0.7))

fgp = folium.FeatureGroup(name="Population")
fgp.add_child(
    folium.GeoJson(
        data=open('world.json', 'r', encoding='utf-8-sig').read(),
        style_function=lambda x: {
geo_merge = geo_df.merge(deaths_geo_count, on='Districts', how='left')
geo_merge
col_name =geo_merge.columns[0]
geo_merge.head()

# Mapping

import folium
from folium.element import IFrame
from geopy.geocoders import Nominatim

# Get the folium base map and set zoom position, then start mapping

m = folium.Map([8, 79.8],
               tiles='cartodbpositron',
               zoom_start=8)

ft = "deaths_per_district"
cmap = folium.colormap.linear.YlOrRd.scale(geo_merge[ft].min(), geo_merge[ft].max())

folium.GeoJson(geo_merge,
               style_function=lambda feature: {
                'fillColor': cmap(feature['properties'][ft]),
                'threshold_scale': [0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400],
                'fillOpacity' : 0.7,
                'weight' : 1, 'color' : 'black'
               }).add_to(m)

cmap.caption = 'Deaths by district'
cmap.add_to(m)
Esempio n. 9
0
import folium
map = folium.Map(location=[38.58, -99.09], zoom_start=6)
map.save("Map1.html")
Esempio n. 10
0
import ee
import folium
import IPython.display as ip
import geehydro
import GetImageCollection as ic

ee.Initialize()
nhd = ee.FeatureCollection('users/mincej20/NHD_Filtered_50')
feat = nhd.first()

centroid = ee.Geometry(feat.geometry().centroid())
long = centroid.coordinates().get(0).getInfo()
lat = centroid.coordinates().get(1).getInfo()

imgs = ic.getImageCollection(feat, True)
Map = folium.Map(location=[long, lat], zoom_start=8)

print(imgs.first().getInfo())
viz = {'bands': ["RED", "GREEN", "BLUE"], 'min': 0, 'max': 3000, 'gamma': 1.4}

Map.setOptions('HYBRID')
Map.addLayer(imgs.first(), viz, "Test", True)
Map.setControlVisibility(layerControl=True,
                         fullscreenControl=True,
                         latLngPopup=True)
html_string = Map.get_root().render()
ip.HTML(html_string)
Esempio n. 11
0
    gy, gx = np.meshgrid(*get_space_coords(x_bounds, y_bounds) )
    return griddata(geometry, feature/(feature.max()-feature.min()) , (gx, gy), method="cubic")

if __name__ == "__main__":
    
    x_bounds=(-123, -121)
    y_bounds=(37, 39)
    
    gdf = gpd.read_file("data/geojson/calif_nev_ncei_grav.geojson")
    
    gdf_subset = gdf[(gdf["latitude"] > y_bounds[0]) &
                     (gdf["latitude"] < y_bounds[1]) &
                     (gdf["longitude"] > x_bounds[0]) &
                     (gdf["longitude"] < x_bounds[1])]
    
    m = folium.Map(tiles='openstreetmap', zoom_start=12, location=[37.8, -122.4])

    coord_list = list(zip(gdf_subset.geometry.x, gdf_subset.geometry.y))
    
    grid_1 = interpolate_2d(coord_list, gdf_subset["isostatic_anom"].values,
                            x_bounds=x_bounds, y_bounds=y_bounds)
    
    g = folium.raster_layers.ImageOverlay(grid_1.T[::-1], opacity=0.5,
                                          bounds=[[y_bounds[0], x_bounds[0]], [y_bounds[1], x_bounds[1]]],
                                          colormap=cm.seismic)
    g.add_to(m)
    
    for (k, row) in gdf_subset.iterrows():
        circ = folium.Circle(location=[row.geometry.y, row.geometry.x], radius=1, fill=True)
        circ.add_to(m)
        
Esempio n. 12
0
                   contour_width=3)

    # Generate a wordcloud
    wc.generate(text)

    # show
    # plt.figure(figsize=[20,10])
    # plt.imshow(wc, interpolation='bilinear')
    # plt.axis("off")
    # plt.savefig("../images/wordcloud_bike_after.png")
    # plt.show()

    # all_df.corr(method ='pearson')

    m = folium.Map(location=[38.8697, -106.9878],
                   zoom_start=8,
                   tiles='Stamen Terrain')

    for index, row in crested_butte_df.iterrows():
        if row['difficulty'] == 'black':
            update_map("#000000")
        elif row['difficulty'] == 'blue':
            update_map("#0000FF")
        elif row['difficulty'] == 'green':
            update_map("#008000")
        elif row['difficulty'] == 'blueBlack':
            update_map("#003366")
        elif row['difficulty'] == 'greenBlue':
            update_map("#00DDDD")
        elif row['difficulty'] == 'dblack':
            update_map("#000000")
Esempio n. 13
0
def heat_map(df):
    locs = zip(df.Y, df.X)
    m = folium.Map([38.8934, -76.9470], tiles='stamentoner', zoom_start=12)
    HeatMap(locs).add_to(m)
    return st.markdown(m._repr_html_(), unsafe_allow_html=True)
Esempio n. 14
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov  8 13:07:07 2017

@author: PatrickAndreNaess
"""

import folium
import numpy as np
from folium.plugins import FastMarkerCluster

lats = BigD['Lat']
lons = BigD['Lon']


m = folium.Map(location=[0,0], attr='XXX Mapbox Attribution',\
               tiles="cartodbdark_matter",\
               zoom_start=2)

FastMarkerCluster(data=list(zip(lats, lons))).add_to(m)

folium.LayerControl().add_to(m)

m.save('/Users/PatrickAndreNaess/Desktop/PyPlots/NYINTERAKTIVmeld.html')
def map_json(data_file,
             geo_data_file,
             save_name,
             by_prac="",
             pop_file="",
             start_loc=[],
             density=True,
             column_names=[],
             legend_title="",
             delim=",",
             start_zoom=5,
             count_column="Total",
             divisor=1,
             fill_color="OrRd",
             key="",
             fill_opac=0.6,
             line_opac=0.3,
             use_pop=False):
    df = pd.read_csv(data_file, delimiter=delim)
    m = folium.Map(location=start_loc, zoom_start=start_zoom)
    df['geometry'] = df.apply((lambda x: Point(x.lon, x.lat)), axis=1)

    ccg_gdf = gpd.read_file(geo_data_file)

    counts = []
    populations = []
    ratios = []
    drug_count = []

    if (pop_file != ""):
        pop_df = pd.read_csv(pop_file)
    if (by_prac != ""):
        prac_df = pd.read_csv(by_prac)

    # FOR FUZZY MATCHING POPULATION 'AREAS'
    if (not pop_file == ""):
        for i in range(len(ccg_gdf['geometry'])):
            dists = []
            pops = []
            names = []
            comp_name = ccg_gdf[column_names[0]][i]
            comp_name = comp_name[:len(comp_name) - 4]
            for v in range(len(pop_df)):
                current_name = pop_df['geography'][v]
                names.append(current_name)
                pops.append(
                    pop_df['Variable: All usual residents measures: Value'][v])
                dists.append(fuzz.ratio(comp_name, current_name))
            ind = dists.index(max(dists))
            if (density == True):
                populations.append(pops[ind] / ccg_gdf['calculated_area'][i])
            else:
                populations.append(pops[ind])

    if (not by_prac == ""):
        print("Input the desired drug names.. (comma delimited)")
        DRUG_NAMEs = input()

        if (not DRUG_NAMEs == ""):
            DRUG_NAME = DRUG_NAMEs.split(",")
            print(DRUG_NAME)
        else:
            DRUG_NAME = ""
            by_prac = ""

    # Rest of mappinp: coount of total prescriptions, specific prescriptions, total practices, ratios
    for i in range(len(ccg_gdf['geometry'])):
        counts.append(0)
        drug_count.append(0)
        for v in range(len(df['geometry'])):
            if (ccg_gdf['geometry'][i].contains(df['geometry'][v])):
                if (not by_prac == ""):
                    try:
                        for c in range(len(DRUG_NAME)):
                            current_prac = df['PRACTICE'][v]
                            current_prac = current_prac.strip()

                            current_index = pd.Index(prac_df['org_code'])
                            current_ind = current_index.get_loc(current_prac)
                            drug_count[i] += prac_df[DRUG_NAME[c]][current_ind]
                    except:
                        print("No match found..")

                if (count_column == ""):
                    counts[i] += 1
                else:
                    counts[i] += df[count_column][i]

        if (density == True):
            if (not pop_file == ""):
                counts[i] = counts[i] / ccg_gdf['calculated_area'][i]
                ratios.append(np.log10(counts[i]) / np.log10(populations[i]))
            if (not by_prac == ""):
                drug_count[i] = drug_count[i] / ccg_gdf['calculated_area'][i]

        counts[i] = counts[i] / divisor
        print(i, '/', len(ccg_gdf['geometry']))

    if (density == True and not pop_file == ""):
        ccg_gdf['ratios'] = ratios
    elif (not pop_file == ""):
        ccg_gdf['population'] = populations

    if (not by_prac == ""):
        ccg_gdf['drug_count'] = drug_count

    ccg_gdf['counts'] = counts

    ##AREA CRS 27700

    folium.Choropleth(geo_data=geo_data_file,
                      name='geometry',
                      data=ccg_gdf,
                      columns=column_names,
                      key_on=key,
                      fill_color=fill_color,
                      fill_opacity=fill_opac,
                      line_opacity=line_opac,
                      legend_name=legend_title,
                      smooth_factor=1).add_to(m)
    folium.LayerControl().add_to(m)
    m.save(save_name)
Esempio n. 16
0
import folium
import pandas
 
data = pandas.read_csv("../data/Volcanoes.txt")

lat = list(data["LAT"])
lon = list(data["LON"])
elev = list(data["ELEV"])

def color_producer(elevation):
    if elevation < 1000:
        return 'green'
    elif 1000<= elevation < 3000:
        return 'orange'
    else:
        return 'red' 
 
map = folium.Map(location=[38.58, -99.09], zoom_start=5, tiles="Mapbox Bright")

fg = folium.FeatureGroup(name = "My Map")
 
for lt, ln, el in zip(lat, lon, elev):        
    fg.add_child(folium.CircleMarker(location=[lt, ln], radius=6, popup=str(el)+ " m",
    fill_color=color_producer(el), color = 'grey', fill = True, fill_opacity = 0.7 ))

fg.add_child(folium.GeoJson(data=(open('../data/world.json', 'r', encoding='utf-8-sig').read())))

map.add_child(fg)

map.save("Map1.html")
Esempio n. 17
0
#created and initiated by Pranay Joshi
import pandas as pd
import folium
import os
import branca
m = folium.Map([39.4133, -105.7567], zoom_start=5)
#creating a simple dataframe with the data.csv which is the tableof all the members extracted from the wikki page
main = pd.read_csv("main.csv")
#accessing tooltip
tooltip = 'OSGeo Members'
#using custom OSGeo logo
logoIcon = folium.features.CustomIcon('icon.png', icon_size=(50, 50))
# follium popup does not support new line as it works a/c to html tag so we need to just create a html file
# so just creating an html file of new line and some intial text using the 'branca' module
html = '''
name:  
'''
html1 = '''
<br>
City: 
'''
html2 = '''
<br>
Country: 
'''
html3 = '''
<br>
contact:
'''
country = 'city, country =   '
contact = 'contact us =   '
Esempio n. 18
0
        json.dump(features, open('features_' + str(cont) + '.json', 'w'))
        cont = cont + 1
        features = []

json.dump(features, open('features_' + str(cont) + '.json', 'w'))

#%%

v_lat = np.linspace(43.292, 43.330, 40)
v_lon = np.linspace(-2.021, -1.947, 40)

#%%
from folium import plugins
import folium
m = folium.Map(location=[43.312134, -1.981296],
               zoom_start=14,
               tiles='CartoDB positron')

folium.plugins.TimestampedGeoJson(data={
    'type': 'FeatureCollection',
    'features': features[0:2]
},
                                  loop=True,
                                  add_last_point=True,
                                  period='PT5S',
                                  duration='PT5M').add_to(m)

#ESTACIONES
for i in range(stations_features.shape[0]):
    point = stations_features.iloc[i]
    folium.CircleMarker(location=[point['latitud'], point['longitud']],
Esempio n. 19
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_
Esempio n. 20
0
for i in range(len(purple)):
    if purple[i] == 'true':
        line_color.append('purple')
purp2 = [str(x[13]) for x in data]
for i in range(len(purp2)):
    if purp2[i] == 'true':
        line_color.append('purple')
yellow = [str(x[14]) for x in data]
for i in range(len(yellow)):
    if yellow[i] == 'true':
        line_color.append('#FFFF00')
pink = [str(x[15]) for x in data]
for i in range(len(pink)):
    if pink[i] == 'true':
        line_color.append('pink')
orange = [str(x[-16]) for x in data]
for i in range(len(orange)):
    if orange[i] == 'true':
        line_color.append('orange')

print(line_color)

train_map = folium.Map(location=[41.880443, -87.644107], zoom_start=10.4)

for i in range(len(data)):
    folium.Marker(location=location[i],
                  popup=names[i],
                  icon=folium.plugins.BeautifyIcon(
                      border_color=line_color[i]).add_to(train_map))
train_map.save('train_map.html')
Esempio n. 21
0
content = json.dumps(JSONContent, indent=4, sort_keys=True)

# MATPLOTLIB PART -------------------
# create a set of axes with Mercator projection
ax = plt.axes(projection=ccrs.Mercator())
ax.add_feature(cf.COASTLINE)
ax.add_feature(cf.OCEAN)
ax.add_feature(cf.BORDERS)
ax.add_feature(cf.LAND)
ax.set_title("Worldwide Bushfires")
plt.show()

# FOLIUM PART --------------------

# print(content)
m = folium.Map()
tooltip = 'Click me!'
index = 0
print("Length x : ", len(x))
print("Length y : ", len(y))
print(x[392308])
while (index < len(x)):
    # print(x[index], y[index])
    folium.Marker([x[index], y[index]],
                  popup='<i>Mt. Hood Meadows</i>',
                  icon=folium.Icon(color='red', icon='info-sign'),
                  tooltip=tooltip).add_to(m)
    print("Loading ", index)
    index += 1000
''' 
folium.Marker([45.3288, -121.6625],
Esempio n. 22
0
geolocator = Nominatim()
import pandas as pd

df = pd.read_csv('farms.csv')

city = df["city"]
city_list = list(city)
state = df["state"]
states = list(state)
state_list = list(state)

address = [
    city_list[i] + " " + state_list[i] for i in range(0, len(city_list))
]

mapit = folium.Map(location=[20.5937, 78.9629], zoom_start=6)

for i in address:
    loc = geolocator.geocode(i)
    lat = loc.latitude
    long = loc.longitude
    folium.Marker(location=[lat, long], fill_color='#43d9de',
                  radius=8).add_to(mapit)
mapit.save('indiaa.html')

farm_info = {}

for item in states:
    if item in farm_info:
        farm_info[item] += 1
    else:
Esempio n. 23
0
def generate_map(data, feature=False, year=2017):
    """ Utiliza el framework Folium para generar el html con la información obtenida 
        de la base de datos. """
    sfMap = folium.Map(location=start_coords, zoom_start=12)
    start = timer()
    total_start = start

    if (feature is None):
        print("    generateMap: without feature")
        marker = folium.plugins.MarkerCluster(name="Density").add_to(sfMap)
        for name, row in data.iterrows():
            folium.Marker([row["Y"], row["X"]],
                          popup=folium.Popup(
                              row["description"])).add_to(marker)
    elif (feature is True):
        callback = (
            'function (row) {'
            'var marker = L.circle(new L.LatLng(row[1], row[0]), {color: "red",  radius: 20000});'
            'marker.bindPopup("example");'
            'return marker};')
        sfMap.add_child(
            FastMarkerCluster(data[['Y', 'X']].values.tolist(),
                              callback=callback))

    else:
        print("    generateMap: with feature", data[['Y', 'X', 'description']])
        MarkerClusterScript(data[['Y', 'X',
                                  'description']].to_json(orient="records"),
                            callback=create_marker).add_to(sfMap)

    print("    generateMap:markers elapsed", timer() - start)
    start = timer()
    district_geo = r'static/datasets/sfpddistricts.geojson'

    incidentsCountPerDistrict = get_per_district(year)
    #if (year == 2017):
    #    incidentsCountPerDistrict = incidentsPerDistrict2017();
    #elif (year == 2016):
    #    incidentsCountPerDistrict = incidentsPerDistrict2016();
    #elif (year == 2015):
    #    incidentsCountPerDistrict = incidentsPerDistrict2015();
    #else:
    #    incidentsCountPerDistrict = []

    # Choropleth. Proporciona las secciones coloreadas para
    # cada distrito
    sfMap.choropleth(geo_data=district_geo,
                     name="Incidents per district",
                     data=incidentsCountPerDistrict,
                     columns=['district', 'count'],
                     key_on='feature.properties.DISTRICT',
                     fill_color='YlOrRd',
                     fill_opacity=0.7,
                     line_opacity=0.2,
                     legend_name='Number of incidents per district')

    folium.LayerControl().add_to(sfMap)

    print("    generateMap:layers elapsed", timer() - start)
    print("generateMap elapsed", timer() - total_start)
    return sfMap

# Fron this plot, we can see that a large number of Bar/Cocktail stores have least visitors.  The next cuisines with least footfalls are Izakaya and Dining bar. 

# **Geographical location of low performing stores**



#Marking high and low performance stores by number of visitors
hpstores = dst[dst['visitors'] > 30]
lpstores = dst[dst['visitors'] < 10]




map_osm = folium.Map(location=[40, 140], zoom_start=5)
for lng, lat, desc in zip(hpstores['longitude'], hpstores['latitude'], hpstores['air_genre_name']):
    folium.Marker([lat, lng], popup=desc, icon = folium.Icon(color='blue')).add_to(map_osm)
    

for lng, lat, desc in zip(lpstores['longitude'], lpstores['latitude'], lpstores['air_genre_name']):
    folium.Marker([lat, lng], popup=desc, icon = folium.Icon(color='red')).add_to(map_osm)
map_osm


# We can see the geographical location of high performance stores, where average number of visitors is more than 30 marked in blue, and low performance stores, where average number of visitors is less than 10 marked in red, on the map.
# 



Esempio n. 25
0
def display_map(latitude=None, longitude=None, resolution=None):
    """ Generates a folium map with a lat-lon bounded rectangle drawn on it. Folium maps can be 
    
    Args:
        latitude   (float,float): a tuple of latitude bounds in (min,max) format
        longitude  ((float, float)): a tuple of longitude bounds in (min,max) format
        resolution ((float, float)): tuple in (lat,lon) format used to draw a grid on your map. Values denote   
                                     spacing of latitude and longitude lines.  Gridding starts at top left 
                                     corner. Default displays no grid at all.  

    Returns:
        folium.Map: A map centered on the lat lon bounds. A rectangle is drawn on this map detailing the
        perimeter of the lat,lon bounds.  A zoom level is calculated such that the resulting viewport is the
        closest it can possibly get to the centered bounding rectangle without clipping it. An 
        optional grid can be overlaid with primitive interpolation.  

    .. _Folium
        https://github.com/python-visualization/folium

    """

    assert latitude is not None
    assert longitude is not None

    ###### ###### ######   CALC ZOOM LEVEL     ###### ###### ######

    margin = -0.5
    zoom_bias = 0

    lat_zoom_level = _degree_to_zoom_level(margin=margin, *
                                           latitude) + zoom_bias
    lon_zoom_level = _degree_to_zoom_level(margin=margin, *
                                           longitude) + zoom_bias
    zoom_level = min(lat_zoom_level, lon_zoom_level)

    ###### ###### ######   CENTER POINT        ###### ###### ######

    center = [np.mean(latitude), np.mean(longitude)]

    ###### ###### ######   CREATE MAP         ###### ###### ######

    map_hybrid = folium.Map(
        location=center,
        zoom_start=zoom_level,
        tiles=" http://mt1.google.com/vt/lyrs=y&z={z}&x={x}&y={y}",
        attr="Google")

    ###### ###### ######   RESOLUTION GRID    ###### ###### ######

    if resolution is not None:
        res_lat, res_lon = resolution

        lats = np.arange(*latitude, abs(res_lat))
        lons = np.arange(*longitude, abs(res_lon))

        vertical_grid = map(lambda x: ([x[0][0], x[1]], [x[0][1], x[1]]),
                            itertools.product([latitude], lons))
        horizontal_grid = map(lambda x: ([x[1], x[0][0]], [x[1], x[0][1]]),
                              itertools.product([longitude], lats))

        for segment in vertical_grid:
            folium.features.PolyLine(segment, color='white',
                                     opacity=0.3).add_to(map_hybrid)

        for segment in horizontal_grid:
            folium.features.PolyLine(segment, color='white',
                                     opacity=0.3).add_to(map_hybrid)

    ###### ###### ######     BOUNDING BOX     ###### ###### ######

    line_segments = [(latitude[0], longitude[0]), (latitude[0], longitude[1]),
                     (latitude[1], longitude[1]), (latitude[1], longitude[0]),
                     (latitude[0], longitude[0])]

    map_hybrid.add_child(
        folium.features.PolyLine(locations=line_segments,
                                 color='red',
                                 opacity=0.8))

    map_hybrid.add_child(folium.features.LatLngPopup())

    return map_hybrid
# Install Folium

# Folium is not available by default. So, we first need to install it before we are able to import it.

!conda install -c conda-forge folium=0.5.0 --yes

import folium

print('Folium installed and imported!')

# Generating the world map is straigtforward in Folium. You simply create a Folium Map object and then you display it. What is attactive about Folium maps is that they are interactive, so you can zoom into any region of interest despite the initial zoom level. 

# define the world map

world_map = folium.Map()

# display world map

world_map

"""Go ahead. Try zooming in and out of the rendered map above.

You can customize this default definition of the world map by specifying the centre of your map and the intial zoom level.

All locations on a map are defined by their respective Latitude and Longitude values. So you can create a map and pass in a center of Latitude and Longitude values of [0, 0].

For a defined center, you can also define the intial zoom level into that location when the map is rendered. The higher the zoom level the more the map is zoomed into the center.

Let's create a map centered around Canada and play with the zoom level to see how it affects the rendered map.
Esempio n. 27
0
    axis = [i for i in range(0, dim)]
    data = {"x": axis, "y": axis}
    return pd.DataFrame.from_dict(data)


lis = [1, 2, 3]

# Bokeh
p = figure(title="simple line example", x_axis_label='x', y_axis_label='y')
p.line([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], legend_label="Temp.", line_width=2)
bokeh_asset = dp.Plot(data=p)

# Folium
m = folium.Map(
    location=[45.372, -121.6972],
    zoom_start=12,
    tiles='Stamen Terrain'
)
folium.Marker(
    location=[45.3288, -121.6625],
    popup='Mt. Hood Meadows',
    icon=folium.Icon(icon='cloud')
).add_to(m)
folium.Marker(
    location=[45.3311, -121.7113],
    popup='Timberline Lodge',
    icon=folium.Icon(color='green')
).add_to(m)
folium.Marker(
    location=[45.3300, -121.6823],
    popup='Some Other Location',
Esempio n. 28
0
import folium
import math

app = Flask(__name__)

def convert(lng, lat):
    x_PI = 3.14159265358979324 * 3000.0 / 180.0
    z = math.sqrt(lng * lng + lat * lat) + 0.00002 * math.sin(lat * x_PI)
    theta = math.atan2(lat, lng) + 0.000003 * math.cos(lng * x_PI)
    bd_lng = z * math.cos(theta) + 0.0065
    bd_lat = z * math.sin(theta) + 0.006
    return [bd_lng, bd_lat]

m = folium.Map(
    location=[30.314192,120.343222],
    tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}',
    zoom_start=12,
    attr='高德地图'
)

stop_data = Stop.get_all()

def parse_zhch(chinese_str: str):
    """将中文转码,以便能正常显示
    """
    return str(str(chinese_str).encode('ascii' , 'xmlcharrefreplace'))[2:-1]

for stop in stop_data:
    folium.CircleMarker(
        location=[stop.lat, stop.lng],
        radius=2,
        popup=parse_zhch(stop.name)
Esempio n. 29
0
            "fillColor": feature["properties"]["color"],
            "color": "black",
            "weight": 0.25,
            "fillOpacity": 0.8,
        }

    n_plt = list(set(zip(cap_ikr.k, cap_ikr.r)))
    n_plt.sort()

    for a1, a2 in n_plt:
        cap = cap_ikr[(cap_ikr.k == a1)]

        if sum(cap.pct_delta == 0) != len(cap):
            cap = cap_ikr[(cap_ikr.k == a1) & (cap_ikr.r == a2)]

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

            pct_vals = dict(zip(cap.i, cap.pct_delta))

            colormap = branca.colormap.linear.RdBu_09.scale(-100, 100)
            colormap.caption = "% Change from Baseline Scenario"
            my_map.add_child(colormap)

            color_dict = {
                key: colormap(pct_vals[key])
                for key in pct_vals.keys()
            }

            for feature in geodata["features"]:
                feature["properties"]["color"] = color_dict[
                    feature["properties"]["GEOID"]]
Esempio n. 30
0
#coding:utf-8
import folium
import pandas as pd

flags = pd.DataFrame({
    'number': ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
    'latitude': [
        35.028309, 46.469391, 39.758949, 41.015137, 24.466667, 3.140853,
        9.005401, -3.989038, 52.377956, 41.085651, 57.790001, 31.205753
    ],
    'longtude': [
        135.753082, 30.740883, -84.191605, 28.979530, 54.366669, 101.693207,
        38.763611, -79.203560, 4.897070, -73.858467, -152.407227, 29.924526
    ]
})

flag_map = folium.Map(location=[35.028309, 135.753082], zoom_start=9)

for i, r in flags.iterrows():
    folium.Marker(location=[r['latitude'], r['longtude']],
                  popup=r['number']).add_to(flag_map)

flag_map