def create_map(df_collisions, df_stations, boroughs):
    geo_map = Map(location=[40.74527, -73.988573], tiles=None, zoom_start=12, control_scale=True)
    close_distance = 200  # meters

    # collisions
    TileLayer('Stamen Terrain', name='Collision Data').add_to(geo_map)
    for borough in boroughs:
        feature_group = FeatureGroup(name=borough.capitalize())
        marker_cluster = MarkerCluster().add_to(feature_group)
        df_collisions[df_collisions['borough'] == borough].apply(
            lambda r: Marker(
                location=[r['latitude'], r['longitude']],
                tooltip=f"{r['cyclist_injured'] + r['cyclist_killed']} cyclists injured/killed",
                icon=Icon(color='darkblue', icon='exclamation-circle', prefix='fa')).add_to(marker_cluster),
            axis=1)
        feature_group.add_to(geo_map)

    # bike stations
    quartiles = df_stations['close_collisions'].quantile([0.25, 0.5, 0.75]).tolist()
    feature_group = FeatureGroup(name='Bike Stations')
    df_stations.apply(lambda r: CircleMarker(
        location=(r['latitude'], r['longitude']),
        radius=2,
        color=get_color(r['close_collisions'], quartiles),
        tooltip=f"Bike Station {int(r['id'])}:  {int(r['close_collisions'])} collisions within {close_distance}m",
        fill=True).add_to(feature_group), axis=1)
    feature_group.add_to(geo_map)

    LayerControl(collapsed=False).add_to(geo_map)
    geo_map.save('templates/map.html')
Beispiel #2
0
def from_ip_to_geo(filename):

    reader = geoip2.database.Reader(
        'C://Users//mmmel//Desktop//GeoLite2-City_20201229//GeoLite2-City.mmdb'
    )

    dict_from_csv = from_csv_to_dict(filename)

    respose = reader.city('82.61.121.164')

    map = folium.Map(
        location=[respose.location.latitude, respose.location.longitude],
        zoom_start=4)

    inbound_node = FeatureGroup(name="inbound")

    outbound_node = FeatureGroup(name="outbound")

    for key, value in dict_from_csv.items():

        respose = reader.city(key)

        pprint(respose.city)

        pprint(respose.location.latitude)

        pprint(respose.location.longitude)

        for i in range(1):

            if value[i][3] is False:

                folium.Marker(
                    location=[
                        respose.location.latitude, respose.location.longitude
                    ],
                    popup=respose.subdivisions.most_specific.name,
                    icon=folium.Icon(color="red")).add_to(outbound_node)

            else:

                folium.Marker(
                    location=[
                        respose.location.latitude, respose.location.longitude
                    ],
                    popup=respose.subdivisions.most_specific.name,
                    icon=folium.Icon(color="blue")).add_to(inbound_node)

    inbound_node.add_to(map)

    outbound_node.add_to(map)

    LayerControl().add_to(map)

    map.save('C://Users//mmmel//Desktop//index.html')

    webbrowser.open('C://Users//mmmel//Desktop//index.html')
Beispiel #3
0
        def map_multiple_outputs_points(directory: str, map_center=None, save_path=None):
            """
            Creates a folium map of single or multiple outputs from the LP model. Circle markers communicate both location of
            station and forecast demand (diameter).
            Good for outputs from LP model that outputs points - not hexes.
            """
            station_locations = open_station_locations()
            if not map_center:
                m_lat = station_locations[:1]['latitude']
                m_long = station_locations[:1]['longitude']

            else:
                m_lat = map_center[0]
                m_long = map_center[1]

            m = Map(
                location=[m_lat, m_long],
                tiles='cartodbpositron',
                zoom_start=9
            )

            colors = ['blue', 'crimson', 'violet', 'orange', 'yellow', 'black']
            cnt = 0

            for file in os.listdir(directory):
                open_path_1 = f'data/GIS/LP_outputs/{file}'
                print(file)
                name = file.rstrip('.csv')
                proposed_stations_1 = open_lp_proposed_stations(lp_proposed_stations_path=open_path_1)
                proposed_stations_1.set_index('id', inplace=True)
                proposed_stations_1 = join_dfs(station_locations, proposed_stations_1)

                feature_group = FeatureGroup(name=name)
                for i, row in proposed_stations_1.iterrows():
                    if row['demand'] == 0:
                        pass
                    else:
                        c = CircleMarker(
                            radius=row['demand'],
                            location=[row["latitude"], row["longitude"]],
                            tooltip=f"Station ID: {row.name} \n Demand: {row['demand']} kWh",
                            color=colors[cnt],
                            fill=True,
                            fill_color=colors[cnt]
                        )
                        c.add_to(feature_group)
                feature_group.add_to(m)
                cnt += 1

            LayerControl('bottomright', collapsed=False).add_to(m)
            if save_path:
                m.save(save_path)

            return m
    def draw_refuse_routes_map(self, refuse_routes_file_path: string = 'resource/data/Hav_Refuse_Routes_WGS84'
                                                                       '/Hav_Refuse_Routes_WGS84.json'):
        geo_map = Map(location=[42.795390191429625, -71.07516023514027], zoom_start=12)
        data = self.preprocess.get_refuse_routes_data(refuse_routes_file_path)
        keys_pool = [
            'MONDAY - Red Week',
            'TUESDAY - Red Week',
            'WEDNESDAY - Red Week',
            'THURSDAY - Red Week',
            'FRIDAY - Red Week',
            'MONDAY - Blue Week',
            'TUESDAY - Blue Week',
            'WEDNESDAY - Blue Week',
            'THURSDAY - Blue Week',
            'FRIDAY - Blue Week',
            'MERCANTILE - Every Friday'
        ]

        for key in keys_pool:
            feature_group = FeatureGroup(name=key, show=True)
            if key.endswith('Red Week'):
                color = 'red'
            elif key.endswith('Blue Week'):
                color = 'blue'
            else:
                color = 'black'
            for each in data[key]:
                geo_json = GeoJson(
                    data=each,
                    style_function=lambda feature, color=color: {
                        'fillColor': '#A9A9A9',
                        'color': color,
                        'weight': 3,
                    },
                    highlight_function=lambda feature, color=color: {
                        'fillColor': '#FFBFFF',
                        'color': color,
                        'weight': 4,
                    },
                    tooltip=key,
                    overlay=True
                )
                geo_json.add_to(feature_group)
            feature_group.add_to(geo_map)
        LayerControl().add_to(geo_map)

        cur_time = time.strftime('%m_%d_%Y_%H_%M_%S', time.localtime())
        file_name = 'refuse_routes_{}.html'.format(cur_time)

        geo_map.save(os.path.join(self.refuse_routes_directory_path, file_name))
    def draw_heat_map(geo_map: Map, requests: dict):
        show = True
        requests_list = sorted(requests.items(), key=lambda item: item[0])
        for request_type in requests_list:
            if show:
                feature_group = FeatureGroup(name=request_type[0], show=True)
                show = False
            else:
                feature_group = FeatureGroup(name=request_type[0], show=False)
            mc = MarkerCluster()
            for request in request_type[1]:
                # print(request[2])
                popup_info = 'Request Type: \n' + request[3] + '\nAddress: ' + request[2]
                mc.add_child(Marker(location=[request[0], request[1]], popup=popup_info))
            mc.add_to(feature_group)
            feature_group.add_to(geo_map)

        LayerControl().add_to(geo_map)
