Пример #1
0
def schedule(lat, long, limit, radius = 10000):
    form = SearchDeparturesForm(request.form)
    map = folium.Map(location=(48.89608815877061, 2.235890140834457), zoom_start=19)
    map.add_child(folium.LatLngPopup())
    trips = []
    tp = []
    if request.method == 'POST' and form.validate():
        address = form.address.data
        point = find_point(address)
        limit = form.limit.data
        #print(point)
        if point is not None:
            #radius = form.radius.data
            coordinates = get_all_coordinates()
            coordinates = [c for c in coordinates if get_distance((c['lat'], c['long']), (point[0], point[1])) < radius]
            map = folium.Map(location=point)
            if coordinates:
                bounds = get_bounds([(c['lat'], c['long']) for c in coordinates])
                map.fit_bounds(bounds)
            map.add_child(folium.LatLngPopup())
            for c in coordinates:
                folium.Marker([c['lat'], c['long']], popup=f'<i>{c["name"].replace("_", " ")}</i>').add_to(map)
            trips = get_departures_around(point[0], point[1], limit)
            dtimes = []
            for t in trips:
                    if (t['dTime'] not in dtimes):
                        dtimes.append(t['dTime'])
                        tmp_dict = {'routeLongName': t['routeLongName'].replace('_', ' '), 'dTime': t['dTime'], 'dStation' : t['name'].replace('_', ' ')}                   
                        tp.append(tmp_dict)
                        folium.Marker([t['lat'], t['long']], popup=f'<i>{t["name"].replace("_", " ")}</i>').add_to(map)
            redirect(url_for('schedule.schedule', lat=point[0], long=point[1], limit = limit, trips = tp))
    return render_template('schedule/schedule.html', map=map._repr_html_(), form=form, trips = tp)
Пример #2
0
def draw_relation(relation, cross_info):
    m = folium.Map([31.2240060, 121.4639028], zoom_start=15)
    for single_relation in relation:
        color = get_random_color()
        for ele in single_relation:
            location_1 = [cross_info[ele[0]][6], cross_info[ele[0]][5]]
            location_2 = [cross_info[ele[1]][6], cross_info[ele[1]][5]]
            location = [location_1, location_2]
            route = folium.PolyLine(location,
                                    weight=5,
                                    color='black',
                                    opacity=1).add_to(m)
    m.add_child(folium.LatLngPopup())
    m.add_child(folium.ClickForMarker(popup='Waypoint'))
    # for ele in cross_info:
    #     coordinate = [ele[6], ele[5]]
    #     folium.Marker(
    #         # folium格式,【纬度,经度】
    #         location=coordinate,
    #         fill_color='#43d9de',
    #         radius=8
    #     ).add_to(m)

    m.save(
        os.path.join(r'' + os.path.dirname(os.getcwd()) + '/dataset/',
                     'relation_no_node.html'))
Пример #3
0
def plot_isolinemap(coord_list1, coord_list2,coords,data):
    
    m = folium.Map(coords[0], zoom_start=6, tiles='cartodbpositron')
    polygon = Polygon(coords)
    folium.GeoJson(polygon).add_to(m)
    folium.LatLngPopup().add_to(m)
    lat=[]
    lon=[]
    labs=[]
    coords_route=[]
    n=len(data['response']['route'][0]['leg'][0]['maneuver'])
    for i in range(n):
        a=data['response']['route'][0]['leg'][0]['maneuver'][i]['position']['latitude']
        b=data['response']['route'][0]['leg'][0]['maneuver'][i]['position']['longitude']
        labs.append(i)
        lat.append(float(a))
        lon.append(float(b))
        coords_route.append((float(a),float(b)))

    for entry in charging_stations:
        folium.Marker(entry,popup='Charging Port',icon=folium.Icon(color='red')).add_to(m)
    
    for uber in uber_data:
        folium.Marker([uber['latitude'],uber['longitude']],popup=uber['uber_id'],icon=folium.Icon(color='green')).add_to(m)

    folium.Marker([lat[0], lon[0]],popup = 'A').add_to(m)
    folium.Marker([lat[n-1], lon[n-1]],popup = 'B').add_to(m)
    folium.PolyLine(locations = coords_route, line_opacity = 0.5).add_to(m)
    m.save("C:\\Users\\Saanika\\Desktop\\map3.html")
    
    return m
