def test_image_overlay():
    """Test image overlay."""
    data = [[[1, 0, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]],
            [[1, 1, 0, 0.5], [0, 0, 1, 1], [0, 0, 1, 1]]]

    m = folium.Map()
    io = plugins.ImageOverlay(data, [[0, -180], [90, 180]], mercator_project=True)
    io.add_to(m)
    m._repr_html_()

    out = m._parent.render()

    # Verify the url generation
    assert io.url == ('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAACCAYAAACddGYaAAA'
                      'AF0lEQVR42mP4z8AARFDw/z/DeiA5H4QBV60H6ABl9ZIAAAAASUVORK5CYII=')

    # Verify the script part is okay.
    tmpl = Template("""
                var {{this.get_name()}} = L.imageOverlay(
                    '{{ this.url }}',
                    {{ this.bounds }},
                    {{ this.options }}
                    ).addTo({{this._parent.get_name()}});
    """)
    assert tmpl.render(this=io) in out

    bounds = m.get_bounds()
    assert bounds == [[0, -180], [90, 180]], bounds
Example #2
0
def create_image_map(image_data, bounds):
    min_lat, max_lat, min_lon, max_lon = bounds
    folium_map = folium.Map(location=[40.738, -73.98],
                            zoom_start=13,
                            tiles="CartoDB dark_matter",
                            width='100%')

    # create the overlay
    map_overlay = add_alpha(to_image(image_data))

    # compute extent of image in lat/lon
    aspect_ratio = map_overlay.shape[1] / map_overlay.shape[0]
    delta_lat = (max_lon - min_lon) / aspect_ratio * np.cos(
        min_lat / 360 * 2 * np.pi)

    # add the image to the map
    img = plugins.ImageOverlay(map_overlay,
                               bounds=[(max_lat - delta_lat, min_lon),
                                       (max_lat, max_lon)],
                               opacity=1,
                               name="Paths")

    img.add_to(folium_map)
    folium.LayerControl().add_to(folium_map)

    # return the map
    return folium_map
Example #3
0
cols = ds.RasterXSize 
rows = ds.RasterYSize 

#Get extent
xmin=geotransform[0]
ymax=geotransform[3]
xmax=xmin+cols*geotransform[1]
ymin=ymax+rows*geotransform[5]

#Get Central point
centerx=(xmin+xmax)/2
centery=(ymin+ymax)/2

#Raster convert to array in numpy
bands = ds.RasterCount
band=ds.GetRasterBand(1)
dataset= band.ReadAsArray(0,0,cols,rows)
dataimage=dataset
dataimage[dataimage[:,:]==-340282346638528859811704183484516925440.000]=0


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

#Save html
map.save('wd.html')
Example #4
0
def init(request):
    form = HCMRForm()
    scenario = request.GET['scenario']
    print scenario

    execution_steps = dict()
    execution_steps['OIL_SPILL_SCENARIO_1'] = [
        "starting service", "Creating simulation request",
        "Simulation running", "Simulation results received",
        "Transforming data to be shown on map",
        "Calculating oil spill intersections with protected areas", "done"
    ]
    execution_steps['OIL_SPILL_SCENARIO_2'] = [
        "starting service", "Creating simulation request",
        "Simulation running", "Simulation results received",
        "Transforming data to be shown on map",
        "Calculating oil spill intersections with protected areas", "done"
    ]
    execution_steps['OIL_SPILL_SCENARIO_3'] = [
        "starting service", "Creating simulation request",
        "Simulation running", "Simulation results received",
        "Transforming data to be shown on map",
        "Calculating oil spill intersections with protected areas", "done"
    ]
    list = []
    for i in range(0, 61):
        list.append(i * 12)
    list.pop(0)
    m = create_map()
    if int(scenario) == 2:
        data_img = Image.open(
            'visualizer/static/visualizer/img/ais_density_maps/ais_data_photo_med.png'
        )
        data = trim(data_img)
        data_img.close()
        # Overlay the image
        density_map_layer = plugins.ImageOverlay(data,
                                                 zindex=1,
                                                 opacity=0.5,
                                                 mercator_project=True,
                                                 bounds=[[30.13, -5.941],
                                                         [45.86, 36.42]])
        density_map_layer.layer_name = 'AIS Density Map'
        m.add_child(density_map_layer)
    folium.LayerControl().add_to(m)
    temp_map = 'templates/map1' + str(int(time.time())) + '.html'
    m.save(temp_map)
    map_html = open(temp_map, 'r').read()
    soup = BeautifulSoup(map_html, 'html.parser')
    map_id = soup.find("div", {"class": "folium-map"}).get('id')
    js_all = soup.findAll('script')

    # print(js_all)
    if len(js_all) > 5:
        js_all = [js.prettify() for js in js_all[5:]]

    css_all = soup.findAll('link')
    if len(css_all) > 3:
        css_all = [css.prettify() for css in css_all[3:]]
    print map_id
    return render(
        request, 'hcmr_pilot/load_service.html', {
            'form': form,
            'scenario': scenario,
            'execution_steps': execution_steps,
            'sim_len_list': list,
            'map_id': map_id,
            'js_all': js_all,
            'css_all': css_all
        })
