Beispiel #1
0
def update_map(df, df_ngb, coords=C.SEATTLE, zoom=C.INIT_ZOOM):

    if not(df.empty):
        coords = (df.coordY[0], df.coordX[0])

        zoom = 18

    new_map = folium.Map(location=coords, zoom_start=zoom)

    if not(df.empty):

        locations = np.asarray(df[pd.Index(['coordY', 'coordX'])])

        # re implement this using switch case
        def output():
            value = "<center><h4>Your home's ADU Eligibility</h4></center>"
            if (df.iloc[0]["zone_ind"] == 0):
                value += "<h5> For an AADU, this home is <b>Not Eligible</b></h5> This is not a single family zoned home"
            elif (df.iloc[0]["zone_ind"] == 1):
                value += "<br><h5> For an AADU, this home is <b>Eligible</b></h5> Here are some pre-approved AADU plans to consider."
            value += "<h5> For a DADU, this home is " + "<b>" + \
                str(df.iloc[0]["adu_eligible"]) + "</b></h5>"
            if (str(df.iloc[0]["adu_eligible"]) == "Eligible"):
                value += "Here are some pre-approved DADU plans to consider."
            if (df.iloc[0]["zone_ind"] == 1 and str(df.iloc[0]["adu_eligible"]) == "Eligible" and pd.isna(df.iloc[0]["ADU"])):
                value += "<br>This home is eligible to build both an ADU AND a DADU!."
            if (df.iloc[0]["adu_eligible"] == "Ineligible"):
                value += "<h5><i>Potential Problems for DADUs</i></h5>"
            if (df.iloc[0]["zone_ind"] == 0):
                value += "<br> This is not a single family zoned home"
            if (df.iloc[0]["ls_indic"] == 0):
                value += "<br> This lot is not large enough to house a DADU"
            if (df.iloc[0]["lot_dim_indic"] == "no"):
                value += "<br> This lot's dimensions are not large enough to house a DADU"
            if (df.iloc[0]["lotcov_indic"] == 0):
                value += "<br> There is insufficient lot coverage on this parcel to build a DADU"
            if (not pd.isna(df.iloc[0]["ADU"])):
                value += "<br> There is already at least one existing ADU on this property"
            if (df.iloc[0]["shoreline_ind"] == 1):
                value += "<br> This home is next to the shoreline. DADUs cannot be built by shorelines"
            if (df.iloc[0]["zone_ind"] == 1):
                value += "<h5><i>Potential considerations of concern for ADUs and DADUs: </i></h5>"
                if (df.iloc[0]["treecanopy_prct"] > 30):
                    value += "Your home may have a significant tree canopy percentage that may restrict your ability to build a DADU"
                if (df.iloc[0]["parcel_steepslope"] == 1):
                    value += "<br> Your home may have some steep areas that may make it more costly to permit and build an ADU"
                if (df.iloc[0]["parcel_flood"] == 1):
                    value += "<br> Your home may be prone to floods. This may make it more costly to permit and build an ADU"
                if (df.iloc[0]["parcel_poteslide"] == 1):
                    value += "<br> Your home may be a potential slide area. This may make it more costly to permit and build an ADU"
                if (df.iloc[0]["parcel_landf"] == 1):
                    value += "<br> Your home may be located on (or close to a?) a landfill. This may make it more costly to permit and build an ADU"
                if (df.iloc[0]["parcel_peat"] == 1):
                    value += "<br> Your home may be a peat settlement. This may make it more costly to permit and build an ADU"
                if (df.iloc[0]["parcel_riparian"] == 1):
                    value += "<br> Your home may be on a riparian corridor. This may make it more costly to permit and build an ADU"
                if (df.iloc[0]["side_sewer_conflict"] == 1):
                    value += "<br> Your home has a conflicting side sewer crossing You may have a conflicting side sewer with a neighbor or may need additional side sewer construction"
                else:
                    if (df.iloc[0]["intersecting_sewer"] == 1):
                        value += "<br> Your home has a side sewer that crosses another lot. You may need to reroute or construct a new side sewer for a DADU"
                    if (df.iloc[0]["landlocked_parcel"] == 1):
                        value += "<br> Being a landlocked parcel, you may have to run a new side sewer through another's lot while constructing an ADU."

            value += "<br><br>More details on the eligibility criteria and your home's eligibility below"
            value += "<br>Check for neighborhood covenants"

            return value

        folium.Polygon(locations=locations, color='blue', weight=6,
                       fill_opacity=0.5, fill=True,
                       popup=folium.Popup(output(), max_width=2000, show=True),
                       tooltip='Click me!',).add_to(new_map)

        neighbor = folium.map.FeatureGroup(name="neighbor",
                                           overlay=True, control=True, show=True,)

        for i in range(0, len(df_ngb)):
            folium.Marker(location=[df_ngb.iloc[i]['latitude'], df_ngb.iloc[i]['longitude']],
                          popup=folium.Popup("Type: " + df_ngb.iloc[i]["ADU_type"] + "<br>"
                                             "Permitted in: " +
                                             str(int(df_ngb.iloc[i]["year_issue"])) + "<br>"
                                             + "Address: " + df_ngb.iloc[i]["address"],  max_width=2000)
                          ).add_to(neighbor)

        neighbor.add_to(new_map)
        folium.LayerControl().add_to(new_map)

    new_map.save("map.html")
    return open("map.html", "r").read()
Beispiel #2
0
    scores = 0
    for label in grids_met:
        g = board.find_grid(label)
        scores += g.congestion_ratio

    return scores / N


if __name__ == '__main__':
    school_locations = pd.read_csv(SCHOOL_FILE)
    bps_sensor = pd.read_csv(BPS_FILE)

    reg = Region(42.70, -71.50, 42.10, -70.75)
    reg.add_ratio()

    bps_sensor = clean_data(bps_sensor)
    scores = [(pnts, score_route(reg, pnts)) for pnts in grainby(bps_sensor)]

    base_map = folium.Map(location=(42.30, -71.05), zoom_start=13)

    idling_route = min(scores, key=lambda x: x[1])
    busy_route = max(scores, key=lambda x: x[1])

    folium.Polygon(idling_route[0],
                   color='blue',
                   popup='most idling',
                   opacity=1).add_to(base_map)
    folium.Polygon(busy_route[0], color='red', popup='most busy',
                   opacity=1).add_to(base_map)

    base_map.save('q3.html')
