@@ -27,12 +27,12 @@ def get_intersecting_geometries(
2727) -> Union [List [str ], Dict [str , List [str ]]]:
2828 """
2929 Get identifiers for census regions intersecting a geometry.
30-
30+
3131 This function returns a list of regions that intersect a given geometry input.
3232 This list of regions can be used directly to query census when one is interested
3333 in census data for a particular geographic region that does not coincide with
3434 defined census geometries.
35-
35+
3636 Parameters
3737 ----------
3838 dataset : str
@@ -53,27 +53,27 @@ def get_intersecting_geometries(
5353 api_key : str, optional
5454 API key for CensusMapper API. If None, uses environment variable
5555 or previously set key.
56-
56+
5757 Returns
5858 -------
5959 List[str] or Dict[str, List[str]]
6060 If simplified=True, returns a list of region identifiers.
6161 If simplified=False, returns a dictionary with level as key and
6262 list of region IDs as value, suitable for use with get_census().
63-
63+
6464 Examples
6565 --------
6666 >>> import pycancensus as pc
6767 >>> from shapely.geometry import Point
68- >>>
68+ >>>
6969 >>> # Example using a Point from lat/lon coordinates
7070 >>> point_geo = Point(-123.25149, 49.27026)
7171 >>> regions = pc.get_intersecting_geometries(
72- ... dataset='CA21',
73- ... level='CT',
72+ ... dataset='CA21',
73+ ... level='CT',
7474 ... geometry=point_geo
7575 ... )
76- >>>
76+ >>>
7777 >>> # Use regions to get census data
7878 >>> census_data = pc.get_census(
7979 ... dataset='CA21',
@@ -84,43 +84,43 @@ def get_intersecting_geometries(
8484 """
8585 # Validate inputs
8686 validate_dataset (dataset )
87-
87+
8888 if api_key is None :
8989 api_key = get_api_key ()
9090 if api_key is None :
9191 raise ValueError (
9292 "API key required. Set with set_api_key() or CANCENSUS_API_KEY "
9393 "environment variable."
9494 )
95-
95+
9696 # Process geometry input
9797 processed_geometry = _process_geometry_input (geometry )
98-
98+
9999 # Ensure geometry is in WGS84 (EPSG:4326)
100100 if processed_geometry .crs is None :
101101 warnings .warn ("No CRS specified for geometry, assuming WGS84 (EPSG:4326)" )
102- processed_geometry = processed_geometry .set_crs (' EPSG:4326' )
102+ processed_geometry = processed_geometry .set_crs (" EPSG:4326" )
103103 elif processed_geometry .crs .to_epsg () != 4326 :
104- processed_geometry = processed_geometry .to_crs (' EPSG:4326' )
105-
104+ processed_geometry = processed_geometry .to_crs (" EPSG:4326" )
105+
106106 # Union multiple geometries if needed
107107 if len (processed_geometry ) > 1 :
108108 geometry_union = unary_union (processed_geometry .geometry )
109- processed_geometry = gpd .GeoSeries ([geometry_union ], crs = ' EPSG:4326' )
110-
109+ processed_geometry = gpd .GeoSeries ([geometry_union ], crs = " EPSG:4326" )
110+
111111 # Convert to GeoJSON
112112 geojson_str = processed_geometry .to_json ()
113-
113+
114114 # Calculate area in square meters (approximate for WGS84)
115115 # Using area in degrees^2 * conversion factor for rough area estimate
116116 area = processed_geometry .area .iloc [0 ]
117117 # Convert from square degrees to approximate square meters at equator
118- area_m2 = area * (111320 ** 2 ) # Rough conversion
119-
118+ area_m2 = area * (111320 ** 2 ) # Rough conversion
119+
120120 # Create cache key
121121 param_string = f"dataset={ dataset } &level={ level } &geometry={ geojson_str } "
122122 cache_key = f"intersect_{ hashlib .md5 (param_string .encode ()).hexdigest ()} "
123-
123+
124124 # Check cache first
125125 if use_cache :
126126 cached_data = get_cached_data (cache_key )
@@ -137,7 +137,7 @@ def get_intersecting_geometries(
137137 result = _query_intersecting_geometries_api (
138138 dataset , level , geojson_str , area_m2 , api_key , quiet
139139 )
140-
140+
141141 # Format output based on simplified parameter
142142 if simplified :
143143 # Return simple list of region IDs
@@ -162,7 +162,7 @@ def _process_geometry_input(geometry) -> gpd.GeoSeries:
162162 return geometry .geometry
163163 elif isinstance (geometry , gpd .GeoSeries ):
164164 return geometry
165- elif hasattr (geometry , ' __geo_interface__' ):
165+ elif hasattr (geometry , " __geo_interface__" ):
166166 # Shapely geometry or similar
167167 return gpd .GeoSeries ([geometry ])
168168 else :
@@ -173,12 +173,11 @@ def _process_geometry_input(geometry) -> gpd.GeoSeries:
173173
174174
175175def _query_intersecting_geometries_api (
176- dataset : str , level : str , geojson_str : str , area : float ,
177- api_key : str , quiet : bool
176+ dataset : str , level : str , geojson_str : str , area : float , api_key : str , quiet : bool
178177) -> Any :
179178 """Query the CensusMapper API for intersecting geometries."""
180179 base_url = "https://censusmapper.ca/api/v1/"
181-
180+
182181 # Prepare request data
183182 request_data = {
184183 "dataset" : dataset ,
@@ -187,10 +186,10 @@ def _query_intersecting_geometries_api(
187186 "area" : area ,
188187 "api_key" : api_key ,
189188 }
190-
189+
191190 if not quiet :
192191 print ("Querying CensusMapper API for intersecting geometries..." )
193-
192+
194193 try :
195194 response = requests .post (
196195 f"{ base_url } intersecting_geographies" ,
@@ -199,19 +198,21 @@ def _query_intersecting_geometries_api(
199198 timeout = 60 ,
200199 )
201200 response .raise_for_status ()
202-
201+
203202 result = response .json ()
204-
203+
205204 if not quiet :
206205 if isinstance (result , list ):
207206 print (f"✅ Found { len (result )} intersecting regions" )
208207 elif isinstance (result , dict ):
209- total = sum (len (v ) if isinstance (v , list ) else 1 for v in result .values ())
208+ total = sum (
209+ len (v ) if isinstance (v , list ) else 1 for v in result .values ()
210+ )
210211 print (f"✅ Found { total } intersecting regions" )
211-
212+
212213 return result
213-
214+
214215 except requests .exceptions .RequestException as e :
215216 raise RuntimeError (f"API request failed: { e } " )
216217 except Exception as e :
217- raise RuntimeError (f"Failed to process API response: { e } " )
218+ raise RuntimeError (f"Failed to process API response: { e } " )
0 commit comments