Beispiel #6
0
def mapper_area(df, geo_json_data, a, units):
    # Initialize the map
    m = folium.Map()

    # Scale the size of the circles
    scale = {0: 4, 1: 10, 2: 16, 3: 24, 4: 32}
    default_radius = 10
    # Add a clickable marker for each facility
    cm_map = FeatureGroup(name="Facilities")
    for index, row in df.iterrows():
        try:
            quantile = row["quantile"]
            folium.CircleMarker(
                location=[row["FAC_LAT"], row["FAC_LONG"]],
                popup=row["FAC_NAME"] + ": " + formatter(int(row[a])) + " " +
                units + "<p><a href='" + row["DFR_URL"] +
                "' target='_blank'>Link to ECHO detailed report</a></p>",  # + "<p><a href='"+row["DFR_URL"]+"' target='_blank'>Link to ECHO detailed report</a></p>",
                radius=default_radius if
                (np.isnan(quantile)) else scale[quantile],
                color="black",
                weight=1,
                fill_color="orange" if (int(row[a]) > 0) else "grey",
                fill_opacity=.4,
                tooltip=row["FAC_NAME"] + ": " + formatter(int(row[a])) + " " +
                units + "").add_to(cm_map)
        except KeyError:
            breakpoint()
    #folium.GeoJsonTooltip(fields=["District"]).add_to(gj)
    cm_map.add_to(m)

    gj = folium.GeoJson(
        geo_json_data,
        name="Congressional District",
    )
    gj.add_to(m)

    m.keep_in_front(cm_map)
    bounds = m.get_bounds()
    m.fit_bounds(bounds)

    folium.LayerControl().add_to(m)

    return m
Beispiel #7
0
def restaurantmap(df_yelp, df_citycoor):
    latitude = 39.0902
    longitude = -95.7129
    yelp_map = folium.Map(location=[latitude, longitude], zoom_start=4)

    for restaurant in [
            "McDonald's", 'Starbucks', 'Subway', 'Taco Bell', 'Chick-fil-A',
            'Burger King', "Wendy's", "Dunkin'", "Domino's Pizza",
            'Panera Bread', 'Pizza Hut', 'Chipotle Mexican Grill',
            'Sonic Drive-In', 'KFC', "Applebee's Grill + Bar",
            'Olive Garden Italian Restaurant', "Arby's", 'Little Caesars',
            'Buffalo Wild Wings', 'Dairy Queen'
    ]:
        restaurcnt = df_yelp[df_yelp['name'] == restaurant].groupby(
            'city').size().reset_index()
        restaurcnt.rename(index=str, columns={0: "count"}, inplace=True)
        colordict = {0: 'lightblue', 1: 'lightgreen', 2: 'orange', 3: 'red'}
        feature_group = FeatureGroup(name=restaurant, show=False)
        #find cities in citycoor dataframe and add the latitude and longitude to restaurcnt
        restaurcnt = pd.merge(restaurcnt,
                              df_citycoor,
                              left_on='city',
                              right_on='City',
                              how='left')
        for lat, lon, count, city in zip(restaurcnt['latitude'],
                                         restaurcnt['longitude'],
                                         restaurcnt['count'],
                                         restaurcnt['city']):
            folium.CircleMarker(
                [lat, lon],
                radius=.4 * count,
                popup=('City: ' + str(city).capitalize() + '<br>'
                       'Count of restaurant: ' + str(count) + '<br>'),
                color='b',
                key_on=count,
                threshold_scale=[0, 1, 2, 3],
                #fill_color=colordict[],
                fill=True,
                fill_opacity=0.7).add_to(feature_group)
        feature_group.add_to(yelp_map)

    folium.LayerControl(collapsed=False).add_to(yelp_map)
    return yelp_map
Beispiel #8
0
def plotNodeFeature(G, dfNdAttribs, ndAttrib, myMap, colourmap=None):
    feature = FeatureGroup(name=ndAttrib.value, show=False)

    if colourmap == None:
        minVal = dfNdAttribs[ndAttrib.name].min()
        maxVal = dfNdAttribs[ndAttrib.name].max()
        colourmap = cm.linear.Reds_09.scale(minVal, maxVal)
        colourmap.caption = ndAttrib.value

    # sorts nodes by value so that nodes with larger values plot later
    # this ensures that circles with darker colour (larger value) always on top thus more visible.
    dfNdAttribs = dfNdAttribs.sort_values(by=[ndAttrib.name])

    for idx, row in dfNdAttribs.iterrows():
        node = row[const.GNodeAttribs.StationId.name]
        deg = row[ndAttrib.name]
        coordCrnStn = [
            row[const.GNodeAttribs.Lat.name], row[const.GNodeAttribs.Lng.name]
        ]

        html = """<html> {ndAttrib} {val} </html><br>
                StationId {stnid}<br>
                {ndDesc}
                """.format(
            ndAttrib=ndAttrib.value,
            val=float("{:.3f}".format(deg)),
            stnid=G.nodes[node][const.GNodeAttribs.StationId.name],
            ndDesc=G.nodes[node][const.GNodeAttribs.StationDesc.name])

        folium.CircleMarker(location=coordCrnStn,
                            radius=5,
                            color=colourmap(deg),
                            weight=2,
                            opacity=0.5,
                            fill_color=colourmap(deg),
                            fill_opacity=.7,
                            tooltip=html).add_to(feature)

    myMap.add_child(colourmap)
    feature.add_to(myMap)
    return myMap
Beispiel #9
0
def create_map(result):

    row = next(result.iterrows())[1]

    m = Map(location=[row.latitude, row.longitude],
            zoom_start=13,
            tiles='Stamen Terrain')

    feature_group = FeatureGroup(name='Some icons')

    for index, row in result.iterrows():
        x = "not planned"
        if str(row.openHouse) != "nan":
            x = datetime.datetime.strptime(row.openHouse,
                                           "%Y-%m-%dT%H:%M:%S.000z")
            x = x.strftime('%b %d %Y %H:%M:%S')
        Marker(location=[row.latitude, row.longitude],
                      icon=DivIcon(
                          icon_size=(150,36),
                          icon_anchor=(7,20),
                          html = '<strong style="text-shadow:-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000,1px 1px 0 #000;">'+
                          '<font size="4" color="'+row['color']+'">'+str(round(row['milprice'],2))+'</>'
                      ),
                      popup=f"<h4>{row.street}</> <br> "+
                           f"<h4> Size: {str(row['size'])} m<sup>2</sup> </> <br> "+
                           f"<h4> Rooms: {str(int(row.rooms))} </> <br> "+
                           f"<h4> Floor: {str(row.floor)}</> <br> "+
                           f"<h4> Expense: {str(row.expense)}</> <br> "+
                           f"<h4> Change: -{str(row.priceChangePercentTotal)}% </> <br> "+
                           f"<a class='btn-floating btn-large waves-effect waves-light red'"+
                           f"href='add/{row.guid}'>"+
                           "<i class='material-icons'>add</i></a> <br>"+
                           f"<h4> Open House: {x} </> <br> "+
                           f"<a href='{row.url}' target='_blank'>link</a>"

              )\
                      .add_to(feature_group)

    feature_group.add_to(m)
    LayerControl().add_to(m)
    m.save(map_file)
Beispiel #10
0
def add_layer(dataset, layername, mapname, color):
    """Plots predictions on a Leaflet map

    Creates a FeatureGroup to hold all of the points.
    FeatureGroup is added to the map as a layer.

    Args:
        dataset: a dataframe with the data to be plotted
        modelname: name of the model to be used as the layer name
        mapname: name of the map to be plotted on
        color: color used for the points in the layer

    Returns:
        a layer of points added to the map
    """
    feature_group = FeatureGroup(name=layername)
    for point in dataset['geometry']:
        CircleMarker(location=[point.y, point.x],
                     radius=4,
                     color=color,
                     fill_color=color).add_to(feature_group)

    feature_group.add_to(mapname)
Beispiel #11
0
def test_unit():

    feature_group = FeatureGroup(name='Teltonika')

    m = Map(
        location=[25.09841, 55.16275],
        zoom_start=2,
        tiles=
        'https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoidGFsazJ0cGMiLCJhIjoiY2ptenozdm0yMWlyNTNwcGhwbzc3dG9rNCJ9.NzVTxRk8eVz6g_BrbjonWg',
        attr='Mapbox')

    Marker(location=[25.09955, 55.16263],
           popup='Mt. Hood Meadows',
           icon=Icon(icon='dashboard')).add_to(feature_group)

    Marker(location=[25.10124, 55.16332],
           popup='Timberline Lodge',
           icon=Icon(color='green')).add_to(feature_group)

    Marker(location=[25.10255, 55.16545],
           popup='''<p>Asset Name: Teltonika</p>
<p><img src="https://html-online.com/editor/tinymce4_6_5/plugins/emoticons/img/smiley-cool.gif" alt="cool" /></p>
<p>Speed: <span style="color: #ff0000;">12 km/hr</span></p>
<p>&nbsp;</p>
<p>&nbsp;</p>''',
           icon=Icon(color='red', icon='screenshot')).add_to(feature_group)

    m.add_child(LatLngPopup())

    feature_group.add_to(m)

    LayerControl().add_to(m)

    m.add_child(MeasureControl())

    m.save('osm.html')