Beispiel #3
0
import folium
import pandas as pd

newList = []
def switchLatLng(geos):
    for geo in geos:
        if isinstance(geo[0],list):
            switchLatLng(geo)
        else:
            newList.append([geo[1], geo[0]])
    return newList

myMap = folium.Map([22.73444963475145, 120.28458595275877], zoom_start=6)
kaoVill = folium.FeatureGroup()
features = pd.read_json('../../dist/mapdata/KaoVillageRange.json')["features"]
for feature in features:
    villpopup = '這裡是<h3>'+feature['properties']['TV_ALL']+'</h3>總面積為'+feature['properties']['AREA']+'平方公尺'
    coors = [switchLatLng(feature['geometry']['coordinates'])]
    newList = []
    villRange = folium.Polygon(coors, 
                               popup = villpopup,
                               fill = True).add_to(kaoVill)
kaoVill.add_to(myMap)
myMap.fit_bounds(kaoVill.get_bounds())
myMap.save('Folium_KaoVillpopup.html')
Beispiel #4
0
bounds = []
for site in sitesR.values:
    name = site[2]
    #建立locations陣列,儲存各範圍polygon所有座標點位。
    #換一個範圍就要先清空,所以建在這邊
    locations = []
    # 每一點位的polygon座標list。因為有的位置有兩個以上的範圍,這邊要先將每個範圍獨立開來。
    for rs in site[1]:
        siteLocations = rs.split(',')
        for siteLatLng in siteLocations:
            latlng = siteLatLng.split(' ')
            local = [float(latlng[0]), float(latlng[1])]
            locations.append(local)
            bounds.append(local)
        #抓到該範圍所有點後,建立polygon
        #需folium 0.6.0以上才會有polygon可以使用
        folium.Polygon(
            locations=locations,
            color='blue',
            weight=1,
            fill_color='#ffa',
            fill_opacity=0.1,
            fill=True,
            popup=name,
            tooltip='取得工程資訊',
        ).add_to(kaoMap)
#將bounds建立polygon並利用.get_bounds()取得視圖範圍,進而設定地圖的縮放範圍
bLayer = folium.Polygon(locations=bounds)
kaoMap.fit_bounds(bLayer.get_bounds())
#將地圖存成html檔
kaoMap.save('PWBsites.html')
    circle = i['circle']
    center = circle['center']
    radius = circle['radius']
    folium.Circle(
        radius=radius,
        location=center,
        fill=True,
        tooltip="Obstacle",
        opacity=0.2,
        color=ORANGE
    ).add_to(my_map)

# Create Polygon
folium.Polygon(
    locations=boundaryArr,
    fill=False,
    tooltip="GeoFence",
    color=RED).add_to(my_map)

# Create Waypath
for i in range(len(waypoint)-1):
    if not hitCircle(linePath[i]):
        folium.PolyLine(
            locations=waypoint[i:i+2],
            fill=False,
            tooltip=f"Waypath {i}",
            color=GREEN
        ).add_to(my_map)

# Create autopilot route
route = []
                                          populationFemale, literacy, sexRatio,
                                          childPopulation)
            iframe = branca.element.IFrame(html=html, width=400, height=250)
            popup = folium.Popup(iframe, parse_html=True)
            folium.Marker(location=[lat, lan],
                          popup=popup,
                          tooltip='<strong>Click to view demography of ' +
                          str(place),
                          icon=folium.Icon(color=colorDecide(event),
                                           icon_color='white',
                                           icon='cloud')).add_to(subgroup)

    subgroup.add_to(m)
folium.Polygon(locations_43,
               popup=None,
               color=findcolor(dic['Shivaji Nagar']),
               weight=4,
               opacity=0.8,
               fill_color=findcolor(dic['Shivaji Nagar'])).add_to(m)
folium.Polygon(locations_71,
               popup=None,
               color=findcolor(dic['Chembur']),
               weight=4,
               opacity=0.8,
               fill_color=findcolor(dic['Chembur'])).add_to(m)
folium.Polygon(locations_74,
               popup=None,
               color=findcolor(dic['Mahul']),
               weight=4,
               opacity=0.8,
               fill_color=findcolor(dic['Mahul'])).add_to(m)
