<jupyter_start><jupyter_text>GeoSeries and folium> First you will learn to get information about the geometries in your data with three different GeoSeries attributes and methods. Then you will learn to create a street map layer using folium. This is the Summary of lecture "Visualizing Geospatial Data in Python", via datacamp.- toc: true - badges: true- comments: true- author: <NAME>- categories: [Python, Datacamp, Visualization]- image: images/downtown_map.png > Note : Folium map doesn't embed this page correctly. So use nbviewer for interactive map [link](https://nbviewer.jupyter.org/github/goodboychan/datacamp_repo/blob/master/Visualizing.Geospatial.Data.in.Python/GeoSeries-and-folium.ipynb)<jupyter_code>import pandas as pd
import numpy as np
import geopandas as gpd
import matplotlib.pyplot as plt
from IPython.display import HTML, IFrame

plt.rcParams['figure.figsize'] = (10, 5)<jupyter_output><empty_output><jupyter_text>GeoSeries attributes and methods I- Shapely attributes and methods    - GeoSeries.area - returns the area of each geometry in a GeoSeries    - GeoSeries.centroid - returns the center point of each geometry in a GeoSeries    - GeoSeries.distance(other) - returns the minimum distance to other  Find the area of the Urban Residents neighborhoodHow big is the Urban Residents neighborhood?<jupyter_code># Read in the neighborhoods geojson file
neighborhoods = gpd.read_file('./dataset/neighborhoods.geojson')

# Get just the Urban Residents neighborhood polygon and save it as urban_polygon
urban_polygon = neighborhoods.loc[neighborhoods.name == "Urban Residents"]
# Print the head of the urban polygon
print(urban_polygon.head())

# Create a copy of the urban_polygon using EPSG:3857 and print the head
urban_poly_3857 = urban_polygon.to_crs(epsg=3857)
print(urban_poly_3857.head())

