Code Monkey home page Code Monkey logo

geopy's Introduction

geopy

Latest Version

License

geopy is a Python client for several popular geocoding web services.

geopy makes it easy for Python developers to locate the coordinates of addresses, cities, countries, and landmarks across the globe using third-party geocoders and other data sources.

geopy includes geocoder classes for the OpenStreetMap Nominatim, Google Geocoding API (V3), and many other geocoding services. The full list is available on the Geocoders doc section. Geocoder classes are located in geopy.geocoders.

geopy is tested against CPython (versions 3.7, 3.8, 3.9, 3.10, 3.11, 3.12) and PyPy3. geopy 1.x line also supported CPython 2.7, 3.4 and PyPy2.

© geopy contributors 2006-2018 (see AUTHORS) under the MIT License.

Installation

Install using pip with:

pip install geopy

Or, download a wheel or source archive from PyPI.

Geocoding

To geolocate a query to an address and coordinates:

>>> from geopy.geocoders import Nominatim
>>> geolocator = Nominatim(user_agent="specify_your_app_name_here")
>>> location = geolocator.geocode("175 5th Avenue NYC")
>>> print(location.address)
Flatiron Building, 175, 5th Avenue, Flatiron, New York, NYC, New York, ...
>>> print((location.latitude, location.longitude))
(40.7410861, -73.9896297241625)
>>> print(location.raw)
{'place_id': '9167009604', 'type': 'attraction', ...}

To find the address corresponding to a set of coordinates:

>>> from geopy.geocoders import Nominatim
>>> geolocator = Nominatim(user_agent="specify_your_app_name_here")
>>> location = geolocator.reverse("52.509669, 13.376294")
>>> print(location.address)
Potsdamer Platz, Mitte, Berlin, 10117, Deutschland, European Union
>>> print((location.latitude, location.longitude))
(52.5094982, 13.3765983)
>>> print(location.raw)
{'place_id': '654513', 'osm_type': 'node', ...}

Measuring Distance

Geopy can calculate geodesic distance between two points using the geodesic distance or the great-circle distance, with a default of the geodesic distance available as the function geopy.distance.distance.

Here's an example usage of the geodesic distance, taking pair of (lat, lon) tuples:

>>> from geopy.distance import geodesic
>>> newport_ri = (41.49008, -71.312796)
>>> cleveland_oh = (41.499498, -81.695391)
>>> print(geodesic(newport_ri, cleveland_oh).miles)
538.390445368

Using great-circle distance, also taking pair of (lat, lon) tuples:

>>> from geopy.distance import great_circle
>>> newport_ri = (41.49008, -71.312796)
>>> cleveland_oh = (41.499498, -81.695391)
>>> print(great_circle(newport_ri, cleveland_oh).miles)
536.997990696

Documentation

More documentation and examples can be found at Read the Docs.

geopy's People

Contributors

aqueiros avatar atosatto avatar cffk avatar crccheck avatar deeplook avatar dennisstritzke avatar ericpalakovichcarr avatar gaelsimon avatar gotche avatar ijl avatar jbouvier avatar jhmaddox avatar jmb avatar kostyaesmukov avatar magnushiie avatar matkoniecz avatar medecau avatar migurski avatar mondeja avatar mtigas avatar mtmail avatar mwtoews avatar paulefoe avatar pratheekrebala avatar sebastianneubauer avatar serphentas avatar sheub avatar spatialbitz avatar thomasg77 avatar vetkansk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

geopy's Issues

failures in testsuite in latest relase, 1.1.3

$ nosetests --verbose --processes=-1

yields

======================================================================
ERROR: test suite for <class 'test.ArcGISAuthenticatedTestCase'>
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib64/python2.7/site-packages/nose/plugins/multiprocess.py", line 788, in run
    self.setUp()
  File "/usr/lib64/python2.7/site-packages/nose/suite.py", line 291, in setUp
    self.setupContext(ancestor)
  File "/usr/lib64/python2.7/site-packages/nose/plugins/multiprocess.py", line 770, in setupContext
    super(NoSharedFixtureContextSuite, self).setupContext(context)
  File "/usr/lib64/python2.7/site-packages/nose/suite.py", line 314, in setupContext
    try_run(context, names)
  File "/usr/lib64/python2.7/site-packages/nose/util.py", line 470, in try_run
    return func()
  File "/mnt/gen2/TmpDir/portage/dev-python/geopy-1.1.3/work/geopy-1.1.3/test/geocoders/arcgis.py", line 74, in setUpClass
    username=env['ARCGIS_USERNAME'],