folium.Polygon(locations_88,
Beispiel #7
0
def update_map(df, df_ngb, coords=C.SEATTLE, zoom=C.INIT_ZOOM):

    if not(df.empty):
        coords = (df.coordY[0], df.coordX[0])

        zoom = 18

    new_map = folium.Map(location=coords, zoom_start=zoom)

    if not(df.empty):

        locations = np.asarray(df[pd.Index(['coordY', 'coordX'])])

        # re implement this using switch case
        def output():
            value = "<center><h4>Your home's Eligibility for an ADU</h4></center>"
            if (df.iloc[0]["zone_ind"] == 0):
                value += "<h5> For an AADU, this home is <b>not eligible</b></h5> because it is not located in a single-family zone"
            elif (df.iloc[0]["zone_ind"] == 1):
                value += "<br><h5> For an AADU, this home is <b>eligible</b></h5> Here are some pre-approved AADU plans to consider."
            value += "<h5> For a DADU, this home is " + "<b>" + \
                str(df.iloc[0]["adu_eligible"]) + "</b></h5>"
            if (str(df.iloc[0]["adu_eligible"]) == "Eligible"):
                value += "Here are some pre-approved DADU plans to consider."
            if (df.iloc[0]["zone_ind"] == 1 and str(df.iloc[0]["adu_eligible"]) == "Eligible" and pd.isna(df.iloc[0]["ADU"])):
                value += "<br>This property is eligible to build both an AADU and a DADU!"
            if (df.iloc[0]["adu_eligible"] == "Ineligible"):
                value += "<h5><i>Potential Challenges for DADUs</i></h5>"
            if (df.iloc[0]["zone_ind"] == 0):
                value += "<br> Your property is not located on a single-family zone"
            if (df.iloc[0]["ls_indic"] == 0):
                value += "<br> Your property does not meet the minimum lot size for a DADU"
            if (df.iloc[0]["lot_dim_indic"] == "no"):
                value += "<br> Your lot's dimensions are not large enough to house a DADU"
            if (df.iloc[0]["lotcov_indic"] == 0):
                value += "<br> Given lot coverage limits, your property appears not to have sufficient available lot area to build a DADU"
            if (not pd.isna(df.iloc[0]["ADU"])):
                value += "<br> At least one ADU already exists on your property"
            if (df.iloc[0]["shoreline_ind"] == 1):
                value += "<br> Your property is located within 200 feet of a designated shoreline (i.e., the Shoreline District). \
                DADUs are not allowed in the Shoreline District"
            if (df.iloc[0]["zone_ind"] == 1):
                value += "<h5><i>Potential considerations of concern for AADUs and DADUs: </i></h5>"
                if (df.iloc[0]["yrbuilt"] < 1959):
                	value += "Given the age of your home, you converting existing space to an AADU could require substantial changes or upgrades to meet current building codes"
                if (df.iloc[0]["treecanopy_prct"] > 30):
                    value += "Your home may have a significant tree canopy percentage that may restrict your ability to build a DADU"
                if (df.iloc[0]["parcel_steepslope"] == 1):
                    value += "<br> Your property appears to have some steep areas that may make it more costly to permit and build an ADU and/or limit where you can site a DADU"
                if (df.iloc[0]["parcel_flood"] == 1):
                    value += "<br> Your property appears to be located in a floods-prone area. This may make it more costly or difficult to design, permit, and build an ADU"
                if (df.iloc[0]["parcel_poteslide"] == 1):
                    value += "<br> Your property appears to be located in a potential slide area. This may make it more costly or difficult to design, permit, and build an ADU"
                if (df.iloc[0]["parcel_landf"] == 1):
                    value += "<br> Your property appears to be located on a former landfill. This may make it more costly or difficult to design, permit, and build an ADU"
                if (df.iloc[0]["parcel_peat"] == 1):
                    value += "<br> Your property appears to be located in an area prone to peat settlement. This may make it more costly or difficult to design, permit, and build an ADU"
                if (df.iloc[0]["parcel_riparian"] == 1):
                    value += "<br> Your property appears to be located within a riparian corridor. This may make it more costly or difficult to design, permit, and build an ADU"
                if (df.iloc[0]["side_sewer_conflict"] == 1):
                    value += "<br> Your property appears to have a side sewer conflict. This could affect or limit the size or location of an ADU on your lot."
                else:
                    if (df.iloc[0]["intersecting_sewer"] == 1):
                        value += "<br> Your property has a side sewer that crosses another lot. You may need to reroute or construct a new side sewer for a DADU"
                    if (df.iloc[0]["landlocked_parcel"] == 1):
                        value += "<br> Your lot appears to be landlocked. Your ADU may require a new side sewer through a neighboring lot."

            value += "<br><br>More details on the eligibility criteria and your home's eligibility below"
            value += "<br>Check for neighborhood covenants"

            return value

        folium.Polygon(locations=locations, color='blue', weight=6,
                       fill_opacity=0.5, fill=True,
                       popup=folium.Popup(output(), max_width=2000, show=True),
                       tooltip='Click me!',).add_to(new_map)

        neighbor = folium.map.FeatureGroup(name="neighbor",
                                           overlay=True, control=True, show=True,)

        for i in range(0, len(df_ngb)):
            folium.Marker(location=[df_ngb.iloc[i]['latitude'], df_ngb.iloc[i]['longitude']],
                          popup=folium.Popup("Type: " + df_ngb.iloc[i]["ADU_type"] + "<br>"
                                             "Permitted in: " +
                                             str(int(df_ngb.iloc[i]["year_issue"])) + "<br>"
                                             + "Address: " + df_ngb.iloc[i]["address"],  max_width=2000)
                          ).add_to(neighbor)

        neighbor.add_to(new_map)
        folium.LayerControl().add_to(new_map)

    new_map.save("map.html")
    return open("map.html", "r").read()
Beispiel #8
0
    def map(
        self,
        width='100%',
        height='100%',
        tiles='Cartodb Positron',
        ignore=[],
        **kwargs,
    ):
        ''' Plot overview map with folium

        Parameters:
        ----------

        tiles: str
            tiles used, see `folium.Map?``
                - "OpenStreetMap"
                - "Mapbox Bright" (Limited levels of zoom for free tiles)
                - "Mapbox Control Room" (Limited levels of zoom for free tiles)
                - "Stamen" (Terrain, Toner, and Watercolor)
                - "Cloudmade" (Must pass API key)
                - "Mapbox" (Must pass API key)
                - "CartoDB" (positron and dark_matter)

        '''

        if ignore == 'all':
            ignore = self._units

        m = folium.Map(
            location=[self.lat_mid, self.lon_mid],
            width=width,
            height=height,
            zoom_start=11,
            tiles=tiles,
        )

        # bathymetric contours
        contours_geojson = load_bathy_contours()
        tooltip = folium.GeoJsonTooltip(
            fields=['title'],
            aliases=['depth'],
        )
        popup = folium.GeoJsonPopup(
            fields=['title'],
            aliases=['depth'],
        )

        #colorscale = branca.colormap.linear.Greys_03.scale(levels[-1],levels[0])
        def style_func(feature):
            return {
                'color': feature['properties']
                ['stroke'],  #colorscale(feature['properties']['level-value']),
                'weight': 3,  #x['properties']['stroke-width'],
                #'fillColor': x['properties']['fill'],
                'opacity': 1.,
                #'popup': feature['properties']['title'],
            }

        folium.GeoJson(
            contours_geojson,
            name='geojson',
            style_function=style_func,
            tooltip=tooltip,
            popup=popup,
        ).add_to(m)

        # campaign details
        for uname, u in self.items():
            if uname not in ignore:
                for d in u:
                    folium.Polygon([(d.start.lat, d.start.lon),
                                    (d.end.lat, d.end.lon)],
                                   tooltip=uname + ' ' + d.label + '<br>' +
                                   str(d.start.time) + '<br>' +
                                   str(d.end.time),
                                   color=cnames[u['color']],
                                   dash_array='10 20',
                                   opacity=.5).add_to(m)
                    folium.Circle(
                        (d.start.lat, d.start.lon),
                        tooltip=uname + ' ' + d.label + '<br>' +
                        str(d.start.time),
                        radius=2 * 1e2,
                        color=cnames[u['color']],
                    ).add_to(m)
                    folium.Circle(
                        (d.end.lat, d.end.lon),
                        tooltip=uname + ' ' + d.label + '<br>' +
                        str(d.end.time),
                        radius=1e2,
                        color=cnames[u['color']],
                    ).add_to(m)

        # useful plugins

        MeasureControl().add_to(m)

        fmtr_lon = "function(dec) {var min= (dec-Math.round(dec))*60; " \
                    +"direction = (dec < 0) ? 'W' : 'E'; " \
                    +"return L.Util.formatNum(dec, 0) + direction + L.Util.formatNum(min, 2);};"
        fmtr_lat = "function(dec) {var min= (dec-Math.round(dec))*60; " \
                    +"direction = (dec < 0) ? 'S' : 'N'; " \
                    +"return L.Util.formatNum(dec, 0) + direction + L.Util.formatNum(min, 2);};"
        MousePosition(lat_formatter=fmtr_lon, lng_formatter=fmtr_lat).add_to(m)

        return m
Beispiel #9
0
        if found: all_subs.append(route)

    return all_subs


if __name__ == '__main__':
    f = open('../csv/GoogleAPIKey.txt', 'r')
    API_key = f.readline()
    f.close()

    school_locations = pd.read_csv(SCHOOL_FILE)
    bps_sensor = pd.read_csv(BPS_FILE)

    reg = Region(42.70, -71.50, 42.10, -70.75)
    reg.add_ratio()

    bps_sensor = clean_data(bps_sensor)
    for pnts in grainby(bps_sensor):
        sts = trace_street(API_key, reg, pnts)
        bps_points = list()
        for st in sts:
            bps_points.append(st.begin_ptn.get_pair())
            if not (st.begin_ptn == st.end_ptn):
                bps_points.append(st.end_ptn.get_pair())

        base_map = folium.Map(location=(42.30, -71.05), zoom_start=13)
        folium.Polygon(bps_points, color='red').add_to(base_map)

        base_map.save('route_tracer.html')
        break
Beispiel #10
0
def map_hotspot_scale(hscale,
                      lat=None,
                      lng=None,
                      R=8,
                      geo_range=1.0,
                      outputfile='hotspot_probs.html',
                      bbox=None):
    """

    :param hscale: list of hotspot probabilities
    :param lat: map center latitude
    :param lng: map center longitude
    :param outputfile:
    :param bbox: lat upper left, long upper left, lat upper right, long upper right
    :return:
    """
    hs = load_hotspots()
    h_by_addr = dict()
    for h in hs:
        h_by_addr[h['address']] = h

    if not bbox:
        bbox = [
            lat + geo_range, lng - geo_range, lat - geo_range, lng + geo_range
        ]
    else:
        lat = (bbox[0] + bbox[2]) / 2
        lng = (bbox[1] + bbox[3]) / 2
    tiles = 'http://{s}.tiles.mapbox.com/v4/wtgeographer.2fb7fc73/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiY2Fybml2ZXJvdXMxOSIsImEiOiJja2U5Y3RyeGsxejd1MnBxZ2RiZXUxNHE2In0.S_Ql9KARjRdzgh1ZaJ-_Hw'
    my_map = folium.Map(
        location=[lat, lng],
        zoom_start=6,
        #tiles=tiles,
        #API_key='pk.eyJ1IjoiY2Fybml2ZXJvdXMxOSIsImEiOiJja2U5Y3RyeGsxejd1MnBxZ2RiZXUxNHE2In0.S_Ql9KARjRdzgh1ZaJ-_Hw'
        #attr='Mapbox'
    )

    vals = [x['odds'] for x in hscale]
    avg = np.mean(vals)
    #vals = np.array(vals)/avg
    print(f"{np.max(vals)}")
    print(f"average scaling factor = {avg}")

    cnorm = mpl.colors.TwoSlopeNorm(vcenter=avg,
                                    vmin=np.min(vals),
                                    vmax=np.max(vals) * 1.2)
    colmap = cm.ScalarMappable(norm=cnorm, cmap='RdYlGn')

    idc = np.argsort(vals)
    hexs = set([])  # store hex's where odds < 1.0 for displaying
    hex_parent = set([])
    hex_gparent = set([])
    hex_ggparent = set([])

    for idx in idc[::-1]:
        hp = hscale[idx]
        hlat = h_by_addr[hp['addr']]['lat']  #+ (random.random()-0.5)*.0000
        hlng = h_by_addr[hp['addr']]['lng']  #+ (random.random()-0.5)*.0000

        if not (bbox[2] < hlat < bbox[0] and bbox[1] < hlng < bbox[3]):
            continue

        color = "#" + ''.join(
            [f"{x:02x}" for x in colmap.to_rgba(hp['odds'], bytes=True)[:3]])

        folium.CircleMarker(
            (hlat, hlng),
            color='black',
            fill_color=color,
            popup=f"{h_by_addr[hp['addr']]['name']} [{hp['odds']:.2f}]",
            fill=True,
            fill_opacity=0.9,
            number_of_sides=8,
            radius=11,
            opacity=.35,
            weight=2,
            z_index_offset=2 - int(hp['odds'])).add_to(my_map)

        hexs.add(h3.h3_to_parent(h_by_addr[hp['addr']]['location'], R))
        hex_parent.add(
            h3.h3_to_parent(h_by_addr[hp['addr']]['location'], R - 1))
        hex_gparent.add(
            h3.h3_to_parent(h_by_addr[hp['addr']]['location'], R - 2))
        hex_ggparent.add(
            h3.h3_to_parent(h_by_addr[hp['addr']]['location'], R - 3))

    print(f"drawing {len(hexs)} target hexs")
    for hex in hexs:
        hex_points = list(h3.h3_to_geo_boundary(hex, False))
        hex_points.append(hex_points[0])
        folium.PolyLine(hex_points, weight=1.5, color='black',
                        opacity=.45).add_to(my_map)
        folium.Polygon(hex_points)

    print(f"drawing {len(hex_parent)} parent hexs")
    for hex in hex_parent:
        hex_points = list(h3.h3_to_geo_boundary(hex, False))
        hex_points.append(hex_points[0])
        folium.PolyLine(hex_points, weight=1.5, opacity=.65).add_to(my_map)
    print(f"drawing {len(hex_gparent)} grandparent hexs")
    for hex in hex_gparent:
        hex_points = list(h3.h3_to_geo_boundary(hex, False))
        hex_points.append(hex_points[0])
        folium.PolyLine(hex_points, weight=1.5, color='white',
                        opacity=.65).add_to(my_map)
    print(f"drawing {len(hex_gparent)} great grandparent hexs")
    for hex in hex_ggparent:
        hex_points = list(h3.h3_to_geo_boundary(hex, False))
        hex_points.append(hex_points[0])
        folium.PolyLine(hex_points, weight=1.5, color='pink',
                        opacity=.65).add_to(my_map)

    my_map.save(outputfile)
Beispiel #11
0
            linewidths=.5,
            cbar_kws={"shrink": .5})