# Print the area of urban_poly_3857 in kilometers squared
area = urban_poly_3857.geometry.area / 10**6
print('The area of the Urban Residents neighborhood is ', area.values, ' km squared')<jupyter_output>name                                           geometry
41  Urban Residents  MULTIPOLYGON (((-86.78122 36.16457, -86.78205 ...
               name                                           geometry
41  Urban Residents  MULTIPOLYGON (((-9660441.281 4323289.005, -966...
The area of the Urban Residents neighborhood is  [1.12898961]  km squared<jupyter_text>The Urban Residents neighborhood is around 1.13 square km. That seems manageable for walking to see the public art!  GeoSeries attributes and methods II  The center of the Urban Residents neighborhoodNow you'll find the center point of the `urban_poly_3857` and plot it over the polygon.<jupyter_code># Create downtown_cernter from urban_poly_3857
downtown_center = urban_poly_3857.geometry.centroid

# Print the type of downtown_center
print(type(downtown_center))

# Plot the urban_poly_3857 as ax and add the center point
ax = urban_poly_3857.plot(color='lightgreen', figsize=(7, 7));
downtown_center.plot(ax=ax, color='black');
plt.xticks(rotation=45);<jupyter_output><class 'geopandas.geoseries.GeoSeries'><jupyter_text>You can see the centroid of the Urban Residents neighborhood. Notice that latitude and longitude are in meters instead of degrees. In the next exercise you will calculate the distance in meters of each artwork from the centroid of the Urban Residents neighborhood.  Prepare to calculate distancesIn this exercise you will prepare a GeoDataFrame called `art_dist_meters` with the locations of downtown art converted to meters using EPSG:3857. You will use `art_dist_meters` in the next exercise to calculate the distance of each artwork from the center of the Urban Residents neighborhood in meters.<jupyter_code>from shapely.geometry import Point

art = gpd.read_file('./dataset/public_art.csv')
art['geometry'] = art.apply(lambda x: Point(float(x.Longitude), float(x.Latitude)), axis=1)
center_point = art.geometry.centroid
from shapely.geometry import Point

# Create art_dist_meters using art and the geometry from art
art_dist_meters = gpd.GeoDataFrame(art, geometry=art.geometry)
art_dist_meters.crs='epsg:4326'
print(art_dist_meters.head(2))

# Set the crs of art_dist_meters to use EPSG:3857
art_dist_meters.geometry = art_dist_meters.geometry.to_crs(epsg=3857)
print(art_dist_meters.head(2))

# Add a column to art_meters, center
art_dist_meters['center'] = center_point
art_dist_meters['center']<jupyter_output><empty_output><jupyter_text>The art_dist_meters Data Frame has the location of each artwork and the center point of the Urban Residents neighborhood -- both using meters for distance.  Art distances from neighborhood centerNow that you have the center point and the art locations in the units we need to calculate distances in meters, it's time to perform that step.<jupyter_code>import pprint

# Build a dictionary of titles and distances for Urban Residents art
art_distances = {}
for row in art_dist_meters.iterrows():
    vals = row[1]
    key = vals['Title']
    ctr = vals['center']
    art_distances[key] = vals['geometry'].distance(other=ctr)
    
# Pretty print the art_distances
pprint.pprint(art_distances)<jupyter_output>{'12th & Porter Mural': 10583948.500651475,
 'A Splash of Color': 10585357.160178259,
 'A Story of Nashville': 10583565.969078569,
 'Aerial Innovations Mural': 10579929.255218184,
 'Airport Sun Project': 10570311.412935875,
 '<NAME>': 10583951.468665037,
 'Angel': 10588435.041707946,
 'Anticipation': 10583698.952539692,
 'April Baby': 10586916.00892881,
 'Arial Triangle [from the Gravity Series]': 10583398.52483797,
 'Ariel': 10585905.336208293,
 '<NAME>': 10586065.827814262,
 'Benedictio': 10577769.979416678,
 'Bicycle Bus-Green Fleet': 10582635.68286198,
 'Blowing Bubbles': 10588435.041707946,
 'Breaking Bread': 10582634.392548595,
 'Building a Positive Community': 10582136.29114304,
 'Can-Do': 10582120.049094511,
 'Chet Atkins': 10583602.67968694,
 "Children's Chairs For The Seasons": 10583565.969078569,
 'Confederate Memorial': 10577769.979416678,
 'Confederate Private Monument': 10585868.029575413,
 'Confluence': 10585513.082652403,
 'Cool Fences': 10579074.34680[...]<jupyter_text>Street maps with folium- Folium    - python package    - interactive maps    - built upon Leaflet.js  Create a folium location from the urban centroidIn order to construct a folium map of the Urban Residents neighborhood, you need to build a coordinate pair location that is formatted for folium.<jupyter_code>urban_polygon.crs = 'epsg:4326'
urban_polygon.crs
# Print the head of the urban_polygon
print(urban_polygon.head())

# Create urban_center from the urban_polygon center
urban_center = urban_polygon.to_crs(epsg=4326).centroid

# Print urban_center
print(urban_center)

# Create array for folium called urban_location
urban_location = [urban_center.y, urban_center.x]

# Print urban_location
print(urban_location)<jupyter_output>name                                           geometry
41  Urban Residents  MULTIPOLYGON (((-86.78122 36.16457, -86.78205 ...
41    POINT (-86.77756 36.16128)
dtype: geometry
[41    36.161278
dtype: float64, 41   -86.777565
dtype: float64]<jupyter_text>Folium locations are arrays with latitude first. You just created a folium location from the center of the Urban Residents neighborhood.  Create a folium map of downtown NashvilleIn this exercise you will create a street map of downtown Nashville using folium.<jupyter_code>import folium

# Construct a folium map with urban_location
downtown_map = folium.Map(location=urban_location, zoom_start=15, width=500, height=500)

# Display the map
downtown_map.save('./html/downtown_map.html')
#hide_input
IFrame(src='/chans_jupyter/assets/attach/downtown_map.html', width=500, height=500)<jupyter_output><empty_output><jupyter_text>Folium locations are arrays with latitude first. You just created a folium location from the center of the Urban Residents neighborhood.  Folium street map of the downtown neighborhoodThis time you will create the folium map of downtown and add the Urban Residents neighborhood area from urban_polygon.<jupyter_code>urban_polygon['center'] = urban_polygon.loc[:, 'geometry'].centroid
# Create array for called folium_loc from the urban_polygon center point
point = urban_polygon.center
folium_loc = [point.values.y, point.values.x]

# Construct a map from folium_loc: downtown_map
downtown_map = folium.Map(location = folium_loc, zoom_start = 15, width=500, height=500)

# Draw our neighborhood: Urban Residents
folium.GeoJson(urban_polygon.geometry).add_to(downtown_map)

downtown_map.save('html/downtown_map2.html')
#hide_input
IFrame(src='/chans_jupyter/assets/attach/downtown_map2.html', width=500, height=500)<jupyter_output><empty_output><jupyter_text>Creating markers and popups in folium  Adding markers for the public artNow that you have added the polygon for the Urban Residents neighborhood to your folium street map, it's time to add the locations of the art within the neighborhood. You can do that by creating folium markers. Each marker needs a location assigned. Use `iterrows()` to loop through the data to grab the values you need.<jupyter_code># Create a GeoDataFrame from art and verify the type
art_geo = gpd.GeoDataFrame(art, crs=neighborhoods.crs, geometry=art.geometry)

# Spartially join neighborhoods with art_geo
neighborhood_art = gpd.sjoin(art_geo, neighborhoods, op='within')

# Create urban_art from neighborhood_art where the neighborhood name is Urban Residents
urban_art = neighborhood_art.loc[neighborhood_art.name == 'Urban Residents']
# Iterate through the urban_art and print each part of tuple returned
for row in urban_art.iterrows():
    print('first part: ', row[0])
    print('second part: ', row[1])
    
# Create a location and marker with each iteration for the downtown_map
for row in urban_art.iterrows():
    row_values = row[1]
    location = [row_values['Latitude'], row_values['Longitude']]
    marker = folium.Marker(location=location)
    marker.add_to(downtown_map)

downtown_map.save('html/downtown_map3.html')    
#hide_input
IFrame(src='/chans_jupyter/assets/attach/downtown_map3.html', width=500, height=500)<jupyter_output><empty_output><jupyter_text>You have created a folium map of downtown Nashville, a polygon showing the Urban Residents neighborhood, and markers to show the location of the artworks. All that's left is to create some popups for the markers!  Troubleshooting data issuesYou will be building popups for the downtown art using the `title` and `desc` columns from the `urban_art` DataFrame. Here, you will inspect those columns to identify and clean up any problematic values.<jupyter_code># Print the urban_art titles
print(urban_art.Title)

# Print the urban_art description
print(urban_art.Description)

# Replace Nan and ' values in description
urban_art.Description.fillna('', inplace=True)
urban_art.Description.str.replace("'", "`")

# Print the urban_art descriptions again
print(urban_art.Description)<jupyter_output>1                        [Fourth and Commerce Sculpture]
4                                   A Story of Nashville
21                                           <NAME>
22                     Children's Chairs For The Seasons
34                                       Foliated Scroll
39                                          Gone Fishing
40                             Happy Times at The Arcade
54                                     <NAME>
55                                 La Storia della Terra
57                                 <NAME>
59                                         Library Doors
60                               Lightning Wire Fountain
66     Nashville, A History through Maps and Aerial V...
67                                               Oh, Roy
68                                  Orpheus and Eurydice
75                               Piecing It All Together
104                                  The Birth of Apollo
105                            [...]<jupyter_text>A map of downtown artNow you will assign a popup to each marker to give information about the artwork at each location. In particular you will assign the art title and description to the popup for each marker. You will do so by creating the map object downtown_map, then add the popups, and finally use the display function to show your map.One warning before you start: you'll need to ensure that all instances of single quotes (') are removed from the pop-up message, otherwise your plot will not render!<jupyter_code>downtown_map = folium.Map(location=urban_location, zoom_start=15, width=500, height=500)
folium.GeoJson(urban_polygon.geometry).add_to(downtown_map)

# Create popups inside the loop you built to create the markers
for row in urban_art.iterrows():
    row_values = row[1] 
    location = [row_values['Latitude'], row_values['Longitude']]
    popup = (str(row_values['Title']) + ': ' + str(row_values['Description'])[:20])
    
    marker = folium.Marker(location = location, popup=popup)
    marker.add_to(downtown_map)

downtown_map.save('./html/downtown_map4.html')
#hide_input
IFrame(src='/chans_jupyter/assets/attach/downtown_map4.html', width=500, height=500)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.07728479332574896, 'fraction_numerical': 0.05324232081911263, 'mean_word_length': 4.132736473335928, 'pattern_counts': {'":': 1, '<': 47, '<?xml version=': 0, '>': 49, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 21, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '11', 'dir': 'jupyter-structured-clean-dedup', 'id': '558351', 'license': 'Apache-2.0', 'n_tokens_mistral': 4439, 'n_tokens_neox': 3839, 'n_words': 1316, 'path': '_notebooks/2020-07-02-01-GeoSeries-and-folium.ipynb', 'repo_name': 'AntonovMikhail/chans_jupyter', 'size': '13241'}