Beispiel #12
0
    def submit(self):

        city = str(self.ui.comboCity.currentText())
        month = str(self.ui.comboMonth.currentText())
        day = str(self.ui.comboDay.currentText())
        city1, month1 = get_filters(city, month)
        global df, df5, df6, gender_mean, female_mean, male_mean, user_subs, user_cust, user
        global ut_subs, ut_cust, ut_subs_fem, ut_subs_male, ut_cust_fem, ut_cust_male
        df, df5 = load_data(city1, month1, day)

        try:
            now = datetime.datetime.now()
            df['age'] = now.year - df['Birth Year']
        except:
            df['age'] = 0
            pass
        try:
            female_mean = df[df['Gender'] == 'Female'].groupby(
                'Start Station').mean()
            female_mean['count'] = df[df['Gender'] == 'Female'].groupby(
                'Start Station')['Id'].count()
            female_mean.drop(columns=[
                'latitude_start', 'longitude_start', 'latitude_end',
                'longitude_end'
            ],
                             inplace=True)
            male_mean = df[df['Gender'] == 'Male'].groupby(
                'Start Station').mean()
            male_mean['count'] = df[df['Gender'] == 'Male'].groupby(
                'Start Station')['Id'].count()
            gender_mean = male_mean.merge(female_mean,
                                          how='outer',
                                          left_index=True,
                                          right_index=True,
                                          suffixes=(' male', ' female'))
            gender_mean['count total'] = gender_mean[
                'count female'] + gender_mean['count male']
            gender_mean['female percent'] = (gender_mean['count female'] /
                                             gender_mean['count total']) * 100
        except:
            pass

        try:
            user_subs = df[df['User Type'] == 'Subscriber'].groupby(
                'Start Station').mean()
            user_subs['count'] = df[df['User Type'] == 'Subscriber'].groupby(
                'Start Station')['Id'].count()
            user_cust = df[df['User Type'] == 'Customer'].groupby(
                'Start Station').mean()
            user_cust['count'] = df[df['User Type'] == 'Customer'].groupby(
                'Start Station')['Id'].count()

            user_cust.drop(columns=[
                'latitude_start', 'longitude_start', 'latitude_end',
                'longitude_end'
            ],
                           inplace=True)
            user = user_subs.merge(user_cust,
                                   how='outer',
                                   left_index=True,
                                   right_index=True,
                                   suffixes=(' subs', ' cust'))
            user.dropna(subset=['latitude_start'], inplace=True)
            user['count subs'] = user['count subs'].fillna(0)
            user['count cust'] = user['count cust'].fillna(0)
            user['count total'] = user['count subs'] + user['count cust']
            user['subs percent'] = (user['count subs'] /
                                    user['count total']) * 100
        except:
            pass

        # Statistics
        commonMonth, commonDay, commonHour = time_stats(df, city1, month1, day)
        commonStartStation, commonEndStation, G, route, dataFr, distRec = station_stats(
            df)
        ttt, ttm = trip_duration_stats(df)
        ut_subs, ut_cust, ut_subs_fem, ut_subs_male, ut_cust_fem, ut_cust_male = user_stats(
            df)
        df6 = dfStats(df, df5, dataFr)

        tstat = []
        tstat.append('Statistics on the most frequent times of travel')
        tstat.append('The Most Common Month : ' + str(commonMonth))
        tstat.append('The Most Common Day : ' + str(commonDay))
        tstat.append('The Most Common Hour : ' + str(commonHour))

        tstat.append('\nStatistics on the most popular stations and trip')
        tstat.append('The Most Common Used Start Station : ' +
                     str(commonStartStation))
        tstat.append('The Most Common Used End Station : ' +
                     str(commonEndStation))

        tstat.append('\nStatistics on the most popular combination stations')
        tstat.append('The Most Common Combination of Start-End Station : ' +
                     str(dataFr['Start Station'].iloc[0]) + ' and ' +
                     str(dataFr['End Station'].iloc[0]))
        tstat.append(
            'The Most Common Combination of Start-End Station Track (km): ' +
            str(distRec[0]))
        tstat.append(
            'The Most Common Combination of Start-End Station Lineal Distance (km): '
            + str(dataFr['Dist_lin_km'].iloc[0]))

        tstat.append('\nStatistics on the total and average trip duration')
        tstat.append('The total travel time : ' + str(ttt))
        tstat.append('The mean travel time : ' + str(ttm))

        tstat.append('\nDisplays statistics on bikeshare users and gender')
        tstat.append('The counts of user types "Subscriber" : ' +
                     str(len(ut_subs)))
        tstat.append('The counts of user types "Customer" : ' +
                     str(len(ut_cust)))
        try:
            tstat.append(
                'The counts of user types "Subscriber" and Gender "Female": ' +
                str(len(ut_subs_fem)))
            tstat.append(
                'The counts of user types "Subscriber" and Gender "Male": ' +
                str(len(ut_subs_male)))
            tstat.append(
                'The counts of user types "Customer" and Gender "Female": ' +
                str(len(ut_cust_fem)))
            tstat.append(
                'The counts of user types "Customer" and Gender "Male": ' +
                str(len(ut_cust_male)))
        except:
            pass
        try:
            tstat.append(
                '\nDisplay earliest, most recent, and most common year of birth'
            )
            tstat.append('The earliest year of birt: ' +
                         str(int(df['Birth Year'].min())))
            tstat.append('The most recent year of birt: ' +
                         str(int(df['Birth Year'].max())))
            tstat.append('The most common year of birt: ' +
                         str(int(df['Birth Year'].mode())))
        except:
            pass

        self.ui.textEdit.setText("\n".join(tstat))

        # Route Map
        graph_map = ox.plot_graph_folium(G,
                                         popup_attribute='name',
                                         edge_width=2,
                                         edge_color="#85d3de",
                                         zoom=8)
        try:
            route_graph_map = ox.plot_route_folium(G,
                                                   route,
                                                   route_map=graph_map,
                                                   popup_attribute='length',
                                                   zoom=8)
        except:
            route_graph_map = graph_map

        locations = df6[['latitude', 'longitude']]
        locationlist = locations.values.tolist()
        for point in range(0, len(df6)):
            Marker(locationlist[point],
                   popup=df6[['Station', 'name'
                              ]].iloc[point].values).add_to(route_graph_map)
        filepath = 'CommonStation_ShortestPath.html'
        route_graph_map.save(filepath)
        w = self.ui.webEngineView_1
        w.resize(740, 540)
        self.url = QtCore.QUrl.fromLocalFile(str(pathname) + '/' + filepath)
        w.load(self.url)
        w.show()

        ##Bike Stations
        maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                   zoom_start=10,
                   control_scale=True,
                   tiles="OpenStreetMap")
        locations2 = df5[['latitude', 'longitude']]
        locationlist2 = locations2.values.tolist()
        group2 = FeatureGroup(name="Bike Stations")
        for point in range(0, len(locationlist2)):
            Marker(locationlist2[point],
                   popup=df5[['Station', 'latitude',
                              'longitude']].iloc[point].values).add_to(group2)
        group2.add_to(maps)
        LayerControl().add_to(maps)
        data = io.BytesIO()
        maps.save(data, close_file=False)
        m = self.ui.webEngineView_2
        m.setHtml(data.getvalue().decode())
        m.resize(740, 540)
        maps.save("BikeStations.html")
        m.show()
        maps.save(data, close_file=True)

        # initial map tab
        maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                   zoom_start=10,
                   control_scale=True,
                   tiles="OpenStreetMap")
        LayerControl().add_to(maps)
        data = io.BytesIO()
        maps.save(data, close_file=False)
        m = self.ui.webEngineView_3
        m.setHtml(data.getvalue().decode())
        m.resize(740, 520)
        m.show()
        maps.save(data, close_file=True)

        try:
            # initial Graphics
            self.figure.clear()
            labels = 'Male', 'Female'
            sizes = [
                len(df[df['Gender'] == 'Male']),
                len(df[df['Gender'] == 'Female'])
            ]
            explode = (0, 0.1)
            ax1 = self.figure.add_subplot(111)
            ax1.pie(sizes,
                    explode=explode,
                    labels=labels,
                    autopct='%1.1f%%',
                    startangle=90)
            ax1.axis('equal')
            self.canvas.draw()
            self.show
        except:
            pass

        # setting value to progress bar
        for i in range(101):
            time.sleep(0.04)
            self.ui.progressBar.setValue(i)