#Map to show stationary stations position
######################
import folium
map_osm = folium.Map(
    location=[13.088279, 80.181568],  #"13.088279,80.181568") 
    zoom_start=12)

# for point in range(0, len(locationlist)):
folium.Marker([13.088279, 80.181568], popup='sta').add_to(map_osm)
folium.Marker([13.1046, 80.1710], popup='sta2').add_to(map_osm)
folium.Marker([13.005, 80.2398], popup='sta3').add_to(map_osm)
folium.Marker([13.16, 80.260], popup='sta4').add_to(map_osm)
folium.Polygon([[13.15, 80.250], [13.18, 80.280], [13.20, 80.270],
                [13.20, 80.290]])
map_osm

colors = ["windows blue", "amber", "faded green", "dusty purple"]
sns.set(
    rc={
        "figure.figsize": (15, 10),
        "axes.titlesize": 18,
        "axes.labelsize": 12,
        "xtick.labelsize": 14,
        "ytick.labelsize": 14
    })

#seasonal decompose to detect stationarity trends and seasonality
###########################
from statsmodels.tsa.seasonal import seasonal_decompose
Beispiel #12
0
              tooltip="Faubourg de l'Arche",
              color="green",
              weight=5,
              opacity=5).add_to(quartier)
    f.Polygon(Quartier_hotel,
              tooltip="Hotel de ville",
              color="lightblue",
              weight=5,
              opacity=5).add_to(quartier)
    f.Polygon(Quartier_Marceau,
              tooltip="Marceau",
              color="orange",
              weight=4,
              opacity=5).add_to(quartier)
    Courbevoie_map.add_child(quartier)


