9

I have tweets with coordinates. I'm trying to bucket the tweets by country using the coordinate information. I know that I can achieve this using some hosted web services but all of these have API limits that I am sure to run into.

I started writing this code learning from another resource about osgeo library.

import osgeo.ogr

shapefile = osgeo.ogr.Open("geodata/worldborders/TM_WORLD_BORDERS-0.3.shp")
layer = shapefile.GetLayer(0)

for i in range(layer.GetFeatureCount()):
    feature = layer.GetFeature(i)
    countryCode = feature.GetField("ISO3")
    countryName = feature.GetField("NAME")
    print countryCode, countryName

    geometry = feature.GetGeometryRef()

The geometry variable has a member function called Contains that can take another Geometry and check whether the other is contained inside itself.

I have a coordinate value from Twitter data in the following format: [45.29680725, -75.92681408]. However an example on osgeo showcases creation of a point like this:

point = osgeo.ogr.Geometry(osgeo.ogr.wkbPoint)
point.SetPoint(0, 474595, 4429281)

How do I convert my coordinates into the above-required format? If I do manage to convert, is this the right approach to mapping twitter coordinates to countries?

6

2 Answers 2

12

This achieves finding country given coordinates: https://github.com/che0/countries

It uses a shapefile containing world borders loaded using python bindings for gdal.

Example:

 import countries

 cc = countries.CountryChecker('TM_WORLD_BORDERS-0.3.shp')
 print cc.getCountry(countries.Point(49.7821, 3.5708)).iso

The world borders shapefile can be obtained from http://thematicmapping.org/downloads/world_borders.php.

1
  • I tried the code and obtained: AttributeError: module 'countries' has no attribute 'CountryChecker' Commented Mar 7, 2023 at 21:20
3

Given that you only need to find what country the tweets are in I guess the VMAP0 data is sufficient.

As for Python libraries I would recommend looking at Shapely, which supports the Shapely library, a turorial on point-in-polygon can be found here. As for reading in the country polygons from the vmap0-data (which i presume are polygons in shapefiles), you should look at ogr.

1
  • Thanks. I've updated the question. Can you check it out please? Commented Feb 27, 2014 at 22:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.