Пример #4
0
def personalMarker():
    """Return the homepage."""

    stats_db = db.session.query(Traffic_Violations_Metadata.date_of_stop,
                                Traffic_Violations_Metadata.latitude,
                                Traffic_Violations_Metadata.longitude,
                                Traffic_Violations_Metadata.state,
                                Traffic_Violations_Metadata.violation_type,
                                Traffic_Violations_Metadata.race,
                                Traffic_Violations_Metadata.gender).filter(
                                    Traffic_Violations_Metadata.__table__.
                                    c["personal_injury"] == 1).all()
    alist = []
    for x in stats_db:
        adict = [x[1], x[2]]
        alist.append(adict)

    map_osm = folium.Map(
        location=[39.15807667, -77.213965],
        zoom_start=10,
        #tiles='./tiles/{z}/{x}/{y}.png',
        attr='osm')

    for item in alist:
        folium.Marker([item[0], item[1]],
                      popup=str(item[0]) + ',' + str(item[1])).add_to(map_osm)

    map_osm.add_child(folium.LatLngPopup())
    file_path = r"./templates/demo.html"
    map_osm.save(file_path)

    return render_template("demo.html")
Пример #5
0
def drawSiteLocation():
    basemap = folium.Map(
        location=[df['latitude'].mean(), df['longitude'].mean()])
    for site in siteRecord:
        folium.Marker(location=siteRecord[site]).add_to(basemap)
    basemap.add_child(folium.LatLngPopup())
    basemap.save(siteMapPath)
Пример #6
0
def generate_map(latitude=39.7,
                 longitude=3,
                 zoom=8,
                 did=None,
                 emailAddress=None,
                 *args,
                 **kwargs):
    location_data = load()

    location_data = location_data[location_data.accuracy < 1000]
    location_data = prepare(location_data)

    m = folium.Map([float(latitude), float(longitude)], zoom_start=int(zoom))
    geo_matrix = location_data[['latitude', 'longitude']].values

    m.add_child(plugins.HeatMap(geo_matrix, radius=15))
    m.add_child(folium.LatLngPopup())
    mime_html = 'text/html'

    fn = os.getcwd() + (f'/proxy-{did}.html' or '/did/index.html')
    m.save(fn)
    if emailAddress:
        from .gdrive import upload, authorize
        fileId = upload(fn, mime_html)
        print(fileId, emailAddress)
        authorize(emailAddress=emailAddress, fileId=fileId)

    content = get_file(fn)
    return Response(content, mimetype=mime_html)
Пример #7
0
 def Map(self, datas):
     x2 = [i[1] for i in datas]  #all the coord
     if (
             len(x2) == 0
     ):  #if there is no coordinates in tweets, then the show the default map: start in Bologna
         m = self.generaMap()
         return m
     else:
         m = folium.Map(location=datas[0][1])  #position of Bologna
         for dati in datas:
             marker_cluster = MarkerCluster().add_to(m)
             # print(dati[2])
             html = '<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>'
             html += '<blockquote class="twitter-tweet tw-align-center" data-lang="en"><p lang="en" dir="ltr"><a href="https://twitter.com/vitadiste/status/' + str(
                 dati[4]) + '?ref_src=twsrc%5Etfw"></a>'
             html += '</blockquote>'
             iframe = folium.IFrame(html,
                                    width=500,
                                    height=300,
                                    ratio='20%')
             popup = folium.Popup(iframe, max_width=1000)
             folium.Marker(dati[1], popup=popup,
                           tooltip=dati[3]).add_to(marker_cluster)
             #if non pictures, then show in popup just text
             m.add_child(folium.LatLngPopup(
             ))  #when click in map, show the corrispond coordinates
             m.save(os.path.dirname(__file__) + "/../mappa.html")
     m.save(os.path.dirname(__file__) + "/../mappa.html")
     return m
Пример #8
0
def basic_map():
    Map = folium.Map(location=[31.83, 117.23],
                     tiles='Stamen Toner',
                     zoom_start=12)
    Map.add_child(folium.LatLngPopup())
    # Map.save('test.html')
    return Map