Affichage_Quartier_Courbevoie()

limite_ville = f.FeatureGroup(name='Délimitation Courbevoie')

f.Polygon(lcourbevoie, color="blue", weight=7.5,
          opacity=8).add_to(limite_ville)
Courbevoie_map.add_child(limite_ville)

f.LayerControl(collapsed=False).add_to(Courbevoie_map)
url = 'templates/courbevoie/CarteCourbevoieVille.html'
Courbevoie_map.save('maCarteCourbevoie.html')
webbrowser.open(os.getcwd() + "/maCarteCourbevoie.html")
#display(Courbevoie_map)
def CreaMap(adresse,nom):
    Courbevoie_map= f.Map(location=[48.8967,2.2567],zoom_start=15)
    icon_market=f.Icon(icon='shopping-cart', prefix='fa',markerColor='orange')
    icon_pharmacie=f.Icon(icon='',prefix='fa',marketColor='green')
    icon_medecin=f.Icon(icon='medkit',prefix='fa')
    icon_pharmacie=f.Icon(icon='ambulance',prefix='fa',markerColor='green')
    icon=icon_maison=f.Icon(icon='home',markerColor='red')
    icon1=f.Icon(marketColor='green')
    f.Marker([48.8967, 2.2567], popup="Monoprix",tooltip="Monoprix",icon=icon_pharmacie).add_to(Courbevoie_map)
    iti_sup=f.FeatureGroup(name='Itinéraire Supérette la plus proche')
    iti=f.FeatureGroup(name='Itinéraire Pharmacie la plus proche')
    zone_sport=f.FeatureGroup(name='Zone de sport')
    Courbevoie_map = Market_adresse(adresse,Courbevoie_map)
    Courbevoie_map = Affichage_client(adresse, Courbevoie_map,icon_maison)

    #on crée la map 

    #on peut rajouter des marqueurs definis par leur longitude et latitude

    #On cherche à créer des icon
    #info-sign
    #cloud
    #home
    #arrow-right

    #file="communes-93-seine-saint-denis.geojson"
    #f.GeoJson(file,name="Courbevoie").add_to(Courbevoie_map)
#Traiter les données d'un fichier csv pas aboutis car données eronnées
#lperi=[]
#lperifinale=[]
#g=open(r'C:\Users\u\Downloads\BAN_odbl_92026.csv', newline='')
#reader=csv.reader(g)
#for row in reader:
    #l=[]
    #if (row[14]!='lat' and row[15]!="long"):
        #a=float(row[14])
        #b=float(row[15])
        #l.append(a)
        #l.append(b)
        #lperi.append(tuple(l))
#print(lperi)
#for i in range(100):
    #lperifinale.append(lperi[i])  