Example #5
0
def index():
    if flask.request.args.get('date') == None:

        return flask.render_template('index.html',
                                     dates=dates,
                                     phenom=m_type,
                                     months=month)

    date = int(flask.request.args.get('date'))
    month_selected = flask.request.args.get('months')
    phenom_long = flask.request.args.get('phenom')
    duration = int(flask.request.args.get('duration'))
    for key, name in CATEGORIES.iteritems():
        if name == phenom_long:
            phenom = key

    choosed_month, year = month_selected.split('/')
    try:
        start_date = datetime.datetime(int(year), int(choosed_month), date, 00,
                                       00, 00)
        end_date = datetime.datetime(int(year), int(choosed_month), date, 23, 59, 59) + \
        datetime.timedelta(days=duration)
    except:
        return flask.render_template('error.html',
                                     dates=dates,
                                     phenom=m_type,
                                     months=month,
                                     error='date')

    # http://stackoverflow.com/questions/12438990/select-records-from-postgres-where-timestamp-is-in-certain-rangsoure
    if phenom_long == 'temperature':
        sql_sensor = "SELECT DISTINCT idsensor FROM data where (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CA' or measuretype = 'ST');" % (
            start_date, end_date)

    elif phenom_long == 'humidity':
        sql_sensor = "SELECT DISTINCT idsensor FROM data where (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CB' or measuretype = 'SH');" % (
            start_date, end_date)
    else:
        sql_sensor = "SELECT DISTINCT idsensor FROM data where (timestamp > '%s' and timestamp < '%s') and measuretype = '%s';" % (
            start_date, end_date, str(phenom))

    holice_map = folium.Map(MAP_CENTER, zoom_start=18, tiles=None)
    folium.TileLayer('OpenStreetMap').add_to(holice_map)
    folium.TileLayer('MapQuestOpen').add_to(holice_map)
    # Map.add_children(folium.plugins.ImageOverlay(...))
    # ICON_URL = 'static/python.jpg'
    holice_map.add_children(
        plugins.ImageOverlay(
            ICON_URL,
            [PICTURE_COORS],
            opacity=0.5,
        ))
    # folium.LayerControl().add_to(holice_map)
    holice_map.add_children(folium.LayerControl())

    cur.execute(sql_sensor)
    # list of sensors [int,int,int], instead of [(int,), (int,), (int,)]
    sensors = [i[0] for i in cur.fetchall()]

    multi_iter1 = {}
    locations, popups = [], []
    for sensor_sql in sensors:
        # print sensor_sql

        for sensor in SENSOR:
            # print sensor
            if sensor[0] == sensor_sql:
                sensor_start_date = datetime.datetime.strptime(
                    sensor[2], "%Y-%m-%d")
                sensor_end_date = datetime.datetime.strptime(
                    sensor[3], "%Y-%m-%d %H:%M:%S")
                start_date_new = start_date
                end_date_new = end_date
                # print str(end_date) + ' > ' + str(sensor_start_date)
                # sensor have to not end measurement before start date and not start measurement after the end of end day
                if end_date >= sensor_start_date and start_date <= sensor_end_date:
                    # if sensor start measurement after start day, the start day will be replaced by sensor start day
                    # if value of start_date and end_date will be replaced, end of sensor measurement after end_date will not be replaced
                    if sensor_start_date > start_date:
                        #print start_date, sensor_start_date
                        start_date_new = sensor_start_date
                    if sensor_end_date < end_date:
                        #print end_date, sensor_end_date
                        end_date_new = sensor_end_date  # + datetime.timedelta(days=duration)

                    sensor_data = {}
                    if phenom_long == 'temperature':
                        sql_data_sensor = "SELECT measurevalue, timestamp FROM data WHERE (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CA' or measuretype = 'ST') and idsensor = %d;" % (
                            start_date_new, end_date_new, int(sensor[0]))
                    elif phenom_long == 'humidity':
                        sql_data_sensor = "SELECT measurevalue, timestamp FROM data WHERE (timestamp > '%s' and timestamp < '%s') and (measuretype = 'CB' or measuretype = 'SH') and idsensor = %d;" % (
                            start_date_new, end_date_new, int(sensor[0]))
                    else:
                        sql_data_sensor = "SELECT measurevalue, timestamp FROM data WHERE (timestamp > '%s' and timestamp < '%s') and measuretype = '%s' and idsensor = %d;" % (
                            start_date_new, end_date_new, str(phenom),
                            int(sensor[0]))
                    print sql_data_sensor
                    cur.execute(sql_data_sensor)
                    # sort tuples by time_pattern
                    sql_data = sorted(list(cur.fetchall()),
                                      key=lambda time: time[1])

                    for row in sql_data:
                        # http://stackoverflow.com/questions/16198606/python-linux-timestamp-to-date-time-and-reverse
                        # https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
                        time_index = int(
                            time.mktime(
                                time.strptime(str(row[1]),
                                              "%Y-%m-%d %H:%M:%S")) * 1000)
                        # some data do not have measurevalue (83k rows)

                        if row[0]:
                            value = float(row[0])
                        else:
                            value = 0.0
                        sensor_data[time_index] = value

                    multi_iter1[sensor[0]] = sensor_data
                    # if there are no data

                    if multi_iter1[sensor[0]]:
                        vis = vincent.Line(multi_iter1[sensor[0]],
                                           width=600,
                                           height=200)
                        x_axis_str = 'data for sensor (' + str(
                            sensor[0]) + '). Time period: ' + str(
                                start_date_new) + ' to ' + str(end_date_new)
                        vis.axis_titles(x=str(x_axis_str), y=phenom_long)

                        vis._axis_properties(axis='y',
                                             title_size=15,
                                             title_offset=-10,
                                             label_align='right',
                                             label_angle=0,
                                             color='#000000')
                        vis.scales['x'] = vincent.Scale(name='x',
                                                        type='time',
                                                        range='width',
                                                        domain=vincent.DataRef(
                                                            data='table',
                                                            field="data.idx"))
                        vis.scales['y'] = vincent.Scale(name='y',
                                                        type='linear',
                                                        range='height',
                                                        domain=vincent.DataRef(
                                                            data='table',
                                                            field="data.val"))

                        vis.to_json('static/vis_%s.json' % sensor[0])

                        popups.append(
                            folium.Popup(max_width=1900).add_child(
                                folium.Vega(json.load(
                                    open('static/vis_%s.json' % sensor[0])),
                                            width="100%",
                                            height="100%")))

                        locations.append(sensor[1])

    if not locations:
        return flask.render_template('error.html',
                                     dates=dates,
                                     phenom=m_type,
                                     months=month,
                                     error='locations')
    holice_map.add_children(plugins.MarkerCluster(locations, popups))

    holice_map.save('templates/map.html')

    return flask.render_template('map.html')