Пример #9
0
def create_map(brand, longitude, latitude, address, diesel):
    # Latitude - долгота
    # Longitude - широта

    # Create base map
    mp = folium.Map(location=[54.9893, 82.9070],
                    zoom_start=7,
                    tiles='OpenStreetMap')
    # Other tiles: Stamen Terrain, Stamen Toner, Mapbox Bright, Mapbox Control Room and other

    # Create Cluster
    marker_cluster = MarkerCluster().add_to(mp)

    for i in range(len(longitude)):
        if longitude[i] >= 56:  # Сохраняем Сибирь и Восток
            # Plot markers and add to marker_cluster
            icon_name = 'truck' if diesel[i] else 'car'

            folium.Marker(location=[latitude[i], longitude[i]],
                          popup=address[i],
                          tooltip=brand[i],
                          icon=folium.Icon(icon=icon_name,
                                           prefix='fa')).add_to(marker_cluster)
            # more icons on https://fontawesome.com/v4.7.0/icons/

    # Enable lat/lon popovers
    mp.add_child(folium.LatLngPopup())

    # Save the map
    mp.save("map1.html")
Пример #10
0
    def __init__(self, **kwargs):

        # Default map center location and zoom level
        latlon = [40, -100]
        zoom = 4

        # Interchangeable parameters between ipyleaflet and folium
        if 'center' in kwargs.keys():
            kwargs['location'] = kwargs['center']
            kwargs.pop('center')
        if 'location' in kwargs.keys():
            latlon = kwargs['location']
        else:
            kwargs['location'] = latlon

        if 'zoom' in kwargs.keys():
            kwargs['zoom_start'] = kwargs['zoom']
            kwargs.pop('zoom')
        if 'zoom_start' in kwargs.keys():
            zoom = kwargs['zoom_start']
        else:
            kwargs['zoom_start'] = zoom

        super().__init__(**kwargs)
        ee_basemaps['HYBRID'].add_to(self)
        folium.LatLngPopup().add_to(self)
        plugins.Fullscreen().add_to(self)

        self.fit_bounds([latlon, latlon], max_zoom=zoom)
Пример #11
0
    def setup_map(self):
        if GOOGLE_MAP:
            tiles = 'https://mt.google.com/vt/lyrs=s&x={x}&y={y}&z={z}'  # google 卫星图
        else:
            tiles = 'http://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}'  # 高德卫星图

        self.Map = folium.Map(
            location=MAP_DEFAULT_CENTER_LOCATION,
            zoom_start=self.Zoom,
            tiles=tiles,
            # tiles='http://webrd02.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=7&x={x}&y={y}&z={z}', # 高德街道图
            # tiles='http://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}', # 高德卫星图
            # tiles='https://mt.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', # google 卫星图
            # tiles='https://mt.google.com/vt/lyrs=h&x={x}&y={y}&z={z}', # google 地图
            attr='default')

        self.ColorMap = branca.colormap.StepColormap(
            [(55, 168, 218), (187, 249, 112), (255, 255, 0), (113, 130, 36),
             (113, 174, 38), (255, 255, 255)],
            vmin=1,
            vmax=7,
            index=[1, 2, 3, 4, 5, 6, 7],
            caption=
            'Fix Quality: 1=SPS, 2=Differential, 3=PPS, 4=RTK Fixed, 5=RTK Float, 6=Estimated'
        )

        self.Map.add_child(self.ColorMap)
        self.Map.add_child(folium.LatLngPopup())
Пример #12
0
def map_constr(fg: folium.FeatureGroup(), loc: tuple, name: str = "map.html"):
    """Construct the layered map.

    :param fg: external feature group
    :param loc: location of the user
    :param name: html file name
    :return: None
    """
    m = folium.Map(location=loc, zoom_start=2)
    fg.add_child(folium.Marker(
        location=loc,
        popup='Your location',
        icon=folium.Icon(color='red')
    ))

    new_feat = folium.FeatureGroup(name="World Part")
    new_feat.add_child(folium.GeoJson(data=open("world.json", encoding="utf-8-sig").read(),
                                      style_function=lambda x: {'fillColor': 'green'
                                                                if x["properties"]["REGION"] < 3
                                                                else "blue" if 3 <= x["properties"]["REGION"] < 5
                                                                else "orange" if 5 <= x["properties"]["REGION"] < 10
                                                                else "red"}))
    folium.LatLngPopup().add_to(m)
    m.add_child(fg)
    m.add_child(new_feat)
    m.add_child(folium.LayerControl())
    m.save(name)