KeyError: 'ARCGIS_USERNAME'

======================================================================
ERROR: test suite for <class 'test.GeoNamesTestCase'>
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib64/python2.7/site-packages/nose/plugins/multiprocess.py", line 788, in run
    self.setUp()
  File "/usr/lib64/python2.7/site-packages/nose/suite.py", line 291, in setUp
    self.setupContext(ancestor)
  File "/usr/lib64/python2.7/site-packages/nose/plugins/multiprocess.py", line 770, in setupContext
    super(NoSharedFixtureContextSuite, self).setupContext(context)
  File "/usr/lib64/python2.7/site-packages/nose/suite.py", line 314, in setupContext
    try_run(context, names)
  File "/usr/lib64/python2.7/site-packages/nose/util.py", line 470, in try_run
    return func()
  File "/mnt/gen2/TmpDir/portage/dev-python/geopy-1.1.3/work/geopy-1.1.3/test/geocoders/geonames.py", line 15, in setUpClass
    cls.geocoder = GeoNames(username=env['GEONAMES_USERNAME'])
  File "/mnt/gen2/TmpDir/portage/dev-python/geopy-1.1.3/work/geopy-1.1.3/geopy/geocoders/geonames.py", line 60, in __init__
    'No username given, required for api access.  If you do not '
ConfigurationError: No username given, required for api access.  If you do not have a GeoNames username, sign up here: http://www.geonames.org/login

======================================================================
ERROR: test suite for <class 'test.YahooPlaceFinderTestCase'>
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib64/python2.7/site-packages/nose/plugins/multiprocess.py", line 788, in run
    self.setUp()
  File "/usr/lib64/python2.7/site-packages/nose/suite.py", line 291, in setUp
    self.setupContext(ancestor)
  File "/usr/lib64/python2.7/site-packages/nose/plugins/multiprocess.py", line 770, in setupContext
    super(NoSharedFixtureContextSuite, self).setupContext(context)
  File "/usr/lib64/python2.7/site-packages/nose/suite.py", line 314, in setupContext
    try_run(context, names)
  File "/usr/lib64/python2.7/site-packages/nose/util.py", line 470, in try_run
    return func()
  File "/mnt/gen2/TmpDir/portage/dev-python/geopy-1.1.3/work/geopy-1.1.3/test/geocoders/placefinder.py", line 19, in setUpClass
    env['YAHOO_SECRET']
  File "/mnt/gen2/TmpDir/portage/dev-python/geopy-1.1.3/work/geopy-1.1.3/geopy/geocoders/placefinder.py", line 74, in __init__
    encoding=None # already UTF-8
TypeError: __init__() got an unexpected keyword argument 'encoding'

----------------------------------------------------------------------
Ran 140 tests in 7.014s

FAILED (SKIP=23, errors=3)

in python2.7

python3.3 3.4 also has

======================================================================
FAIL: Point.format()
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/mnt/gen2/TmpDir/portage/dev-python/geopy-1.1.3/work/geopy-1.1.3/test/test_point.py", line 51, in test_point_format
    self.assertEqual(point.format(), "51 19m 12.9s N, 0 1m 24.95s E")
AssertionError: '51 19m 12.90000000000532s N, 0 1m 24.949999999999996s E' != '51 19m 12.9s N, 0 1m 24.95s E'
- 51 19m 12.90000000000532s N, 0 1m 24.949999999999996s E
+ 51 19m 12.9s N, 0 1m 24.95s E

. Do you replicate?

YahooFinder placefinder.py exactly_one fails on empty results

Line 191 placefinder.py

    if exactly_one:
        return results[0]
    else:
        return results

fails on no proper result being returned - specifically one filtered out because country code's don't match.
Throws index error.

Is this designed and expected behavior?

geopy.Point __repr__ method does not format properly

I simply opened up a python (2.7.6) shell to play around with the Geopy.point.Point class and I noticed the repr method does not format its string properly.

>>> import geopy
>>> p1 = geopy.point.Point(1.0,2.0)
>>> p1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "geopy/point.py", line 158, in __repr__
    return "Point(%r, %r, %r)" % self._items
TypeError: not enough arguments for format string

It seems to be just a misuse of the % style string formatting in python. It should be passing in a tuple, not a list which self._items returns.

This was especially frustrating as it was my first time using the library haha.

YahooPlaceFinder class has two problems (maybe?)

