{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Saving the power plants to a GeoJSON\n\nGeoJSONs are a great format to be able to open points very easily. They are basically just geo-located JSON files, which prevent us from having to retrieve the location info from each point with a self-made function each time we want to plot / access to points.\n\nIn this short notebook, I'll show how this is done with a library called `geopandas` and how to then simply save this file.\n\nI also created a dataset [here](https://www.kaggle.com/maxlenormand/geolocated-power-plants-geojson) if you simply want to download the `.geojson` file directly."},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"import numpy as np\nimport os\n\nimport pandas as pd\n\n# Plotting libraries\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Geospatial libraries that we will be using for this\nimport folium\nimport geopandas as gpd\nfrom shapely.geometry import Point","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"First we need to find where the location information is in the original `.csv` file:"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true,"_kg_hide-input":true},"cell_type":"code","source":"power_plants = pd.read_csv('/kaggle/input/ds4g-environmental-insights-explorer/eie_data/gppd/gppd_120_pr.csv')\npower_plants.columns","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"If we take a look at the `.geo` column, we cna see that the location is in a string in there:"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plotting the .geo info of the first power plant\npower_plants['.geo'][0]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We can easily extract the longitude & latitude of a given point and keep it as a float"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"longitude = float(power_plants['.geo'][0].split(\"[\")[1][:-2].split(\",\")[0])\nlatitude = float(power_plants['.geo'][0].split(\"[\")[1][:-2].split(\",\")[1])\n\nprint(f'Longitude: {longitude}, lattitude: {latitude}')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# We can create a new column containing this information\npower_plants['longitude'] = [float(power_plants['.geo'][point].split(\"[\")[1][:-2].split(\",\")[0]) for point in range(power_plants.shape[0])]\npower_plants['latitude'] = [float(power_plants['.geo'][point].split(\"[\")[1][:-2].split(\",\")[1]) for point in range(power_plants.shape[0])]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"GeoDataFrames are like pandas DataFrames, except they have an additional column called the `geometry` which will contain Shapely information about the row object given (here it is a point, but it could also be polygons (for boundaries of a country for example) or multipolyons)."},{"metadata":{"trusted":true},"cell_type":"code","source":"geometry_power_plants = [Point(x,y) for x,y in zip(power_plants.longitude, power_plants.latitude)]","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"del power_plants['.geo']","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"As we are saving these points with some geo-location information, we need to give it a CRS: Coordinate Reference System. These are just the reference system used to calculate the given longitude and latitude given in the `geometry` column."},{"metadata":{"trusted":true},"cell_type":"code","source":"gdf_power_plants = gpd.GeoDataFrame(power_plants, crs = {'init': 'epsg: 4326'}, geometry = geometry_power_plants)\ngdf_power_plants.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We can now simply plot this GeoDataFrame"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"gdf_power_plants.plot()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Just to be sure, we can plot these on a Folium Map, to check that we have the correct CRS and we didn't mess up anything. (You can also check by un-hiding the code, that plotting points on a map with a GeoDataFrame is much easier than if we had to create an additional function to retrieve the longitude and latitude. Technically we could just keep that in a pandas DataFrame, but for the sake of the deomstration, GeoDataFrames are shown here)."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# Plot on the map\nlat=18.200178; lon=-66.664513\nplot = folium.Map(location = (lat, lon), zoom_start=9)\n\nfor plant_lat, plant_long in zip(gdf_power_plants.latitude, gdf_power_plants.longitude):\n    folium.Marker(location = (plant_lat, plant_long),\n                    icon = folium.Icon(color='blue')).add_to(plot)\n    \nplot","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"And finally, we want to save this GeoDataFrame to be able to use it later"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Saving the geodataframe for easy use later\ngdf_power_plants.to_file('Geolocated_gppd_120_pr.geojson', driver='GeoJSON')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"I should add that there are more benefits to making handling GeoJSONs instead of CSVs. For example, we can very easily drop them in QGIS and compare them to any rasters we might have:\n\n![Imgur](https://i.imgur.com/AX4e89p.png)"},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}