Beispiel #13
0
    def Clicked_2(self):
        def percent(data, percent=None):
            index = []
            for i in percent:
                index.append(data.quantile(i))
            return index

        global df, df5, df6, gender_mean, female_mean, male_mean, user_subs, user_cust, user
        global ut_subs, ut_cust, ut_subs_fem, ut_subs_male, ut_cust_fem, ut_cust_male
        radioBtn = self.sender()
        if radioBtn.isChecked():
            if radioBtn.text() == 'Trip Duration':
                ##Average Trip Duration map
                maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                           zoom_start=10,
                           control_scale=True,
                           tiles="OpenStreetMap")
                try:
                    locations3a = df[[
                        'latitude_start', 'longitude_start', 'Trip Duration',
                        'Start Station', 'age'
                    ]].copy()
                    locations3 = locations3a.groupby('Start Station').mean()
                    locations3.dropna(subset=['Trip Duration'], inplace=True)
                    index = percent(locations3['Trip Duration'],
                                    percent=[0.01, 0.40, 0.75, 0.85, 0.98])
                    colormap = cm.LinearColormap(
                        colors=['blue', 'cyan', 'yellow', 'orange', 'red'],
                        vmin=locations3['Trip Duration'].quantile(0.01),
                        vmax=locations3['Trip Duration'].quantile(0.98),
                        caption='Average Trip Duration (m.)',
                        index=index)
                    locationlist3 = locations3.values.tolist()
                    group3 = FeatureGroup(name="Trip Duration")
                    for i in range(0, len(locationlist3)):
                        Circle(location=locationlist3[i][0:2],
                               radius=150,
                               fill=True,
                               color=colormap(locationlist3[i][2]),
                               popup=locations3[['Trip Duration', 'age'
                                                 ]].iloc[i]).add_to(group3)
                    group3.add_to(maps)
                    colormap.add_to(maps)
                except:
                    pass
                LayerControl().add_to(maps)
                data = io.BytesIO()
                maps.save(data, close_file=False)
                m = self.ui.webEngineView_3
                m.setHtml(data.getvalue().decode())
                m.resize(740, 520)
                maps.save("TripDuration.html")
                m.show()
                maps.save(data, close_file=True)

            # Gender map
            if radioBtn.text() == 'Gender Map':
                ##female percent
                maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                           zoom_start=10,
                           control_scale=True,
                           tiles="OpenStreetMap")
                try:
                    gm = gender_mean.dropna(subset=['count total'])
                    index = percent(gm['female percent'],
                                    percent=[0.01, 0.25, 0.60, 0.85, 0.99])
                    colormap = cm.LinearColormap(
                        colors=['blue', 'cyan', 'yellow', 'orange', 'red'],
                        vmin=gm['female percent'].quantile(0.01),
                        vmax=gm['female percent'].quantile(0.99),
                        caption='Female Percent',
                        index=index)
                    locationlist4 = gm[[
                        'latitude_start', 'longitude_start', 'female percent'
                    ]].values.tolist()
                    group4 = FeatureGroup(name="Female Percent")
                    pop = gm[[
                        'Trip Duration female', 'age female', 'count female',
                        'female percent'
                    ]]
                    for i in range(0, len(locationlist4)):
                        Circle(location=locationlist4[i][0:2],
                               radius=150,
                               fill=True,
                               color=colormap(locationlist4[i][2]),
                               popup=pop.iloc[i]).add_to(group4)

                    group4.add_to(maps)
                    colormap.add_to(maps)
                except:
                    pass
                LayerControl().add_to(maps)
                data = io.BytesIO()
                maps.save(data, close_file=False)
                m = self.ui.webEngineView_3
                m.setHtml(data.getvalue().decode())
                m.resize(740, 520)
                maps.save("FemalePercent.html")
                m.show()
                maps.save(data, close_file=True)

            ## age map
            if radioBtn.text() == 'Age Map':
                maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                           zoom_start=10,
                           control_scale=True,
                           tiles="OpenStreetMap")
                try:
                    age = df.groupby('Start Station').mean()
                    age.dropna(subset=['age'], inplace=True)
                    index = percent(age['age'],
                                    percent=[0.01, 0.25, 0.50, 0.75, 0.99])
                    colormap = cm.LinearColormap(
                        colors=['blue', 'cyan', 'yellow', 'orange', 'red'],
                        vmin=age['age'].quantile(0.01),
                        vmax=age['age'].quantile(0.99),
                        caption='Age Average',
                        index=index)
                    locationlist5 = age[[
                        'latitude_start', 'longitude_start', 'age'
                    ]].values.tolist()
                    group5 = FeatureGroup(name="Age Average")
                    pop = gender_mean[[
                        'age male', 'count male', 'age female', 'count female'
                    ]]
                    for i in range(0, len(locationlist5)):
                        Circle(location=locationlist5[i][0:2],
                               radius=150,
                               fill=True,
                               color=colormap(locationlist5[i][2]),
                               popup=pop.iloc[i]).add_to(group5)

                    group5.add_to(maps)
                    colormap.add_to(maps)
                except:
                    pass
                LayerControl().add_to(maps)
                data = io.BytesIO()
                maps.save(data, close_file=False)
                m = self.ui.webEngineView_3
                m.setHtml(data.getvalue().decode())
                m.resize(740, 520)
                maps.save("AgeAverage.html")
                m.show()
                maps.save(data, close_file=True)

            ## Trip Count
            if radioBtn.text() == 'Trip Count':
                maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                           zoom_start=10,
                           control_scale=True,
                           tiles="OpenStreetMap")

                count = df.groupby('Start Station').mean()
                count['count'] = df.groupby(
                    'Start Station')['Trip Duration'].count()
                count.dropna(subset=['count'], inplace=True)
                index = percent(count['count'],
                                percent=[0.05, 0.40, 0.75, 0.95])
                colormap = cm.LinearColormap(
                    colors=['blue', 'cyan', 'yellow', 'orange', 'red'],
                    vmin=count['count'].quantile(0.05),
                    vmax=count['count'].quantile(0.95),
                    caption='Trip Count Start Station',
                    index=index)
                locationlist6 = count[[
                    'latitude_start', 'longitude_start', 'count'
                ]].values.tolist()
                group6 = FeatureGroup(name="Trip Count")
                pop = count[['Trip Duration', 'count', 'age']]
                for i in range(0, len(locationlist6)):
                    Circle(location=locationlist6[i][0:2],
                           radius=150,
                           fill=True,
                           color=colormap(locationlist6[i][2]),
                           popup=pop.iloc[i]).add_to(group6)
                group6.add_to(maps)
                colormap.add_to(maps)
                LayerControl().add_to(maps)
                data = io.BytesIO()
                maps.save(data, close_file=False)
                m = self.ui.webEngineView_3
                m.setHtml(data.getvalue().decode())
                m.resize(740, 520)
                maps.save("TripCount.html")
                m.show()
                maps.save(data, close_file=True)

            ## User Type
            if radioBtn.text() == 'User Type':
                maps = Map([df5['latitude'].mean(), df5['longitude'].mean()],
                           zoom_start=10,
                           control_scale=True,
                           tiles="OpenStreetMap")
                index = percent(user['subs percent'],
                                percent=[0.01, 0.10, 0.40, 0.70, 0.95])
                colormap = cm.LinearColormap(
                    colors=['blue', 'cyan', 'yellow', 'orange', 'red'],
                    vmin=user['subs percent'].quantile(0.01),
                    vmax=user['subs percent'].quantile(0.95),
                    caption='User Type: Subscriber (Percent)',
                    index=index)

                locationlist7 = user[[
                    'latitude_start', 'longitude_start', 'subs percent'
                ]].values.tolist()
                group7 = FeatureGroup(name="User Type")
                pop = user[['count subs', 'count cust', 'subs percent']]
                for i in range(0, len(locationlist7)):
                    Circle(location=locationlist7[i][0:2],
                           radius=150,
                           fill=True,
                           color=colormap(locationlist7[i][2]),
                           popup=pop.iloc[i]).add_to(group7)
                group7.add_to(maps)
                colormap.add_to(maps)
                LayerControl().add_to(maps)
                data = io.BytesIO()
                maps.save(data, close_file=False)
                m = self.ui.webEngineView_3
                m.setHtml(data.getvalue().decode())
                m.resize(740, 520)
                maps.save("UserType.html")
                m.show()
                maps.save(data, close_file=True)