Example #6
0
import os
import folium
from folium import plugins

Uni_map = os.path.join('', 'Uni_map.png')

map_osm = folium.Map(location=[65.0593, 25.4663],
                     zoom_start=17,
                     tiles='Stamen Terrain')
folium.Marker([65.0593, 25.4663], popup='Central Station').add_to(map_osm)
folium.Marker([65.0593, 25.4669], popup='Tellus Library').add_to(map_osm)
folium.CircleMarker(location=[65.0599, 25.4699],
                    radius=50,
                    popup='You are in University area',
                    color='#3186cc',
                    fill_color='#3186cc').add_to(map_osm)

plugins.ImageOverlay(
    image=open(Uni_map, 'r'),
    bounds=[[65.0540, 25.4585], [65.0640, 25.4765]],
    opacity=0.8,
).add_to(map_osm)

folium.LayerControl().add_to(map_osm)

map_osm.save(os.path.join('', 'map2.html'))
Example #7
0
from folium import plugins

path = 'D:/Project_Data/Arctic_PRIZE/Processed_Data/S1'

merc = os.path.join(
    path,
    'S1A_EW_GRDM_1SDH_20170601T071215_20170601T071320_016837_01BFE1_35BF_terrian_200mHH.tif'
)

m = folium.Map([37, 0], zoom_start=1, tiles='stamentoner')