Пример #13
0
def plot_basins_from_lat_long(basins_with_ppt, basin_name, all_basin_geoms, randomize = False):
    """ Plot the given basins along with precipitation """
    """ Gives error sometimes as some of the basins are not present"""
    from folium.plugins import HeatMap
    import random
    
    if (not randomize):    
        basin_data = basins_with_ppt[basin_name]
    else:
        basin_name = random.choice(list(all_basin_geoms.keys()))
        basin_data = basins_with_ppt[basin_name]
        
    lat_point_list = basin_data["Latitude"]
    lon_point_list = basin_data["Longitude"]
    polygon_geom = Polygon(zip(lon_point_list, lat_point_list))

    
    crs = {'init': 'epsg:4326'}
    m = folium.Map(zoom_start=100, tiles='cartodbpositron')

#    polygon = gpd.GeoDataFrame(index=[0], crs=crs, geometry=[polygon_geom])       
#    folium.GeoJson(polygon).add_to(m)
#    folium.LatLngPopup().add_to(m)
    
    HeatMap(data=basin_data[['Latitude', 'Longitude', 'Precipitation']].groupby(['Latitude', 'Longitude']).sum().reset_index().values.tolist(), radius=8, max_zoom=13).add_to(m)
    
    polygon = gpd.GeoDataFrame(index=[0], crs=crs, geometry=[all_basin_geoms[basin_name]])
    folium.GeoJson(polygon).add_to(m)
    folium.LatLngPopup().add_to(m)
    m.fit_bounds(polygon_geom.bounds)
    
    return m
Пример #14
0
 def FunDraw(self, datas):
     x2 = [i[3] for i in datas]  #all the coord
     if (len(x2) == 0):
         m = self.generaMap()
         return m
     else:
         m = folium.Map(location=datas[0][3])
         for dati in datas:
             # print(dati[2])
             marker_cluster = MarkerCluster().add_to(m)
             # print(dati[2])
             html = '<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>'
             html += '<blockquote class="twitter-tweet" tw-align-center data-lang="en"><p lang="en" dir="ltr"><a href="https://twitter.com/vitadiste/status/' + str(
                 dati[1]) + '?ref_src=twsrc%5Etfw"></a>'
             html += '</blockquote>'
             iframe = folium.IFrame(html,
                                    width=600,
                                    height=400,
                                    ratio='20%')
             popup = folium.Popup(iframe, max_width=1000)
             folium.Marker(dati[3], popup=popup,
                           tooltip=dati[5]).add_to(marker_cluster)
             folium.PolyLine(x2, color=self.randomcolor(),
                             weight=5).add_to(m)
             m.add_child(folium.LatLngPopup(
             ))  #when click in map, show the corrispond coordinates
             m.save(os.path.dirname(__file__) + "/../mappa.html")
     m.save(os.path.dirname(__file__) + "/../mappa.html")
     return m
Пример #15
0
def Mapa_Inicial():

    m = folium.Map(location=[-0.176290, -78.483158],
                   tiles='openstreetmap',
                   zoom_start=13)

    m.add_child(folium.LatLngPopup())
    display(m)
    r = 'running'
    global input_coords_list
    input_coords_list = []
    print(
        'Ingrese sus ubicaciones comenzando por su lugar central. Para terminar ingrese la palabra "FIN": \n'
    )
    while r == 'running':

        #coordenadas=input('Ingrese sus ubicaciones comenzando por su lugar central. Para terminar ingrese la palabra "FIN": \n')
        coordenadas = input()

        if coordenadas == 'FIN':
            r = 'FIN'
            break

        coordenadas = coordenadas.split(',')
        coordenadas = list(map(float, coordenadas))
        if type(coordenadas) == list:
            input_coords_list.append(coordenadas)  #Cambio hecho aquí
            print('Punto: ', coordenadas, ' registrado correctamente.\n')
        elif type(coordenadas) != list:
            print(
                'Valores ingresados no válidos. Ingrese únicamente valores válidos de latitud y longitud según el mapa, o FIN para finalizar.\n'
            )