#f.Polygon(lperifinale, color="blue", weight=7.5, opacity=8).add_to(Courbevoie_map)
    
    #Trouver les données de Courbevoie :
    lcourbevoie=[( 48.906294552742324,2.266398166116926), (48.902283797738605,2.284270341799327), (48.898400020270955,2.271065300760704),(48.896657,2.264661), (48.88688989505178,2.253756950262125), (48.89567616526661,2.2337852355532384), (48.900653602651886,2.2316248960533365), (48.90607328944114,2.2582158432572785), (48.906294552742324,2.266398166116926)]
    #f.Polygon(lcourbevoie, color="blue", weight=7.5, opacity=8).add_to(Courbevoie_map)

    #Mettre un bouton 
    #a=f.LayerControl(position='bottomright', collapsed=True,autoZIndex=True).add_to(Courbevoie_map)
    #a.add_child(name="blabla")
    tooltip="Clique pour voir ce magasin"
    #popup1=f.Popup(print("blabla"))

    #f.Marker([48.90,2.26],popup=f.Popup(max_width=450).add_child(f.Marker([48.95,2.26]).add_to(Courbevoie_map)).add_to(Courbevoie_map))

    #le popup ce qui apparait
    #le tooltip ce qui nous fais cliquer
    #Pour changer les graphiques de l'affichage
    #f.raster_layers.TileLayer('Stamen Terrain').add_to(Courbevoie_map)
    #f.raster_layers.TileLayer('Stamen Toner').add_to(Courbevoie_map)
    #f.raster_layers.TileLayer('Stamen Watercolor').add_to(Courbevoie_map)
    #f.raster_layers.TileLayer('CartoDB Positron').add_to(Courbevoie_map)
    #f.raster_layers.TileLayer('CartoDB Dark_Matter',name="map sombre").add_to(Courbevoie_map)

    #Le par defaut est le mieux dans notre cas

    # using ipywidgets
    # plot location with marker

    Courbevoie_map = Affichage_supérette(Courbevoie_map)
    Courbevoie_map = Affichage_pharmacie(Courbevoie_map)

    iti = Itinéraire_Pharmacie_la_plus_proche(Convertisseur_adresse_gps(adresse),Convertisseur_adresse_gps(Adresse_Pharmacie_la_plus_proche(adresse)),iti)
    iti_sup= Itinéraire_Supérette_la_plus_proche(Convertisseur_adresse_gps(adresse),Coordonnée_Superette_la_plus_proche(adresse),iti_sup)
    Courbevoie_map.add_child(iti)
    Courbevoie_map.add_child(iti_sup)
    #Affichage Zone de Sport
    loc=Convertisseur_adresse_gps(adresse)
    f.CircleMarker(location=loc,tooltip="Zone de sport",radius=300,color='black').add_to(zone_sport)
    Courbevoie_map.add_child(zone_sport)
    #On fait afficher les featureGroup 
    all_subgroups = f.FeatureGroup(name='Contour Courbevoie')
    f.Polygon(lcourbevoie, color="blue", weight=7.5, opacity=8).add_to(all_subgroups)
    Courbevoie_map.add_child(all_subgroups)
    # add layer control to map (allows layers to be turned on or off)
    f.LayerControl(collapsed=False).add_to(Courbevoie_map)

    #Mesure Control
    # measure control
    measure_control = plugins.MeasureControl(position='bottomright', 
                                         active_color='red', 
                                         completed_color='red', 
                                         primary_length_unit='meter')

    # add measure control to map
    Courbevoie_map.add_child(measure_control)



    url = 'courbevoie/templates/courbevoie/maCarteCourbevoie.html'
    Courbevoie_map.save(url)
 def _new_polygon(locations, hotspot):
     return folium.Polygon(locations=locations,
                           fill_color='red' if hotspot else 'green',
                           fill_opacity=0.2,
                           color='black',
                           weight=1)