Beispiel #14
0
    def map_html(self, tiltakspunkter, filepath):
        """
        tiltakspunkter er av typen Point og oppgitt i epsg:4326
        filepath er der du ønsker .html filen med kart skal havne.
        """

        tiltakspunkter = tiltakspunkter

        box_tmp = bounding_box(tiltakspunkter)
        box_center_x = (box_tmp[0] + box_tmp[2]) / 2
        box_center_y = (box_tmp[1] + box_tmp[3]) / 2

        map_center_lon = box_center_x
        map_center_lat = box_center_y

        map = folium.Map(location=[map_center_lat, map_center_lon],
                         zoom_start=9,
                         tiles='Stamen Terrain')

        tiltaksFeature = FeatureGroup(name='Tiltakspunkter', show=False)

        marker_cluster = plugins.MarkerCluster(options=dict(
            zoomToBoundsOnClick=False)).add_to(tiltaksFeature)

        #feature_tiltak = FeatureGroup(name='tiltakspunkter')
        tooltip_tiltak = 'Tiltakspunkt'

        tmp_tiltak = tiltakspunkter['punkt_geom_wkt']
        x_list = tmp_tiltak.apply(lambda p: p.x)
        y_list = tmp_tiltak.apply(lambda p: p.y)
        for i in range(0, len(x_list)):
            try:
                Marker(location=[y_list[i], x_list[i]],
                       popup=tiltakspunkter['punkt_navn'][i],
                       icon=folium.Icon(color='red',
                                        icon_color='black',
                                        icon='angle-double-down',
                                        prefix='fa'),
                       tooltip=tooltip_tiltak).add_to(marker_cluster)
            except:
                Marker(location=[y_list[i], x_list[i]],
                       popup='Atter et punkt',
                       icon=folium.Icon(color='red',
                                        icon_color='black',
                                        icon='angle-double-down',
                                        prefix='fa'),
                       tooltip=tooltip_tiltak).add_to(marker_cluster)

        feature_skipshaler = FeatureGroup(name='skipshaler')

        try:
            oljetankskip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'oljetankskip')

            haler_feat_10 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 10]
            skipshaler_10_json = haler_feat_10.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#4DB6AC',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_olje = folium.features.GeoJson(
                skipshaler_10_json, style_function=style_skipshaler)
            haler_olje.add_to(oljetankskip)
        except:
            pass

        try:
            kjemikalie_produkttankskip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'kjemikalie_produkttankskip')

            haler_feat_11 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 11]
            skipshaler_11_json = haler_feat_11.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#26A69A',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_kjemi = folium.features.GeoJson(
                skipshaler_11_json, style_function=style_skipshaler)
            haler_kjemi.add_to(kjemikalie_produkttankskip)
        except:
            pass

        try:
            gasstankskip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'gasstankskip')

            haler_feat_12 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 12]
            skipshaler_12_json = haler_feat_12.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#009688',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_gass = folium.features.GeoJson(
                skipshaler_12_json, style_function=style_skipshaler)
            haler_gass.add_to(gasstankskip)
        except:
            pass

        try:
            bulkskip = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                    'bulkskip')

            haler_feat_13 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 13]
            skipshaler_13_json = haler_feat_13.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#00897B',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_bulk = folium.features.GeoJson(
                skipshaler_13_json, style_function=style_skipshaler)
            haler_bulk.add_to(bulkskip)
        except:
            pass

        try:
            stykkgods_roro_skip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'stykkgods_roro_skip')

            haler_feat_14 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 14]
            skipshaler_14_json = haler_feat_14.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#00796B',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_stykkgods = folium.features.GeoJson(
                skipshaler_14_json, style_function=style_skipshaler)
            haler_stykkgods.add_to(stykkgods_roro_skip)
        except:
            pass

        try:
            konteinerskip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'konteinerskip')

            haler_feat_15 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 15]
            skipshaler_15_json = haler_feat_15.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#00695C',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_konteiner = folium.features.GeoJson(
                skipshaler_15_json, style_function=style_skipshaler)
            haler_konteiner.add_to(konteinerskip)
        except:
            pass

        try:
            passasjerbat = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'passasjerbat')

            haler_feat_16 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 16]
            skipshaler_16_json = haler_feat_16.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#81C784',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_passasjer = folium.features.GeoJson(
                skipshaler_16_json, style_function=style_skipshaler)
            haler_passasjer.add_to(passasjerbat)
        except:
            pass

        try:
            ropax_skip = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                      'ropax_skip')

            haler_feat_17 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 17]
            skipshaler_17_json = haler_feat_17.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#66BB6A',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_ropax = folium.features.GeoJson(
                skipshaler_17_json, style_function=style_skipshaler)
            haler_ropax.add_to(ropax_skip)
        except:
            pass

        try:
            cruiseskip = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                      'cruiseskip')

            haler_feat_18 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 18]
            skipshaler_18_json = haler_feat_18.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#4CAF50',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_cruise = folium.features.GeoJson(
                skipshaler_18_json, style_function=style_skipshaler)
            haler_cruise.add_to(cruiseskip)
        except:
            pass

        try:
            offshore_supplyskip = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'offshore_supplyskip')

            haler_feat_19 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 19]
            skipshaler_19_json = haler_feat_19.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#43A047',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_offshore = folium.features.GeoJson(
                skipshaler_19_json, style_function=style_skipshaler)
            haler_offshore.add_to(offshore_supplyskip)
        except:
            pass

        try:
            andre_offshorefartoy = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'andre_offshorefartoy')

            haler_feat_20 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 20]
            skipshaler_20_json = haler_feat_20.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#388E3C',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_andre_offshore = folium.features.GeoJson(
                skipshaler_20_json, style_function=style_skipshaler)
            haler_andre_offshore.add_to(andre_offshorefartoy)
        except:
            pass

        try:
            bronnbat = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                    'bronnbat')

            haler_feat_21 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 21]
            skipshaler_21_json = haler_feat_21.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#00E676',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_bronn = folium.features.GeoJson(
                skipshaler_21_json, style_function=style_skipshaler)
            haler_bronn.add_to(bronnbat)
        except:
            pass

        try:
            slepefartoy = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                       'slepefartoy')

            haler_feat_22 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 22]
            skipshaler_22_json = haler_feat_22.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#00C853',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_slepe = folium.features.GeoJson(
                skipshaler_22_json, style_function=style_skipshaler)
            haler_slepe.add_to(slepefartoy)
        except:
            pass

        try:
            andre_servicefartoy = plugins.FeatureGroupSubGroup(
                feature_skipshaler, 'andre_servicefartoy')

            haler_feat_23 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 23]
            skipshaler_23_json = haler_feat_23.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#9CCC65',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_andre_service = folium.features.GeoJson(
                skipshaler_23_json, style_function=style_skipshaler)
            haler_andre_service.add_to(andre_servicefartoy)
        except:
            pass

        try:
            fiskefartoy = plugins.FeatureGroupSubGroup(feature_skipshaler,
                                                       'fiskefartoy')

            haler_feat_24 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 24]
            skipshaler_24_json = haler_feat_24.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#7CB342',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_fisk = folium.features.GeoJson(
                skipshaler_24_json, style_function=style_skipshaler)
            haler_fisk.add_to(fiskefartoy)
        except:
            pass

        try:
            annet = plugins.FeatureGroupSubGroup(feature_skipshaler, 'annet')

            haler_feat_25 = self.total_populasjon[
                self.total_populasjon.shiptype_nr == 25]
            skipshaler_25_json = haler_feat_25.to_json(default=str)
            style_skipshaler = lambda x: {
                'color': '#558B2F',
                'weight': 3,
                'opacity': 0.1,
            }
            haler_annet = folium.features.GeoJson(
                skipshaler_25_json, style_function=style_skipshaler)
            haler_annet.add_to(annet)
        except:
            pass

        feature_passlines = FeatureGroup(name='passeringslinjer')
        passeringslinje_json = self.passline.to_json(default=str)
        tooltip_passeringslinje = 'Passeringslinje'
        style_passline = lambda x: {
            'color': '#000000',
            'weight': 4,
            'opacity': 1.0,
        }
        folium.features.GeoJson(
            passeringslinje_json,
            style_function=style_passline,
            tooltip=tooltip_passeringslinje).add_to(feature_passlines)

        #feature_tiltak.add_to(marker_cluster)
        marker_cluster.add_to(map)
        feature_passlines.add_to(map)
        feature_skipshaler.add_to(map)
        oljetankskip.add_to(map)
        kjemikalie_produkttankskip.add_to(map)
        gasstankskip.add_to(map)
        bulkskip.add_to(map)
        stykkgods_roro_skip.add_to(map)
        konteinerskip.add_to(map)
        passasjerbat.add_to(map)
        ropax_skip.add_to(map)
        cruiseskip.add_to(map)
        offshore_supplyskip.add_to(map)
        andre_offshorefartoy.add_to(map)
        bronnbat.add_to(map)
        slepefartoy.add_to(map)
        andre_servicefartoy.add_to(map)
        fiskefartoy.add_to(map)
        annet.add_to(map)

        folium.LayerControl(collapsed=False).add_to(map)

        minimap = plugins.MiniMap()

        map.add_child(minimap)
        map.add_child(folium.LatLngPopup())

        map.save(filepath)