def mapa(estaciones, ceseve, ruta_info):
    # creamos el mapa
    m = folium.Map(tiles='Stamen Terrain', zoom_start=0.5, min_zoom=2)
    # graficamos las estaciones
    for estacion in estaciones:
        lista = estacion.get_contents()['channels'][0].split(".")
        nombre = lista[0] + "." + lista[1]
        latitud = estacion[0][0].__dict__["_latitude"]
        longitud = estacion[0][0].__dict__["_longitude"]
        folium.Marker(location=[latitud, longitud],
                      popup=nombre).add_to(m)  #nombre
        m.add_child(folium.LatLngPopup())

    # cargamos la informacion del terremoto
    directorio = ruta_info + "/info.txt"
    archivo = open(directorio)
    archivos = []
    for element in archivo:
        archivos.append(element.strip())
    ceseve = ceseve[ceseve["id_evento"] == archivos[0]]
    lon_e = ceseve["lon_cmt"].values[0]
    lat_e = ceseve["lat_cmt"].values[0]
    folium.Marker(location=[lat_e, lon_e],
                  popup='Lugar Evento',
                  icon=folium.Icon(color='red', icon='info-sign')).add_to(m)
    os.chdir(ruta_info)
    m.save('index.html')
    webbrowser.open("index.html")
Пример #17
0
    def removeEverything(self):

        self.map = folium.Map(location=[self.lat, self.lon],
                              width=500,
                              height=500,
                              zoom_start=13)
        self.map.add_child(folium.LatLngPopup())
        self.map.save(self.routedPath)
Пример #18
0
 def index():
     start_coords = (19.663280, 75.300293)
     folium_map = folium.Map(location=start_coords, zoom_start=7)
     folium.LatLngPopup().add_to(folium_map)
     folium_map.save('templates/basic_input_map.html')
     form = ReusableForm(request.form)
     print(form.errors)
     return render_template('index.html', form=form)
Пример #19
0
 def generaMap(self):
     m = folium.Map(witdth='100%',
                    height='90%',
                    location=[44.4933, 11.3432])  #position of Bologna
     m.add_child(folium.LatLngPopup(
     ))  # if you click one point, it shows corrisponde coordinates
     m.save(os.path.dirname(__file__) + "/../mappa.html")
     return m
Пример #20
0
def read_root(request: Request):
    print(request)
    start_coords = (46.9540700, 142.7360300)
    folium_map = folium.Map(location=start_coords, zoom_start=14)
    c = folium.LatLngPopup()
    folium_map.add_child(c)
    folium_map.save("templates/map.html")
    return templates.TemplateResponse("index.html", {"request": request})
Пример #21
0
def printMap(coordinates,zoom,poly):
    '''
    Print the map and the polygon pass in array []
    Return Map
    '''
    m = folium.Map(coordinates, zoom_start=zoom, tiles='cartodbpositron')
    folium.GeoJson(poly).add_to(m)
    folium.LatLngPopup().add_to(m)
    return m
Пример #22
0
def line_index(request):
    page = request.GET.get('page', '1')
    kw = request.GET.get('kw', '')
    line = request.GET.get('line', '')

    line_list = LineCongestion.objects.order_by('-line')
    line_stops = Line.objects.filter(line_num=line)
    if line:
        start_stop = Stop.objects.filter(ars=line_stops[0].stop)
        if len(start_stop) > 0:
            start_location = [start_stop[0].y, start_stop[0].x]
            m = folium.Map(location=start_location, zoom_start=14)
        else:
            start_location = [37.53259896192619, 126.98341369628906]
            m = folium.Map(location=start_location, zoom_start=12)
    else:
        start_location = [37.53259896192619, 126.98341369628906]
        m = folium.Map(location=start_location, zoom_start=12)
    points = []
    for line_stop in line_stops:
        stops = Stop.objects.filter(ars=line_stop.stop)
        if len(stops) > 0:
            html = """
                <iframe src="./stop/""" + str(
                stops[0].ars
            ) + """" width='100%' height='300vh'; style="border:none;"></iframe>
                """
            location = [stops[0].y, stops[0].x]
            points.append(location)
            popup = folium.Popup(html, max_width=1000, min_width=600)
            icon = folium.Icon(color='blue', icon='home', prefix='glyphicon')
            m.add_child(
                folium.Circle(location=location,
                              radius=5,
                              fill_color='black',
                              popup=popup,
                              icon=icon))
    minimap = MiniMap()
    m.add_child(minimap)
    m.add_child(folium.LatLngPopup())
    if len(points) > 0:
        folium.PolyLine(points, color="blue", weight=5, opacity=1).add_to(m)
    m = m._repr_html_()

    if kw:
        line_list = line_list.filter(Q(line__icontains=kw)).distinct()

    paginator = Paginator(line_list, 10)
    page_obj = paginator.get_page(page)
    context = {
        'line_list': page_obj,
        'page': page,
        'kw': kw,
        'line': line,
        'm': m
    }
    return render(request, 'sbclc/line_list.html', context)