Two things:

  1. I found that in _call_yahoo(), the join(item) for params failed for "count" because params['count'] = 1 is an integer, not a string. Making it params['count'] = '1' solves this but I have to wonder if there was a reason it is the way it is

  2. In _filtered_results(), the quality filter errors out with:

line 89, in _filtered_results
    if int(place['quality']) > min_quality
TypeError: string indices must be integers

Did something change with the Yahoo! BOSS API that this is happening?
I'm pretty new to Python so please be patient with me!

This is for .98

Is there a way to find all valid addresses in a city?

Hi. I want to make a hit map of a city, I want to place in each street address the distance to the nearest bus station. For this, I need to "crawl" the city. You code seems to be exactly what I need, but, from what I gather, it access an online service per quary which is going to be slow, and will probably breach some limitation. For example, nominatim allow 1 quary/sec. I have osm file of my city on my machine. Can I use this instead?

Thanks.

IL, USA doesn't find results but Illinois, USA does and NY, USA does as well

print geolocator.geocode("IL, USA").raw
{u'display_name': u'United States of America', u'importance': 0.944692348398, u'
place_id': u'127658196', u'lon': u'-100.4458825', u'lat': u'39.7837304', u'osm_t
ype': u'relation', u'licence': u'Data \xa9 OpenStreetMap contributors, ODbL 1.0.
http://www.openstreetmap.org/copyright', u'osm_id': u'148838', u'boundingbox':
[u'-14.7608357', u'71.6048217', u'-179.9999999', u'180'], u'type': u'administrat
ive', u'class': u'boundary', u'icon': u'https://nominatim.openstreetmap.org/imag
es/mapicons/poi_boundary_administrative.p.20.png'}

Doesn't give me the proper results :'(

Installation error (SyntaxError)

Caise syntaxError while install pachage by pip

pip install -U geopy
Downloading/unpacking geopy from https://pypi.python.org/packages/source/g/geopy/geopy-1.1.5.tar.gz#md5=c0ca5e67f2a839563e8268c8b1713d0c
  Downloading geopy-1.1.5.tar.gz (64kB): 64kB downloaded
  Running setup.py egg_info for package geopy
    Traceback (most recent call last):
      File "<string>", line 16, in <module>
      File "/home/chehov/.virtualenvs/.../build/geopy/setup.py", line 6, in <module>
        from geopy import __version__ as version
      File "geopy/__init__.py", line 9, in <module>
        from geopy.point import Point
      File "geopy/point.py", line 9, in <module>
        from geopy.format import (
      File "geopy/format.py", line 119
        for n, d
          ^
    SyntaxError: invalid syntax
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 16, in <module>

  File "/home/chehov/.virtualenvs/.../build/geopy/setup.py", line 6, in <module>

    from geopy import __version__ as version

  File "geopy/__init__.py", line 9, in <module>

    from geopy.point import Point

  File "geopy/point.py", line 9, in <module>

    from geopy.format import (

  File "geopy/format.py", line 119

    for n, d

      ^

SyntaxError: invalid syntax

----------------------------------------

https://github.com/geopy/geopy/blob/master/geopy/format.py#L119

P.S. Ubuntu 10.04, Python 2.6.5

Please include tests in source dist

Hello,
this is a very minor issue!
Please can you include tests in the source dist? This way a downstream distribution can run tests during the build of the package. Not installing tests there aren't problems related to namespace pollution.

Thanks and kind regards!

Seconds in degrees-minutes-seconds representation always printed as 0.

I was just playing around for the first time with geopy (0.99 from PyPI) and am confused about the following:

>>> import geopy
>>> import geopy.distance
>>> start = geopy.Point(51.078217, 13.773686)
>>> d = geopy.distance.VincentyDistance(kilometers = 1.0)
>>> print d.destination(point=start, bearing=0)
51 5m 0.0s N, 13 46m 0.0s E
>>> d = geopy.distance.VincentyDistance(kilometers = 5.1)
>>> print d.destination(point=start, bearing=0)
51 7m 0.0s N, 13 46m 0.0s E

As you can see, the seconds part of the output point is always given as 0.0. This is not by accident, it is wrong, another implementation of the Vincenty formulae (http://www.movable-type.co.uk/scripts/latlong-vincenty.html) provides the same degrees and minutes, but also fractions of seconds.

TypeError in __repr__ of Point class

Point created like in docstring of the Point class here raises TypeError when __repr__ is called.

The reason is usage of string formatting with list instead of tuple.

In [1]: from  geopy import Point

In [2]: Point(41.5, -81, 0)
Out[2]: ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-d42982c18706> in <module>()
----> 1 Point(41.5, -81, 0)

/usr/local/lib/python2.7/dist-packages/IPython/core/displayhook.pyc in __call__(self, result)
    245             self.start_displayhook()
    246             self.write_output_prompt()
--> 247             format_dict, md_dict = self.compute_format_data(result)
    248             self.write_format_data(format_dict, md_dict)
    249             self.update_user_ns(result)

/usr/local/lib/python2.7/dist-packages/IPython/core/displayhook.pyc in compute_format_data(self, result)
    155 
    156         """
--> 157         return self.shell.display_formatter.format(result)
    158 
    159     def write_format_data(self, format_dict, md_dict=None):

/usr/local/lib/python2.7/dist-packages/IPython/core/formatters.pyc in format(self, obj, include, exclude)
    150             md = None
    151             try:
--> 152                 data = formatter(obj)
    153             except:
    154                 # FIXME: log the exception

/usr/local/lib/python2.7/dist-packages/IPython/core/formatters.pyc in __call__(self, obj)
    479                 type_pprinters=self.type_printers,
    480                 deferred_pprinters=self.deferred_printers)
--> 481             printer.pretty(obj)
    482             printer.flush()
    483             return stream.getvalue()

/usr/local/lib/python2.7/dist-packages/IPython/lib/pretty.pyc in pretty(self, obj)
    360                             if callable(meth):
    361                                 return meth(obj, self, cycle)
--> 362             return _default_pprint(obj, self, cycle)
    363         finally:
    364             self.end_group()

/usr/local/lib/python2.7/dist-packages/IPython/lib/pretty.pyc in _default_pprint(obj, p, cycle)
    480     if getattr(klass, '__repr__', None) not in _baseclass_reprs:
    481         # A user-provided repr.
--> 482         p.text(repr(obj))
    483         return
    484     p.begin_group(1, '<')

/usr/local/lib/python2.7/dist-packages/geopy/point.pyc in __repr__(self)
    149 
    150     def __repr__(self):
--> 151         return "Point(%r, %r, %r)" % (self._items)
    152 
    153     def format(self, altitude=None, deg_char='', min_char='m', sec_char='s'):

TypeError: not enough arguments for format string

Python3 incompatibility

Hi there,

Thanks for the amazing library.
The latest merge breaks python3 compatibility. Line 69 to 74 should look like this:

    if hasattr(page.headers, "getparam"): # urllib
        encoding = page.headers.getparam("charset") or "iso-8859-1"
    else: # requests?
        encoding = page.headers.get("charset") or "iso-8859-1"

    return str(page.read(), encoding=encoding).encode('utf-8')

Find venues near an address

Thanks for the great tool! I have looked at the documentations but still there are some questions with regard to what can geopy achieve now and what can be added to it (if a service is already available).
Looking at geocoder it seems some services can be used to return venues near an address,

  • Is it possible to do a similar search (find venues) using geopy?
  • Specially is it possible to get list of e.g. restaurants near some latitude, longitude?
  • If geopy does not have this options, is it possible to do in theory?

geopy.geocoders.Nominatim geocode() result fails to __repr__ itself

import geopy.geocoders

text = u'Po\u015bpiecha 22, Zabrze, Poland'
geocoder = geopy.geocoders.Nominatim(timeout=10.0, )
locs = geocoder.geocode(text, exactly_one=False)
loc = locs[0]
print "loc.address: %r" % (loc.address, )
repr_locs = repr(locs)

loc.address: u'22, Ksi\u0119dza Paw\u0142a Po\u015bpiecha, Centrum Po\u0142udnie, Zabrze, wojew\xf3dztwo \u015bl\u0105skie, 41-800, Polska'

Traceback (most recent call last):

File "bug.py", line 9, in

repr_locs = repr(locs)

UnicodeEncodeError: 'ascii' codec can't encode character u'\u0119' in position 16: # ordinal not in range(128)

BUG-report: Distance computation fails for valid geo. coordinates!

REWRITTEN 06.12.2013 (simpler description, improved mini-example, bugfix in mini-example)
UPDATED 31.12.2013 (revisit after changes in version 0.96.3, improved mini-example, used version 0.97)

For a couple of valid geo-coordinates distance-computations raise exception. This seems to me like a bug.

In the provided example code below, we have two lists of pairs of coordinates: list "a" geopy.distance.ELLIPSOIDS fails and list "b" fails both.

See my mini-example:

import pprint
import geopy
import geopy.distance


# format: list of point pairs
#   each point is specified as (lat, long)
#
# lat n/s: [90, -90]
# long w/e: [180, -180]
#
a = [[(6.5, -4.5),(-5.5, 176.5)],
[(37.5, 121.5),(-37.5, -58.5)],
[(-11.5, -77.5),(10.5, 103.5)],
[(-33.5, -58.5),(33.5, 121.5)],
[(6.5, -55.5),(-7.5, 123.5)],
[(31.5, 120.5),(-31.5, -59.5)],
[(32.5, 121.5),(-32.5, -58.5)],
[(-7.5, -79.5),(8.5, 99.5)],
[(-12.5, -171.5),(13.5, 7.5)],
[(-4.5, 106.5),(5.5, -74.5)]]

b = [[(-5.5, -79.5),(5.5, 100.5)],
[(-2.5, -59.5),(2.5, 120.5)],
[(5.5, -74.5),(-5.5, 105.5)],
[(-2.5, -52.5),(2.5, 127.5)],
[(2.5, 100.5),(-2.5, -79.5)],
[(-5.5, 106.5),(5.5, -73.5)],
[(-2.5, 104.5),(2.5, -75.5)],
[(-5.5, 116.5),(5.5, -63.5)],
[(-5.5, 121.5),(5.5, -58.5)]]

distance_variants = geopy.distance.ELLIPSOIDS.keys() + ['great_circle']


def check(points, variants):
    """ first checks geopy.Point conversion and then different variants of distance computation"""
    (lat1, long1), (lat2, long2) = points
    p1 = geopy.Point(lat1, long1)
    p2 = geopy.Point(lat2, long2)

    testlat1, testlong1, _ = p1
    testlat2, testlong2, _ = p2

    if (testlat1, testlong1) != (lat1, long1):
        print "ERROR: (%s, %s) = geopy.Point(%s,%s)" % (testlat1, testlong1, lat1, long1)
        return

    if (testlat2, testlong2) != (lat2, long2):
        print "ERROR: (%s, %s) = geopy.Point(%s,%s)" % (testlat1, testlong1, lat1, long1)
        return

    print "Distance in km between %r <-> %r" % (p1, p2)
    for dv in variants:
        res = ""
        if dv == "great_circle":
            try:
                res = geopy.distance.great_circle(p1,p2).km
            except Exception, e:
                res = "ERROR: " + str(e)
        else:
            for iterations in (20, 40, 80, 160, 320, 640, 1280, 2560, 5120, 10240, 20480, 40960, 81920, 163840, 327680):
                try:
                    res = geopy.distance.distance(p1,p2,ellipsoid=dv,iterations=iterations).km
                    res = "%s km  (iterations=%s)" % (res, iterations)
                    break
                except Exception, e:
                    res = "ERROR: %s  (iterations=%s)" % (e, iterations)
        print "%20s : %s" % (dv, res)


print "ERRORS in geopy.distance.ELLIPSOIDS (distance in km)"
for item in a:
    check(item, distance_variants)

print "ERRORS in geopy.distance.great_circle (distance in km)"
for item in b:
    check(item, distance_variants)

results in:

Distance in km between Point(6.5, -4.5, 0.0) <-> Point(-5.5, 176.5, 0.0)
       Clarke (1880) : 19860.699201 km  (iterations=40)
              GRS-67 : 19860.7928533 km  (iterations=20)
         Airy (1830) : 19859.0166797 km  (iterations=20)
              WGS-84 : 19860.7217849 km  (iterations=20)
              GRS-80 : 19860.7217848 km  (iterations=20)
           Intl 1924 : 19861.4071186 km  (iterations=20)
        great_circle : 19863.8595647
Distance in km between Point(37.5, 121.5, 0.0) <-> Point(-37.5, -58.5, 0.0)
       Clarke (1880) : ERROR: Vincenty formula failed to converge!  (iterations=327680)
              GRS-67 : ERROR: Vincenty formula failed to converge!  (iterations=327680)
         Airy (1830) : ERROR: Vincenty formula failed to converge!  (iterations=327680)
              WGS-84 : ERROR: Vincenty formula failed to converge!  (iterations=327680)
              GRS-80 : ERROR: Vincenty formula failed to converge!  (iterations=327680)
           Intl 1924 : ERROR: Vincenty formula failed to converge!  (iterations=327680)
        great_circle : 20020.7259548
...
ERRORS in geopy.distance.great_circle (distance in km)
Distance in km between Point(-5.5, -79.5, 0.0) <-> Point(5.5, 100.5, 0.0)
       Clarke (1880) : ERROR: Vincenty formula failed to converge!  (iterations=327680)
              GRS-67 : ERROR: Vincenty formula failed to converge!  (iterations=327680)
         Airy (1830) : ERROR: Vincenty formula failed to converge!  (iterations=327680)
              WGS-84 : ERROR: Vincenty formula failed to converge!  (iterations=327680)
              GRS-80 : ERROR: Vincenty formula failed to converge!  (iterations=327680)
           Intl 1924 : ERROR: Vincenty formula failed to converge!  (iterations=327680)
        great_circle : 20020.7259548
...

(CHANGED: Test script now dry increasing number of iterations to obtain solution for a distance.)

(MacOSX, Version geopy-0.97-py2.7.egg)

Observations:

  • Great circle distance: Math-exception is fixed; all coordinates in example work
  • Ellipsoid computation: Increasing the iterations only work for Clarke-Approximation (for the example coordinates).
    A dramatic increase of the number of iterations doesn't really help. This hints (at least for me) towards a floating point issue.
  • Used coordinates are valid and distance between them should work.
    (Updated bug summary)

Please help on this topic.
Thank you for your help so far.

Add customized http request User-Agent header

My application that uses geopy was blocked by Nominatim as geopy uses the standard user agent header for requests provided by urllib (Python-urllib/2.7). Nominatim requires to add an identifying user agent header per application in order to be able to track and block requests if needed.

In PR #115 I added such functionality, every request for all geocoders will identify with User-Agent: geopy/VERSION. In the Nominatim geocoder one can choose an arbitrary customized user agent header.

Smartystreets wrong api address

Hi,

I think the smartystreets api address changed.. and it's not correct on the code. I think the new SmartyStreets API url is: api.smartystreets.com/street-address

Documentation on class names is outdated

Hi, just a quick issue that may cause confusion if users aren't familiar with modules, but the web documentation on how to import modules is outdated - geopy's distance function examples call the old names (vincenty, greatercircles) and not the current ones (i.e. now you need to write "from geopy.distance import VincentyDistance").

Nominatim always return "None"

I am trying to use OSM but I always get "None" on the result

from geopy.geocoders import Nominatim

geolocator = Nominatim()

address, (latitude, longitude) = geolocator.geocode('Avenida Paulista, Cerqueira Cesar Sao Paulo')

I got this error:

TypeError: 'NoneType' object is not iterable

How to choose which geocoding provider to use?

There are a lot of provider options to chose from, but there is nothing in the documentation to suggest a reason for using any one of them in particular. Are some of the providers more accurate? Are some faster? Are some of them more rate limited than others?

new to geopy, wanting timezone api

Can I use geopy for timezone api from geonames (and google)?

I just used geopy, and google v3 to get longitude and latitude, for an address
but now I want to get timezone too

I looked around, and there seem to be 3 possibilities I consider

  1. geonames timezone api (again, im not sure geopy does it)
  2. google timezone api (i dont see any python module for it)
  3. tzwhere (but I would like a web service)

I would love to stick to geopy for timezones too
but I dont know if geopy has this capability...

No module named geocoders

from geopy.geocoders import Nominatim

g = Nominatim()

def find():

query = raw_input('What would you like to search')

place = g.geocode(query)

print place.address
print place.latitude, place.longitude

find()

I have installed geopy==1.9.1 but still it is showing me this error

placefinder.py SyntaxEror

Python3.2 on windows 7

C:\Windows\System32>pip install geopy
Downloading/unpacking geopy
Real name of requirement geopy is geopy
Downloading geopy-1.0.1.tar.gz (71Kb): 71Kb downloaded
Running setup.py egg_info for package geopy

warning: no previously-included files matching '*' found under directory 'test'
no previously-included directories found matching 'geopy\__pycache__'
no previously-included directories found matching 'geopy\geocoders\__pycache__'

Installing collected packages: geopy
Running setup.py install for geopy
File "C:\Python32\Lib\site-packages\geopy\geocoders\placefinder.py", line 72
url = u'?'.join((
^
SyntaxError: invalid syntax

warning: no previously-included files matching '*' found under directory 'test'
no previously-included directories found matching 'geopy\__pycache__'
no previously-included directories found matching 'geopy\geocoders\__pycache__'

Successfully installed geopy
Cleaning up...

run python3 and import geopy:
Python 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)] on win
32
Type "help", "copyright", "credits" or "license" for more information.

import geopy
Traceback (most recent call last):
File "", line 1, in
File "geopy__init__.py", line 11, in
from geopy.geocoders import * # pylint: disable=W0401
File "geopy\geocoders__init__.py", line 71, in
from geopy.geocoders.placefinder import YahooPlaceFinder
File "geopy\geocoders\placefinder.py", line 72
url = u'?'.join((
^
SyntaxError: invalid syntax

please help.

Thanks,
Sean

Python 2.6 supported?

Is Python 2.6 supported? I see in format.py we use dict comprehensions which are only available in 2.7+

If Python 2.6 is not supported, can we please document the versions of Python that are supported in the docs and the README?

Altitude not printed in formatted Point

When you print out a point, it leaves out the altitude.:

>>> import geopy
>>> pt=geopy.Point(latitude=41.5, longitude=81.0, altitude=2.5)
>>> pt
Point(41.5, 81.0, 2.5)
>>> pt.altitude
2.5
>>> pt.format()
'41 30m 0s N, 81 0m 0s E, km'

The bug is that geopy/point.py:Point.format_altitude needs to specify the keyword 'unit' as the argument to format_distance, because when calling using positional args, it is using overwriting the format instead. i.e. at line geopy/point.py:196, change:

    def format_altitude(self, unit='km'):
        return format_distance(self.altitude, unit)

to

    def format_altitude(self, unit='km'):
        return format_distance(self.altitude, unit=unit)

ArcGIS reverse WKID failure

nosetests -v test.test_backends:ArcGISTestCase.test_reverse_wkid

FAIL: ArcGIS.reverse with non-default WKID
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/projects/geopy/test/test_backends.py", line 350, in test_reverse_wkid
    self.assertAlmostEqual(coords[0], known_coords[0], delta=self.delta_inexact)
AssertionError: -15.545442684553564 != 4976084.454557315 within 0.02 delta

Aeronautical co-ordinates format Nddmmss.ss Wdddmmss.ss

In many aeronautical publications (such as the UK AIP - http://www.ais.org.uk) the co-ordinate system used is Nddmmss.ss Wdddmmss.ss with or without the decimal seconds.

When passed to Point as a string, the whole gets interpreted as degrees and then converted back to 360/180 degrees as (normally) appropriate.

Is this a co-ordinate system that can be added to geopy?

I have a patch for the parse_degrees class method of the Point class which checks the format and splits it up appropriately, but I'm not sure if this is the right place.

Return Bounds or Viewport to Estimate Coding Precision

When you geocode place names with different levels of specificity (ie, 'United States' vs. 'Cambridge MA', it is helpful to know the precision of the geocoder's response, in addition to just the single point representative of that region. One way to do this is to look at the bounds, or the viewport that contains the region of interest. For example, Google offers the 'northeast' and 'southwest' corners of the region:

Is there a simple way to include these outputs in the geocode response?

UnicodeEncodeError: if I the street has diacritics in it's name.

If I try to geocode
geolocator.geocode("Jindricha Plachty 5, Praha") street name is "Jindřicha Plachty"
I got
Traceback (most recent call last):
File "", line 1, in
UnicodeEncodeError: 'ascii' codec can't encode character u'\u0159' in position 13: ordinal not in range(128)

Return location objects with more information

Instead of returning a tuple, geocoders should return an object that can be iterated through the same for backwards compatibility, but also exposes the details of services' responses, e.g, specific address fields, administrative division types, on a per-geocoder basis.

more info

Can I use this code for free in my application? Are there any licensing issues involved?

GoogleV3 geocode should allow no `query` parameter

According to the Google Geocoding API:

Using the components filter it is possible to make a query without the address parameter, but you cannot specify a component without a value. Request:

https://maps.googleapis.com/maps/api/geocode/json?components=route:Annegatan|administrative_area:Helsinki|country:Finland&key=API_KEY

geocode should be able to be called without having to specify the query (address):

location = geolocator.geocode(components={'city': 'Paris', 'country': 'FR'})

Error in geocoding example in README?

The first example in the README for v1.1.0 appears to have an error. If I run the example verbatim from the README, I get:

geolocator = Nominatim()
location = geolocator.geocode("175 5th Avenue NYC")
Traceback (most recent call last):
File "", line 1, in
File "/sw/lib/python2.7/site-packages/geopy/geocoders/osm.py", line 192, in geocode
self._call_geocoder(url, timeout=timeout), exactly_one
File "/sw/lib/python2.7/site-packages/geopy/geocoders/base.py", line 160, in _call_geocoder
raise GeocoderServiceError(message)
geopy.exc.GeocoderServiceError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>

The example works without error if I add "scheme='http'" to the call to Nominatim(). E.g.

geolocator = Nominatim(scheme='http')
location = geolocator.geocode("175 5th Avenue NYC")
print(location.address)
Flatiron Building, 175, 5th Avenue, Flatiron, New York, NYC, New York, 10010, United States of America

Google geocoder should accept API key

According to Google Geocoder docs as of 2/18/2014:

"All Geocoding API applications should use an API key."

Also, if you have multiple users from the same IP using the API, without the API key, you will get shut down almost immediately.

Pull request to follow shortly.

Mapquest Geocoder format_string

In the Mapquest API the input for format_string is never used in the geocode process. When geocoding, only

query

is used and not

self.format_string % query

as I believe was intended.

In the geocode function of the mapquest api:

params = {
   'location' : query
}

should be:

params = {
   'location' : self.format_string % query
}

Insufficient Priveleges for Nominatim

When using Nominatim, we get an geopy.exc.GeocoderInsufficientPrivileges exception, even though Nominatim should not require account credentials:

>>> geolocator = Nominatim()
>>> geolocator.geocode("Washington, DC", timeout=10) 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/geopy/geocoders/osm.py", line 191, in geocode
    self._call_geocoder(url, timeout=timeout), exactly_one
  File "/usr/local/lib/python2.7/dist-packages/geopy/geocoders/base.py", line 147, in _call_geocoder
    raise ERROR_CODE_MAP[code](message)
geopy.exc.GeocoderInsufficientPrivileges: HTTP Error 403: Forbidden

Can anyone else confirm?

GoogleV3.timezone doesn't return DST information

The pytz timezone returned from the timezone() method ignores the daylight savings information that's in the API response. At this point in the code: https://github.com/geopy/geopy/blob/master/geopy/geocoders/googlev3.py#L319

Only the timeZoneId is taken into account, yet the API response contains the appropriate DST info:

{u'status': u'OK', u'dstOffset': 3600, u'rawOffset': 0, u'timeZoneName': u'British Summer Time', u'timeZoneId': u'Europe/London'}

It would be awesome if the DST information could also be applied to the result. Thanks!

Geocoding Queue That Respects Rate Limits?

First of all, I love this package. Many thanks to the contributors and maintainers.

While using it, I've found myself building a simple wrapper class that geocodes a list of addresses and enforces a per-second rate limit (the actual version that I'm using has a few more bells and whistles, but this is the basic idea). The resulting object takes a geocoder object and uses the geopy api (namely calling a geocode method on the geocoder and passing in an address from the given list).

Would a pull request to add such a class be welcome?

Bing structured query does not work

Hi,

I've noticed the structured query for bing maps does not work. The unit tests are passing, because it ignores the unit test when the API returns nothing.

Steps to reproduce:

ipython
import geopy
key = 'YOURAPIKEY'
print geopy.geocoders.Bing(key).geocode({'postalCode': '80020', 'countryRegion':'United States'})
None
print geopy.geocoders.Bing(key).geocode('80020 United States')
Broomfield, CO 80020, United States

bounds breaks opencage geocoder

This test code fragment works, yielding a geolocation (43.074718, -89.386238)

from geopy.geocoders import OpenCage
query = "100 State St, Madison WI 53711, USA";
geolocator = OpenCage(key, timeout=3600)
location = geolocator.geocode(query,exactly_one=True,
#                              bounds="42.8448769,-89.8394169,43.2940373,-89.0094259",
                              country="USA"
                              )
print (location.address)

but if I uncomment the bounds line the search comes up empty and the subsequent attempt to use the search result errors out:

Traceback (most recent call last):
  File "test_geopy.py", line 39, in <module>
    print (location.address)
AttributeError: 'NoneType' object has no attribute 'address'

Geopy with Nominatim doesn't work

I am trying to geocode the following address:

geolocatorNominatim.geocode('Av. Universidad, Coyoacán, Mexico City, Federal District, 01090, Mexico')

The error I am getting is the following:

   print geolocatorNominatim.geocode('Av. Universidad, Coyoacán, Mexico City, Federal District, 01090, Mexico')
  File "/usr/local/lib/python2.7/site-packages/geopy/geocoders/osm.py", line 176, in geocode
    self._call_geocoder(url, timeout=timeout), exactly_one
  File "/usr/local/lib/python2.7/site-packages/geopy/geocoders/base.py", line 156, in _call_geocoder
    raise GeocoderTimedOut('Service timed out')
geopy.exc.GeocoderTimedOut: Service timed out

Can someone reproduce that?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.