Beispiel #15
0
m.add_child(cvd).add_child(blk).add_child(mhi).add_child(unemp).add_child(
    unedu)
# m.add_child(folium.map.LayerControl())

# In[159]:

# plot homicides with popup, dot marker, put into a feature group
# marker_cluster = MarkerCluster(name='Homicide').add_to(m)
hmc_fg = FeatureGroup(name='Homicide', overlay=True, control=False)

for (index, row) in hmc.iterrows():
    folium.CircleMarker(location=[row.loc['Lat'], row.loc['Long']],
                        popup='Date: ' + str(row.loc['occurrence_date']) +
                        ' Type: ' + row.loc['homicide_type'] +
                        ' Neighbourhood: ' + row.loc['Neighbourhood'],
                        radius=2,
                        color='black',
                        tooltip='click').add_to(hmc_fg)

# keep it always on top
m.keep_in_front(hmc_fg)
hmc_fg.add_to(m)
m.add_child(folium.map.LayerControl())

m

# In[160]:

m.save('TOneighbourhood.html')
Beispiel #16
0
            png = outputdir + site_nameinfo + '_' + version + '_' + i + '_windrose.png'

            #Plot average map
            try:
                folium.raster_layers.ImageOverlay(
                    png,
                    bounds=extents,
                    name=site_nameinfo + ' ' + version + ' ' + i,
                    opacity=1,
                    show=True).add_to(feature_group)
                plotted_sites.append(site_nameinfo + '_' + version + '_' + i)
            except FileNotFoundError:
                print('Missing ' + site_nameinfo + ' ' + version + ' ' + i)
                missing_sites.append(site_nameinfo + '_' + version + '_' + i)
                continue
        feature_group.add_to(m)

# Add ability to move between layers
folium.LayerControl().add_to(m)

# Save and show the created map. Use Jupyter to see the map within your console
m.save(inputdir + 'folium_windrose_map.html')
m
# Print how many sites have been plotted
print('Number of plotted sites is ' + str(len(plotted_sites)))
print('Number of missing sites is ' + str(len(missing_sites)))