Пример #23
0
def show_marker(code):
    info = find_info(code)
    Destination = [info[2], info[3]]
    m = folium.Map(location= Destination, zoom_start=15)
    m.add_child(folium.LatLngPopup())

    folium.Circle(radius=500, location=Destination, color='green').add_to(m)
    folium.Marker(location= Destination, popup='<b>Destination</b>'+'\n'+'<i>'+info[0]).add_to(m)
    m.save('map.html')
Пример #24
0
def generate_base_map(gdf):
    """[summary] creates a base map for use in building Naptan maps.

    Args:
        gdf ([geopandas data]): [description]
        map_name ([str]): [str identify of the map]
    Returns:
        [type]: [description]
    """

    gm = folium.Map(
        location=[gdf["Latitude"].mean(), gdf["Longitude"].mean()],
        zoom_start=11,
        prefer_canvas=True,
        zoom_control=True,
        control_scale=True,
    )
    #  add measure control with km and area return calculations.
    gm.add_child(
        MeasureControl(
            position="bottomright",
            primary_length_unit="kilometers",
            secondary_length_unit="miles",
            secondary_area_unit="acres",
            primary_area_unit="sqmeters",
        ))
    # added lat long pop up for reference
    folium.LatLngPopup().add_to(gm)
    # clustering added
    mc = MarkerCluster().add_to(gm)

    # add the popups with relevant data
    for row in gdf.itertuples():
        html = f"""<!DOCTYPE html><div class="boxed">
                <b>ATCOCode:</b> <i>{row.ATCOCode}</i><br>
                <b>StopType:</b> <i>{row.StopType}</i><br>
                <b>StopPoint:</b> <i>{row.StopPoint}</i><br>
                <b>Coordinates:</b> <i>{row.Latitude}, {row.Longitude}</i><br>
                <b>Locality_Name:</b> {row.LocalityName}<br>
                <b>AreaName:</b> <i>{row.AreaName}</i><br>
                </div>
                """
        # add the markers to the marker cluster.
        mc.add_child(
            folium.Marker(
                location=[row.Latitude, row.Longitude],
                popup=html,
                radius=8,
                icon=folium.Icon(color="green", prefix="fa-", icon="ok-sign"),
            ))
    # add layer control.
    folium.LayerControl(collapsed=False, position="topright").add_to(gm)
    # get name of the mapped area.
    map_name = gdf.AreaName.iloc[0]
    # save the map
    save_generated_map(mc, map_name=map_name)
    return gm
Пример #25
0
def display_wms(polygon, bbox, wms, wms_layers, time, height=512):
    """
    Display polygons and their satellite img using WMS and an interactive map. Use only in Jupyter Notebooks.

    :param polygon: a shapely [Multi]Polygon for the area of interest (AOI)
    :param bbox: the bbox of the AOI
    :param height: the height of the satellite image. Width is computed to keep proportions. Defaults to 512
    :param wms_layers: a string mapped to the layers of interest. Can take two values:
    '0' (only first layer) or 'all' (all layers)
    :param time: date range for the satellite image formatted as 'YYYY-MM-DD' or 'YYYY-MM-DD/YYYY-MM-DD'
    (eg '2018-12-27/2019-01-10')
    """
    map_center = polygon.centroid
    m = folium.Map([map_center.y, map_center.x],
                   zoom_start=3,
                   tiles='cartodbpositron')
    folium.GeoJson(polygon).add_to(m)
    folium.LatLngPopup().add_to(m)
    display(m)

    projection = 'EPSG:4326'
    width = height2width(bbox, height)

    layers = list(wms.contents)

    if wms_layers == '0':
        # get layer from WMS
        print(wms[layers[0]].title)
        img = wms.getmap(layers=[wms[layers[1]].name],
                         srs=projection,
                         bbox=bbox,
                         size=(width, height),
                         format='image/png',
                         time=time,
                         showlogo=False,
                         transparent=False,
                         maxcc=30)

        display(Image.open(img))

    elif wms_layers == 'all':
        # get layers from WMS
        for lay in layers:
            print(wms[lay].title)
            img = wms.getmap(layers=[wms[lay].name],
                             srs=projection,
                             bbox=bbox,
                             size=(width, height),
                             format='image/png',
                             time=time,
                             showlogo=False,
                             transparent=False,
                             maxcc=30)

            display(Image.open(img))