Beispiel #15
0
    school_locations = pd.read_csv(SCHOOL_FILE)
    bps_sensor = pd.read_csv(BPS_FILE)

    reg = Region(42.70, -71.50, 42.10, -70.75)
    reg.add_ratio()

    bps_sensor = clean_data(bps_sensor)
    routes = grainby(bps_sensor)
    for index, origin_route in enumerate(routes):

        if len(origin_route) > 300 or len(origin_route) < 15: continue

        base_map = folium.Map(location=(42.30, -71.05), zoom_start=13)
        folium.Polygon(origin_route,
                       popup='bps route',
                       color='blue',
                       opacity=1).add_to(base_map)

        sts = trace_street(API_key, reg, origin_route)
        sts = [st for st in sts if not (st.begin_ptn == st.end_ptn)
               ]  # filter out single point street
        csts = [st for st in sts if st.has_congestion]

        subs_routes = substitue_route(csts)
        if len(subs_routes) == 0: continue

        add_school_markers(base_map, school_locations)

        for route in subs_routes:
            folium.Polygon(route,
                           popup='optimized route',
Beispiel #16
0
def show_map():
    '''
    Function to render a map around the specified line
    '''

    # import pdb
    # pdb.set_trace()

    if request.method == 'GET':
        name = request.values.get('name')
        coords_list = ast.literal_eval(request.values.get('coords'))
        geom_type = request.values.get('geom_type')
    else:
        name = request.form.get('name')
        coords_list = ast.literal_eval(request.form.get('coords'))
        geom_type = request.form.get('geom_type')

    if geom_type == "MultiPolygon":
        poly_points = []
        total_points = [] #used to calculate the average coordinates of the area of interest
        for a_polygon_coords in coords_list[0]: # may have more than one polygon
            points = []
            for coords in a_polygon_coords:
                points.append(tuple([coords[1], coords[0]]))   # swap x & y for mapping
                total_points.append(tuple([coords[1], coords[0]]))
            poly_points.append(points)
        ave_lat = sum(p[0] for p in total_points) / len(total_points)
        ave_lon = sum(p[1] for p in total_points) / len(total_points)

        lon_diff = max(p[1] for p in total_points) - min(p[1] for p in total_points)
        lat_diff = max(p[0] for p in total_points) - min(p[0] for p in total_points)
        ave_diff = (lon_diff + lat_diff)/2
        if ave_diff > 0.47:
            zoom_start_level = 8
        elif ave_diff > 0.3:
            zoom_start_level = 9
        elif ave_diff > 0.2:
            zoom_start_level = 10
        elif ave_diff > 0.1:
            zoom_start_level = 11
        elif ave_diff > 0.02:
            zoom_start_level = 12
        elif ave_diff > 0.01:
            zoom_start_level = 13
        elif ave_diff > 0.007:
            zoom_start_level = 14
        else:
            zoom_start_level = 15


        # create a new map object
        folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=zoom_start_level)
        tooltip = 'Click for more information'
        for a_poly_point in poly_points:
            folium.Polygon(a_poly_point, color="red", weight=2.5, opacity=1, popup=name, tooltip=tooltip).add_to(folium_map)
    elif geom_type == 'MultiLine': #polyline
        for a_line_coords in coords_list[0]:
            points = []
            for coords in a_line_coords:
                points.append(tuple([coords[1], coords[0]]))
            ave_lat = sum(p[0] for p in points) / len(points)
            ave_lon = sum(p[1] for p in points) / len(points)
            # create a new map object
            folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=13)
            tooltip = 'Click for more information'
            folium.PolyLine(points, color="red", weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map)
    else: #point
        # create a new map object
        lat = coords_list[1]
        lon = coords_list[0]
        folium_map = folium.Map(location=[lat, lon], zoom_start=15)
        tooltip = 'Click for more information'
        folium.Marker([lat, lon], popup=name, tooltip=tooltip).add_to(folium_map)

    # if len(coords_list) == 1:  #polyline or polygon
    #     # swap x & y for mapping
    #     points = []
    #     if len(coords_list[0]) == 1: #polygon
    #         for coords in coords_list[0][0]:
    #             points.append(tuple([coords[1], coords[0]]))
    #         ave_lat = sum(p[0] for p in points) / len(points)
    #         ave_lon = sum(p[1] for p in points) / len(points)
    #         # create a new map object
    #         folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=12)
    #         tooltip = 'Click for more information'
    #         folium.Polygon(points, color="red", weight=2.5, opacity=1, popup=name, tooltip=tooltip).add_to(folium_map)
    #     else: #polyline
    #         for coords in coords_list[0]:
    #             points.append(tuple([coords[1], coords[0]]))
    #         ave_lat = sum(p[0] for p in points) / len(points)
    #         ave_lon = sum(p[1] for p in points) / len(points)
    #         # create a new map object
    #         folium_map = folium.Map(location=[ave_lat, ave_lon], zoom_start=13)
    #         tooltip = 'Click for more information'
    #         folium.PolyLine(points, color="red", weight=2.5, opacity=1, popup = name, tooltip=tooltip).add_to(folium_map)
    # else: #point
    #     # create a new map object
    #     lat = coords_list[1]
    #     lon = coords_list[0]
    #     folium_map = folium.Map(location=[lat, lon], zoom_start=15)
    #     tooltip = 'Click for more information'
    #     folium.Marker([lat, lon], popup=name, tooltip=tooltip).add_to(folium_map)

    return folium_map.get_root().render()
Beispiel #17
0
target_list = [{"target_name": "hedef_x", "coordinates": [5.0, 2.0]},
               {"target_name": "hedef_y", "coordinates": [17.0, 1.5]},
               {"target_name": "hedef_z", "coordinates": [9.0, 22.0]},
               {"target_name": "hedef_t", "coordinates": [1.0, 3.0]}]
target_list.insert(0, {"target_name": "start", "coordinates": [0.0, 0.0]})
target_list.append({"target_name": "return", "coordinates": [0.0, 0.0]})

geomap = folium.Map([0, 0], zoom_start=5)
geopath_polygon = []
for arr in polys:
    geopath_polygon.append([[coord.x, coord.y] for coord in arr])

polypath = polys
for i in geopath_polygon:
    folium.Polygon(i, fill=True, color='red').add_to(geomap)

file = open("output.txt", "w")
file.write("[")
for i in range(len(target_list)):
    if i != len(target_list) - 1:
        shortest_path = g.shortest_path(vg.Point(target_list[i]["coordinates"][0], target_list[i]["coordinates"][1]),
                                        vg.Point(target_list[i + 1]["coordinates"][0], target_list[i + 1]["coordinates"][1]))
        geopath = [[point.x, point.y] for point in shortest_path]
        file.write(f'({target_list[i+1]["target_name"]}, {geopath}),\n')
        print(geopath)
        for point in geopath:
            folium.Marker(point, popup=str(point)).add_to(geomap)
            folium.PolyLine(geopath).add_to(geomap)
            folium.Marker(geopath[0], icon=folium.Icon(color='red')).add_to(geomap)
            folium.Marker(geopath[-1], icon=folium.Icon(color='red')).add_to(geomap)
Beispiel #18
0
import folium
import csv
import pyproj

with open('gps surface.csv') as csvfile:
    gps_data = [i[1:3] for i in csv.reader(csvfile, delimiter=',')][2:]


inProj = pyproj.Proj(init='epsg:28992')
outProj = pyproj.Proj(init='epsg:4326')

reproj = [pyproj.transform(inProj,outProj,i[0],i[1]) for i in gps_data]
reproj = [(i[1],i[0]) for i in reproj]

m = folium.Map(location=reproj[0], tiles='cartodbdark_matter', zoom_start=15)
reproj.append(reproj[0])
folium.Polygon(reproj,fill=True).add_to(m)

for i in enumerate(reproj):
    folium.CircleMarker(location=i[1],radius=0.7, popup=str(i)).add_to(m)

m.save('roof_map.html')
    "locations_71": 0,
    "locations_74": 2,
    "locations_88": 1,
    "locations_89": 4,
    "locations_94": 5
}


def findcolor(loc):
    col = colorEval(data.iloc[diction[loc]]["AQI"])
    return col


folium.Polygon(locations_43,
               popup=None,
               color=findcolor("locations_43"),
               weight=4,
               opacity=0.8,
               fill_color=findcolor("locations_43")).add_to(m)
folium.Polygon(locations_71,
               popup=None,
               color=findcolor("locations_71"),
               weight=4,
               opacity=0.8,
               fill_color=findcolor("locations_71")).add_to(m)
folium.Polygon(locations_74,
               popup=None,
               color=findcolor("locations_74"),
               weight=4,
               opacity=0.8,
               fill_color=findcolor("locations_74")).add_to(m)
