#!/usr/bin/env python # coding: utf-8 # In[ ]: import os os.system("pip install geojson") # In[ ]: os.system("pip install shapely") # In[ ]: os.system("pip install geopandas") # In[40]: import h3 import geopandas as gpd import sys import json import geojson from shapely.geometry import Polygon, mapping # In[41]: gdfile='/home/data24/data24/0_PYTHON/H3/Partido_de_Pergamino.geojson' gdfile2='/home/data24/data24/0_PYTHON/H3/punto.geojson' resolucion=8 puntos_geojson = '/home/data3/master_folder/files_uploaded/Sin título.geojson' areas_geojson = '/home/data3/master_folder/files_uploaded/Zonas_Policiales.geojson' # In[42]: def polyfill(gdfile,gdfile2,resolucion): gdf=gpd.read_file(gdfile) gdf2=gpd.read_file(gdfile2) hexes=[] for geom in gdf.geometry: hexaux = h3.polyfill(geom.__geo_interface__, resolucion, geo_json_conformant=True) for hex in hexaux: hexes.append(hex) hexagons_geojson = geojson.FeatureCollection([geojson.Feature(geometry=geojson.Polygon([h3.h3_to_geo_boundary(h, geo_json=True)]), properties={"index": h})for h in hexes]) for k,h in enumerate(hexagons_geojson['features']): hexagons_geojson['features'][k]['properties']['npuntos']=0 for point in gdf2['geometry']: for i,hexag in enumerate(hexagons_geojson['features']): if(point.within(Polygon(hexag['geometry']['coordinates'][0]))): hexagons_geojson['features'][i]['properties']['npuntos']+=1 # with open('hexagons11.geojson', 'w') as f: # geojson.dump(hexagons_geojson, f) # res = gpd.GeoDataFrame.from_features(hexagons_geojson) # res.to_file('gpd_hexagons11.geojson',driver='GeoJSON') # return res # In[62]: def polyfill_2(gdfile,gdfile2,resolucion): # Leer el archivo GeoJSON gdf = gpd.read_file(gdfile) gdf2 = gpd.read_file(gdfile2) # Añadir la nueva propiedad a cada geometría en el GeoDataFrame gdf['npuntos'] = 0 # Convertir el GeoDataFrame de nuevo a GeoJSON geojson_data = geojson.FeatureCollection([ geojson.Feature( geometry=mapping(gdf.iloc[i].geometry), properties=gdf.iloc[i].drop('geometry').to_dict() ) for i in range(len(gdf)) ]) for point in gdf2['geometry']: for i,geom in enumerate(geojson_data['features']): if(point.within(Polygon(geom['geometry']['coordinates'][0]))): geojson_data['features'][i]['properties']['npuntos']+=1 path_output = f'{gdfile.rsplit("/",1)[0]}/salida_con_puntos_{(gdfile.rsplit("/",1)[1]).rsplit(".",1)[0]}.geojson' with open(path_output, 'w') as f: geojson.dump(geojson_data, f, indent=8) # res = gpd.GeoDataFrame.from_features(geojson_data) # res.to_file('gpd_hexagons11.geojson',driver='GeoJSON') return path_output # In[63]: print(polyfill_2(areas_geojson,puntos_geojson,resolucion)) # In[ ]: print(polyfill(gdfile,gdfile2,resolucion))