0

I'm willing to build a tiny service that given a point location, it searches within a multipolygon, which polygon object it is intersecting. My current development is defined as this:

from osgeo import ogr, osr, gdal
import geopandas as gpd
import shapely
import json
import requests
import zipfile
import io




'''
Returns the city, state of a certain geolocation in Brazil
'''

debbuging_mode = True

if debbuging_mode:
    ogr.UseExceptions()
    osr.UseExceptions()
    gdal.UseExceptions()

def main(lat=None, lon=None):
    # Variable setup
    if (lat == None) or (lon == None):
        # Using a generic city for demonstration
        with open('static/test/ponta_pora.json') as json_file:
            data = json.load(json_file)
            for key in data:
                lat = data['latDec']
                lon = data['lonDec']
    ibgeCode = city_name = state = None

    # Define spatial reference (WGS84)
    srs = osr.SpatialReference()
    srs.ImportFromEPSG(4326)

    # Create ogr point object
    point = ogr.Geometry(ogr.wkbPoint)
    point.AddPoint(x=float(lon),y=float(lat), z=float(0.0)) # Forcing datatype is mandatory

    shp_file = 'static/datasets/ibge/2018/UF/BRUFE250GC_SIR.shp'
    driver = ogr.GetDriverByName('ESRI Shapefile')
    dataSource = driver.Open(shp_file,0)
    layer = dataSource.GetLayer(0) # Single layer shapefile by definition

    intersection = None
    layer.Intersection(point, intersection)

    print(intersection)
    print('Intersection: '+intersection.ExportToWkt())

    return lat, lon, ibgeCode, city_name, state

The shapefile is a multipolygon with its parts being all cities in Brazil, and the Json provides a valid coordinate in WGS84.

However, I am getting an error when trying to intersect:

Traceback (most recent call last):
  File "/Users/ricardobarroslourenco/PycharmProjects/brazil_city_search/bcs/__init__.py", line 88, in <module>
    main()
  File "/Users/ricardobarroslourenco/PycharmProjects/brazil_city_search/bcs/__init__.py", line 48, in main
    layer.Intersection(point, intersection)
  File "/anaconda3/envs/brazil_city_search/lib/python3.7/site-packages/osgeo/ogr.py", line 2555, in Intersection
    return _ogr.Layer_Intersection(self, *args, **kwargs)
TypeError: in method 'Layer_Intersection', argument 2 of type 'OGRLayerShadow *'

Any hint on what this error might be? Note: The final print is just for debuggig, ideally I would be parsing the intersected plygon object and returning its properties.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.