Пример #26
0
def heapMapLatLon():
    marker = None
    latitude = None
    longitude = None
    dateRequest = None

    if request.method == 'POST':
        latitude = request.form.get('latitude')
        longitude = request.form.get('longitude')
        marker = folium.Marker(location=[latitude, longitude],
                               popup='<i>Usted esta aqui!!</i>',
                               tooltip='Click me!',
                               icon=folium.Icon(color='red'))
        dateRequest = request.form.get('date')
        dateform = datetime.datetime.strptime(dateRequest, '%m/%d/%Y')
        dateUse = '2018-' + str(dateform.date().month) + '-' + str(
            dateform.date().day)

    #Create the map
    start_coords = (-34.60, -58.42)
    folium_map = folium.Map(location=start_coords, zoom_start=13)
    folium_map.add_child(folium.LatLngPopup())

    if (dateRequest is not None):
        # Seleccionamos solo las columnas de coordenadas validas para la fecha seleccionada
        df = initDataFrame()
        df_selected = df[(df['latitud'] != 0) & (df['longitud'] != 0) &
                         (df['fecha_for'] == dateUse)]

        #Create de HeatMap
        HeatMap(data=df_selected[['latitud', 'longitud', 'count']].groupby(
            ['latitud', 'longitud']).sum().reset_index().values.tolist(),
                radius=8,
                max_zoom=13).add_to(folium_map)

        #Add marker
        if marker is not None:
            folium_map.add_child(marker)

        #Save in html
        folium_map.save('static/map.html')
        return render_template('mapa.html',
                               current_time=int(time.time()),
                               latitude=latitude,
                               longitude=longitude,
                               date=dateRequest)
    else:
        #Save in html
        folium_map.save('static/map.html')
        return render_template('mapa.html',
                               current_time=int(time.time()),
                               latitude=latitude,
                               longitude=longitude,
                               date=dateRequest)
Пример #27
0
def setControlVisibility(self,
                         layerControl=True,
                         fullscreenControl=True,
                         latLngPopup=True):

    if layerControl:
        folium.LayerControl().add_to(self)
    if fullscreenControl:
        plugins.Fullscreen().add_to(self)
    if latLngPopup:
        folium.LatLngPopup().add_to(self)
Пример #28
0
 def __init__(self, lat, lon):
     #Create map object and allow click to get location
     self.lat, self.lon = lat, lon
     self.map = folium.Map(location=[lat, lon],
                           width=500,
                           height=500,
                           zoom_start=13)
     self.map.add_child(folium.LatLngPopup())
     #self.routedPath = "html/routedMap.html"
     self.routedPath = os.path.split(
         os.path.abspath(__file__))[0] + r'/html/routedMap.html'
Пример #29
0
def create_map(Destination):
    m = folium.Map(location=[40.1776, 44.5126], zoom_start=15)
    m.add_child(folium.LatLngPopup())
    with open("Stations.json") as f:
        Station = json.load(f)

    folium.Circle(radius=500, location=Destination, color='green').add_to(m)
    marker = {"Destination": Destination}
    for i in marker.items():
        folium.Marker(location=i[1], popup=i[0]).add_to(m)
        print(i)
    m.save('map.html')
Пример #30
0
def sncf_stops(lat, long, radius):
    form = SearchMapForm(request.form)
    map = folium.Map(location=(48.89608815877061, 2.235890140834457), zoom_start=19)
    map.add_child(folium.LatLngPopup())
    if request.method == 'POST' and form.validate():
        address = form.address.data
        point = find_point(address)
        print(point)
        if point is not None:
            radius = form.radius.data
            coordinates = get_all_coordinates()
            coordinates = [c for c in coordinates if get_distance((c['lat'], c['long']), (point[0], point[1])) < radius]
            map = folium.Map(location=point)
            if coordinates:
                bounds = get_bounds([(c['lat'], c['long']) for c in coordinates])
                map.fit_bounds(bounds)
            map.add_child(folium.LatLngPopup())
            for c in coordinates:
                folium.Marker([c['lat'], c['long']], popup=f'<i>{c["name"].replace("_", " ")}</i>').add_to(map)
            redirect(url_for('map.sncf_stops', lat=point[0], long=point[1], radius=radius))
    return render_template('map/sncf-stops.html', map=map._repr_html_(), form=form)