img = plugins.ImageOverlay(
    name='Mercator projection SW',
    image=merc,
    bounds=[[15, 80], [83, 35]],
    opacity=0.6,
    interactive=True,
    cross_origin=False,
    zindex=1,
)

folium.Popup('I am an image').add_to(img)

img.add_to(m)

folium.LayerControl().add_to(m)

m.save(os.path.join('results', 'ImageOverlay_0.html'))

m
Example #8
0
cluster2.layer_name = "Locations with more than {:d} daily pickups".format(
    MIN_SHOW_CHART)

# Overlay the image
import scipy
from scipy.ndimage.filters import gaussian_filter
wherePeopleLive = np.flipud(
    np.load('whereArePeopleGoing.npy')[:, :, -2]).astype(float)
wherePeopleLive = scipy.ndimage.filters.gaussian_filter(wherePeopleLive,
                                                        sigma=4)
wherePeopleLive = np.log10(wherePeopleLive + 1)
wherePeopleLive[np.where(wherePeopleLive == 0)] = np.nan

whereArePeopleGoing = plugins.ImageOverlay(wherePeopleLive, opacity=0.8, \
                                           bounds =[[40.550, -74.150],\
                                                    [40.900, -73.750]],\
                                           colormap=plt.cm.inferno,\
                                           attr = 'Where do young people live?')
whereArePeopleGoing.layer_name = "Where do young people live?"
whereArePeopleGoing.add_to(map_of_nyc)

########################################
from folium.plugins import *
folium.plugins.MeasureControl(position='topright',
                              primary_length_unit='miles',
                              secondary_length_unit='meters')

########################################
map_of_nyc.add_child(folium.LayerControl())
map_of_nyc.save('map.html')
################################################################################
plt.margins(0, 0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.savefig(FileName, bbox_inches='tight', pad_inches=0, dpi=300)

# Create a map and overlay the image
map_osm = folium.Map(location=[lat_destination, long_destination],
                     zoom_start=10)

folium.Marker([lat_destination, long_destination],
              popup='Work').add_to(map_osm)
folium.Marker([lat_home, long_home], popup='Home').add_to(map_osm)

plugins.ImageOverlay(
    image=open(FileName, 'br'),
    bounds=[[min(lat), min(long)], [max(lat), max(long)]],
    opacity=0.4,
).add_to(map_osm)

folium.LayerControl().add_to(map_osm)
map_osm.save('TravelTimeMap.html')
"""
TILES:
     |  - "OpenStreetMap"
 |      - "Mapbox Bright" (Limited levels of zoom for free tiles)
 |      - "Mapbox Control Room" (Limited levels of zoom for free tiles)
 |      - "Stamen" (Terrain, Toner, and Watercolor)
 |      - "Cloudmade" (Must pass API key)
 |      - "Mapbox" (Must pass API key)
 |      - "CartoDB" (positron and dark_matter)
 """