folium.Polygon(locations_88,
def visualize_hexagons(hexagons_df,
                       legends=True,
                       join_muiltiindex_cols=True,
                       polygon_conf_dict={},
                       folium_map=None,
                       folium_map_config={}):
    """
    Creates a Folium map with hexagons and pop-up legend.
    :param hexagons_df: DataFrame with the H3 index has index.
    :param legends: If 'True', each hexagon will have a pop-up with all the values of its row.
    :param join_muiltiindex_cols: Joins the 'hexagons_df' columns in a single columns, if MultiIndex
    :param polygon_conf_dict: a dict to config the folium.Polygon obj. Ex.:
                {
                    # fill color is True by default, it has to be explicit turned off
                    "color": {"col":"lost_tours", "big_is_better": False, "colormap_legend": "legend", "fill_color": True},
                    "color": {"val":"green"}, # Color can also just be a single value
                    "weight": {"col":"n_bookings", "max": 6, "min":1},
                    "opacity": {"val":0.3},
                    "fill_opacity": {"val":0.15}
                }
                default: opacity: 0.3; fill_opacity: 0.15; weight: 0.5; color: green
    :param folium_map: The folium map obj to had the Hexagons to. If None a new map is created
    :param folium_map_config: default = {"zoom_start": 11,"tiles": 'cartodbpositron', "location": avg_hexagon_location}
                location: The initial lat, long to start the map at. If None tha Avg center of the hexagons will be used.
                zoom_start: the 'folium.Map()' zoom_start value. default 11
                tiles: the 'folium.Map()' tiles value. default 'cartodbpositron'
    :return: Folium map obj
    """

    hexagons_df = hexagons_df.copy()

    hexagons = hexagons_df.index.values
    n_hexs = len(hexagons)
    add_color_map_to_map = False

    # Hexagons popup Legends
    if legends is None or legends is False:
        legends = np.array(n_hexs * [None])
    elif legends is True:
        if join_muiltiindex_cols and type(
                hexagons_df.columns) == pd.MultiIndex:
            hexagons_df.columns = ["-".join(c) for c in hexagons_df.columns]
        hexagons_dict = hexagons_df.to_dict("index")
        legends = [f"{idx}: {hexagons_dict[idx]}" for idx in hexagons]

    # processing Polygon Propreties
    # Adding default Polygon configs
    polygon_conf_dict.setdefault("opacity", {"val": 0.3})
    polygon_conf_dict.setdefault("fill_opacity", {"val": 0.15})
    polygon_conf_dict.setdefault("weight", {"val": 0.5})
    polygon_conf_dict.setdefault("color", {"val": "green"})

    all_poly_props_df = pd.DataFrame()
    for col_name, conf in polygon_conf_dict.items():
        if "col" in conf:
            poly_prop_values = hexagons_df[conf["col"]]
            # Normalize
            if set(("min", "max")).issubset(conf):
                poly_prop_values = (conf["min"] + norm_col(poly_prop_values) *
                                    (conf["max"] - conf["min"])).values
        elif "val" in conf:
            poly_prop_values = len(hexagons_df) * [conf["val"]]
        #     else:
        #         raise Exception("No 'col' or 'val' key found! :(")
        # Processing colors
        if col_name == "color":
            if "col" in conf:
                big_is_better = conf[
                    "big_is_better"] if "big_is_better" in conf else True
                cm_legend = conf[
                    "colormap_legend"] if "colormap_legend" in conf else str(
                        conf["col"]).replace("'", "")
                colormap = ColorMap(np.min(poly_prop_values),
                                    np.max(poly_prop_values), cm_legend,
                                    big_is_better)
                poly_prop_values = [colormap(ci) for ci in poly_prop_values]
                add_color_map_to_map = True
            # Adds fill color by default, it has to be explicit turned off
            if ("fill_color" in conf and conf["fill_color"]) or ("fill_color"
                                                                 not in conf):
                all_poly_props_df["fill_color"] = poly_prop_values

        all_poly_props_df[col_name] = poly_prop_values

    polys_config = list(all_poly_props_df.to_dict("index").values())

    # Initial Location
    if "location" not in folium_map_config:
        location = np.mean([h3.h3_to_geo(h3_id) for h3_id in hexagons], axis=0)
        folium_map_config["location"] = location

    # Creates Folium map
    if folium_map is None:
        folium_map_config.setdefault("zoom_start", 11)
        folium_map_config.setdefault("tiles", 'cartodbpositron')
        m = folium.Map(**folium_map_config)
    else:
        m = folium_map

    # adding polygons
    for hex_id, leg, poly_conf in zip(hexagons, legends, polys_config):
        locations = h3.h3_to_geo_boundary(hex_id)
        folium.Polygon(locations, popup=leg, **poly_conf).add_to(m)
    # adds the colormap legend to the map
    if add_color_map_to_map:
        m.add_child(colormap.colormap)
        colormap.colormap.add_to(m)
    return m
Beispiel #21
0
                                             height=300).interactive())

vega = folium.features.VegaLite(base, width=700, height=50)
graph_popup = folium.Popup()  # Create a popup
vega.add_to(graph_popup)  # Add graph to popup
marker = folium.features.Marker([df_cd.iloc[5, 0], df_cd.iloc[5, 1]],
                                icon=folium.Icon(color='white',
                                                 icon='bicycle',
                                                 icon_color="orange",
                                                 prefix='fa')).add_to(m)
graph_popup.add_to(marker)
marker.add_to(m)

# Linking markers
my_Polygone = folium.Polygon(locations=df_cd,
                             weight=4,
                             color='yellow',
                             opacity=1)
m.add_child(my_Polygone)

folium.TileLayer(tiles='Stamen Terrain', name='Stamen Terrain',
                 show=True).add_to(m)
folium.TileLayer(tiles='cartodb positron', name='cartodb positron',
                 show=True).add_to(m)
folium.TileLayer(tiles="stamentonerbackground",
                 name="stamentoner background",
                 show=True).add_to(m)

# Add a title

title_html = '''
             <h3 align="center" style="color:purple;background-color:#2AAE67;font-size:210%"> <b>Montpellier's bicycle counters</b> </h3>