#%%
'''
# Try to plot them all on one page
df1 = df_airpact
covid_map = folium.Map(
    location=[curr_df['Lat'].mean(), curr_df['Long'].mean()],
    zoom_start=5,
    zoom_control=False,
    max_bounds=True)

# plot heatmap for states
states_feature = FeatureGroup(name="States Heatmap")
folium.GeoJson(geo_json_data,
               style_function=lambda feature: {
                   'fillColor': my_color_function(feature),
                   'color': 'black',
                   'weight': 2,
                   'dashArray': '5, 5'
               }).add_to(states_feature)
states_feature.add_to(covid_map)

# plot cluster for each case in each state

# custom JS function for cluster
icon_create_function = '''
 function (cluster) {
 var childCount = cluster.getChildCount();
 var c = ' marker-cluster-';
 if (childCount < 0) {
   c += 'small';
 } 
 else if (childCount < 0) {
   c += 'medium';
 } 
 else {
Beispiel #18
0
    def show_map(coords: list,
                 web_engine_view: QWebEngineView,
                 pop_up: str = None,
                 university=None,
                 kindergarden=None,
                 schools=None,
                 highschools=None,
                 transport=None,
                 charging=None,
                 bicycle=None,
                 groceries=None,
                 services=None,
                 sports=None):
        icon_size = (45, 45)
        small_icon = (40, 40)
        max_width = 400
        bytes_io = BytesIO()
        map_builder = Map(location=coords,
                          tiles="CartoDB positron",
                          zoom_start=16)
        map_icon = CustomIcon(up(up(__file__)) + "/images/marker.png",
                              icon_size=icon_size)

        if kindergarden:
            kindergarden_cluster = MarkerCluster(
                name='barnehage', show=False).add_to(map_builder)
            for pois in kindergarden:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/kindergarden.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(kindergarden_cluster)

        if schools:
            schools_cluster = MarkerCluster(name="barneskole",
                                            show=False).add_to(map_builder)
            for pois in schools:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/schools.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(schools_cluster)

        if highschools:
            highschools_cluster = MarkerCluster(name='vidregåendeskole',
                                                show=False).add_to(map_builder)
            for pois in highschools:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/highschools.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(highschools_cluster)

        if university:
            university_cluster = MarkerCluster(name='hogskole_universitet',
                                               show=False).add_to(map_builder)
            for pois in university:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/university.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(university_cluster)

        if transport:
            transport_cluster = MarkerCluster(name='holdeplass',
                                              show=False).add_to(map_builder)
            for pois in transport:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/transport.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(transport_cluster)

        if charging:
            charging_cluster = MarkerCluster(name='ladeplass',
                                             show=False).add_to(map_builder)
            for pois in charging:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/charging.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(charging_cluster)

        if bicycle:
            bicyle_cluster = MarkerCluster(name='bysykler',
                                           show=False).add_to(map_builder)
            for pois in bicycle:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/bicycle.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(bicyle_cluster)

        shops_cluster = MarkerCluster(name="butikker",
                                      show=False).add_to(map_builder)

        if groceries:
            for pois in groceries:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/groceries.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(shops_cluster)

        if services:
            for pois in services:
                pois_icon = CustomIcon(up(up(__file__)) +
                                       "/images/services.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(shops_cluster)

        if sports:
            sports_cluster = MarkerCluster(name='sportsaktiviteter',
                                           show=False).add_to(map_builder)
            for pois in sports:
                pois_icon = CustomIcon(up(up(__file__)) + "/images/sports.png",
                                       icon_size=small_icon)
                lat = pois["Breddegrad"]
                long = pois["Lengdegrad"]
                pois_pop_up = Popup(CreateHtmlTable(pois).html_table(),
                                    max_width=max_width)
                Marker(location=[lat, long], icon=pois_icon,
                       popup=pois_pop_up).add_to(sports_cluster)

        if pop_up:
            Marker(coords,
                   icon=map_icon,
                   popup=Popup(pop_up,
                               max_width=max_width)).add_to(map_builder)
        else:
            Marker(coords, icon=map_icon).add_to(map_builder)

        TileLayer('CartoDB dark_matter').add_to(map_builder)

        TileLayer('OpenStreetMap').add_to(map_builder)

        TileLayer(
            'https://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png',
            attr=
            '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> '
            'contributors, Tiles style by <a href="https://www.hotosm.org/" '
            'target="_blank">Humanitarian OpenStreetMap Team</a> hosted by '
            '<a href="https://openstreetmap.fr/" target="_blank">OpenStreetMap '
            'France</a>',
            name='openstreetmap_hot').add_to(map_builder)

        TileLayer('Stamen Toner').add_to(map_builder)

        TileLayer(
            'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/'
            'tile/{z}/{y}/{x}',
            attr='Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, '
            'USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, '
            'UPR-EGP, and the GIS User Community',
            name='esri_worldimagery').add_to(map_builder)

        TileLayer(
            'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/'
            'tile/{z}/{y}/{x}',
            attr='Tiles &copy; Esri &mdash; Source: Esri, DeLorme, '
            'NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, '
            'Esri China (Hong Kong), Esri (Thailand), TomTom, 2012',
            name='esri_worldstreetmap').add_to(map_builder)

        TileLayer(
            'https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/'
            'tile/{z}/{y}/{x}',
            attr='Tiles &copy; Esri &mdash; Esri, DeLorme, NAVTEQ, '
            'TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, '
            'Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri '
            'China (Hong Kong), and the GIS User Community',
            name='esri_worldtopomap').add_to(map_builder)

        TileLayer(
            'https://tileserver.memomaps.de/tilegen/{z}/{x}/{y}.png',
            attr='Map <a href="https://memomaps.de/">memomaps.de</a> '
            '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, '
            'map data &copy; <a href="https://www.openstreetmap.org/copyright">'
            'OpenStreetMap</a> contributors',
            name='openvkarte').add_to(map_builder)

        TileLayer(
            'https://{s}.tile-cyclosm.openstreetmap.fr/cyclosm/{z}/{x}/{y}.png',
            attr=
            '<a href="https://github.com/cyclosm/cyclosm-cartocss-style/releases" '
            'title="CyclOSM - Open Bicycle render">CyclOSM</a> | Map data: &copy; '
            '<a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> '
            'contributors',
            name='cyclosm').add_to(map_builder)

        TileLayer(
            'http://tile.mtbmap.cz/mtbmap_tiles/{z}/{x}/{y}.png',
            attr=
            '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> '
            'contributors &amp; USGS',
            name='mtbmap').add_to(map_builder)

        railway_feature = FeatureGroup('jernbane_tbane', show=False)
        TileLayer(
            'https://{s}.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png',
            attr=
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright'
            '">OpenStreetMap</a> contributors | Map style: &copy; <a href='
            '"https://www.OpenRailwayMap.org">OpenRailwayMap</a> (<a href='
            '"https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
            name='openrailwaymap').add_to(railway_feature)
        railway_feature.add_to(map_builder)

        safecast_feature = FeatureGroup('miljø', show=False)
        TileLayer(
            'https://s3.amazonaws.com/te512.safecast.org/{z}/{x}/{y}.png',
            attr=
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">'
            'OpenStreetMap</a> contributors | Map style: &copy; '
            '<a href="https://blog.safecast.org/about/">SafeCast</a> '
            '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
            name='safecast').add_to(safecast_feature)
        safecast_feature.add_to(map_builder)

        trails_feature = FeatureGroup('turstil', show=False)
        TileLayer(
            'https://tile.waymarkedtrails.org/hiking/{z}/{x}/{y}.png',
            attr=
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">'
            'OpenStreetMap</a> contributors | Map style: &copy; '
            '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> '
            '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
            name='waymarkedtrails_hiking').add_to(trails_feature)
        trails_feature.add_to(map_builder)

        cycling_feature = FeatureGroup('sykkelsti', show=False)
        TileLayer(
            'https://tile.waymarkedtrails.org/cycling/{z}/{x}/{y}.png',
            attr=
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">'
            'OpenStreetMap</a> contributors | Map style: &copy; '
            '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> '
            '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
            name='waymarkedtrails_cycling').add_to(cycling_feature)
        cycling_feature.add_to(map_builder)

        slopes_feature = FeatureGroup('bakker_helning', show=False)
        TileLayer(
            'https://tile.waymarkedtrails.org/slopes/{z}/{x}/{y}.png',
            attr=
            'Map data: &copy; <a href="https://www.openstreetmap.org/copyright">'
            'OpenStreetMap</a> contributors | Map style: &copy; '
            '<a href="https://waymarkedtrails.org">waymarkedtrails.org</a> '
            '(<a href="https://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA</a>)',
            name='waymarkedtrails_slopes').add_to(slopes_feature)
        slopes_feature.add_to(map_builder)

        LayerControl().add_to(map_builder)
        map_builder.save(bytes_io, close_file=False)
        web_engine_view.setHtml(bytes_io.getvalue().decode())
        web_engine_view.show()
Beispiel #19
0
SUMMARY_DAYS_CAMPING = 'days_camping'
SUMMARY_DAYS_CITY = 'days_city'
SUMMARY_MILES = 'miles'
SUMMARY_HOURS = 'hours'
SUMMARY_LONGEST_DAY_MILES = 'longest_day_miles'
SUMMARY_LONGEST_DAY_HOURS = 'longest_day_hours'

### BEGINNING OF FEATURE GROUPS

# A feature group has the following properties:
#  - map overlay of markers, where marker popups have date + description
#  - entry in summary_tables, including date + description

# Route
fg_route = FeatureGroup(name='Route', show=True)
fg_route.add_to(m)

for i, day in enumerate(trip):
    leg = []
    if i == 0 or day.get(DAY_NEW_LEG):
        pass  # do nothing!
    else:
        wake_up_coord = trip[i - 1][DAY_COORD]
        leg.append(wake_up_coord)
    if day.get(DAY_WAYPOINTS):
        leg.extend(day[DAY_WAYPOINTS])
    sleep_coord = day[DAY_COORD]
    leg.append(sleep_coord)

    if len(leg) < 2:
        continue
Beispiel #20
0
SUMMARY_DAYS_CAMPING = 'days_camping'
SUMMARY_DAYS_CITY = 'days_city'
SUMMARY_KMS = 'kilometres'
SUMMARY_HOURS = 'hours'
SUMMARY_LONGEST_DAY_KMS = 'longest_day_kms'
SUMMARY_LONGEST_DAY_HOURS = 'longest_day_hours'

### BEGINNING OF FEATURE GROUPS

# A feature group has the following properties:
#  - map overlay of markers, where marker popups have date + description
#  - entry in summary_tables, including date + description

# Route
fg_route = FeatureGroup(name='Route', show=True)
fg_route.add_to(m)

for i, day in enumerate(trip):
    leg = []
    if i == 0 or day.get(DAY_NEW_LEG):
        pass  # do nothing!
    else:
        wake_up_coord = trip[i - 1][DAY_COORD]
        leg.append(wake_up_coord)
    if day.get(DAY_WAYPOINTS):
        leg.extend(day[DAY_WAYPOINTS])
    sleep_coord = day[DAY_COORD]
    leg.append(sleep_coord)

    if len(leg) < 2:
        continue
Beispiel #21
0
                    height=300,
                    ratio='1%')
    popup = Popup(iframe, max_width=2650)

    html_tooltip = """
    <h4><i>{}</i></h4>
    <p>Click para más información</p>
    """.format

    feature_articulos.add_child(
        Marker([row['Latitud'], row['Longitud ']],
               popup=popup,
               tooltip=html_tooltip(row['Cita']),
               icon=Icon(color='red', icon='info-sign')))

feature_articulos.add_to(hospedero_map)

for especie in df_resumen.Especie.unique():
    temp_df = df_resumen[df_resumen['Especie'] == especie]
    #     show_especie = True if especie == 'Carollia perspicillata' else False
    feature_group = FeatureGroup(especie, show=False)

    html_tooltip = """
    <h4><i>{}</i></h4>
    <h5><b>Cantidad:</b> {}</h5>
    """.format

    temp_df.apply(lambda row: feature_group.add_child(
        CircleMarker([row['Latitud'], row['Longitud']],
                     radius=5 * row['Cantidad'],
                     tooltip=Tooltip(html_tooltip(especie, row['Cantidad'])),
Beispiel #22
0
def add_marker(html, group, tooltip):
    if group == 'NAM':
        Marker(location=coords, popup=html, tooltip=tooltip, icon=Icon(color='green', icon='map-marker', prefix='fa')).add_to(nam_group)
    elif group == 'EMEA':
        Marker(location=coords, popup=html, tooltip=tooltip, icon=Icon(color='purple', icon='map-marker', prefix='fa')).add_to(emea_group)
    elif group == 'APA':
        Marker(location=coords, popup=html, tooltip=tooltip, icon=Icon(color='red', icon='map-marker', prefix='fa')).add_to(asia_group)



for loc in locations:
    ind = locations[loc]
    coords, region, tz, compl, contact, image = ind[0], ind[1], ind[2], ind[3], ind[4], ind[5]
    tooltip = loc.split(',')[0]
    time = get_time(timezone(tz))
    date = get_date(timezone(tz))
    temp = get_temp(tooltip)
    temp_c, temp_f = temp[0],temp[1]
    html = format_html(loc, time, date, temp_c, temp_f, compl, contact, image)

    add_marker(html, region, tooltip)


nam_group.add_to(m)
emea_group.add_to(m)
asia_group.add_to(m)

LayerControl().add_to(m)

m.save('corporate_map.html')
Beispiel #23
0
def foliumMap():
    map_l = folium.Map(location=[55.9486, -3.2008],
                       tiles='Stamen Terrain',
                       zoom_start=14)

    venues_layer = FeatureGroup(name='Venues')
    transport_layer = FeatureGroup(name='Transport Hubs')
    walking_layer = FeatureGroup(name='Walking Tours')
    districts_layer = FeatureGroup(name='Districts')
    crowdedness_layer = FeatureGroup(name='Crowdedness Zones')
    parking_layer = FeatureGroup(name='Street Parking Zones')

    v = plotVenue()
    for i in v:
        folium.Marker(
            i[3:],
            popup=folium.Popup('Name: ' + str(i[0]) + '<br>' + 'Show : ' +
                               str(i[1]) + '<br>' + 'Genre: ' + str(i[2]),
                               max_width=450)).add_to(venues_layer)

    t = plotTransport()
    for i in t:
        folium.Marker(i[2:],
                      popup=folium.Popup('Name: ' + str(i[0]) + '<br>' +
                                         'Type: ' + str(i[1]),
                                         max_width=450),
                      icon=folium.Icon(color='red')).add_to(transport_layer)

    w = plotWalkingTours()
    for i in w:
        walkingtours = json.load(i[4])
        gj = folium.GeoJson(walkingtours,
                            style_function=lambda feature: {'color': 'Red'})
        gj.add_child(
            folium.Popup('Walking Tour: ' + str(i[0]) + '<br>' + 'Show 1: ' +
                         str(i[1]) + '<br>' + 'Show 2: ' + str(i[2]) + '<br>' +
                         'Show 3: ' + str(i[3]),
                         max_width=450))
        gj.add_to(walking_layer)

    d = plotDistricts()
    for i in d:
        districts = json.load(i[1])
        gj = folium.GeoJson(
            districts, style_function=lambda feature: {'fillColor': 'Yellow'})
        gj.add_child(folium.Popup(str(i[0]), max_width=450))
        gj.add_to(districts_layer)

    c = plotCrowdedness()
    for i in c:
        crowdedness = json.load(i[1])
        #folium.GeoJson(crowdedness, style_function=lambda feature: {'fillColor':'Red'})
        gj = folium.GeoJson(
            crowdedness, style_function=lambda feature: {'fillColor': 'Red'})
        gj.add_child(
            folium.Popup('Crowdedness Zone ' + str(i[0]), max_width=450))
        gj.add_to(crowdedness_layer)

    p = plotParkingZone()
    for i in p:
        crowdedness = json.load(i[4])
        gj = folium.GeoJson(
            crowdedness, style_function=lambda feature: {'fillColor': 'Green'})
        gj.add_child(
            folium.Popup('Parking Zone: ' + str(i[0]) + '<br>' +
                         'Start time: ' + str(i[1]) + '<br>' + 'End time: ' +
                         str(i[2]) + '<br>' + 'Disabled only: ' + str(i[3]),
                         max_width=450))
        gj.add_to(parking_layer)

    venues_layer.add_to(map_l)
    transport_layer.add_to(map_l)
    walking_layer.add_to(map_l)
    districts_layer.add_to(map_l)
    crowdedness_layer.add_to(map_l)
    parking_layer.add_to(map_l)
    LayerControl().add_to(map_l)
    return map_l.get_root().render()
Beispiel #24
0
def create_map():
    status_color_map = {
        'unknown': 'gray',
        'planned': 'blue',
        'under construction': 'green'
    }

    m = folium.Map(location=[51.4392, 6.9804], zoom_start=12)

    marker_cluster = MarkerCluster().add_to(m)

    constructions_sites = []

    for file in glob.glob(project_cards_folder + '/*.json'):
        print(file)
        with open(file) as construction_site_json:
            data = json.load(construction_site_json)
            print(data)
            constructions_sites.append(data)

    constructions_sites_feature_group = FeatureGroup(name='Projects')

    # get all project status and create subgroups based on the status
    sub_groups = list(set([cs['constructionSite'].get('status', 'unknown') for cs in constructions_sites]))
    feature_groups = dict()
    for sub_group in sub_groups:
        feature_groups[sub_group] = folium.plugins.FeatureGroupSubGroup(marker_cluster, sub_group)

    for cs in constructions_sites:
        status = cs['constructionSite'].get('status', 'unknown')
        used_layer = feature_groups[status]

        folium.GeoJson(
            cs['constructionSite']['geojson'],
            name='geojson',
        ).add_to(used_layer)

        try:
            coordinates = cs['constructionSite']['geojson']['geometry']['coordinates']
        except KeyError:
            coordinates = cs['constructionSite']['geojson']['features'][0]['geometry']['coordinates']

        # get location for marker based on the first pair of coordinates
        if isinstance(coordinates[0], list):
            # for polygons
            location = [coordinates[0][0][1],
                        coordinates[0][0][0]]
        elif isinstance(coordinates[0], float):
            # for points
            location = [coordinates[1], coordinates[0]]
        else:
            print('--------- unknown coordinate format')

        popup = folium.Popup(cs['constructionSite']['marker'], max_width=2650)

        folium.Marker(
            location=location,
            popup=popup,
            icon=folium.Icon(color=status_color_map[status])
        ).add_to(used_layer)

    constructions_sites_feature_group.add_to(m)

    print(feature_groups)
    for k, v in feature_groups.items():
        print(k)
        print(v)
        v.add_to(m)
    LayerControl().add_to(m)

    html_file_name = 'index_' + str(time.time()) + '.html'
    m.save('map/' + html_file_name)
    return html_file_name