def get_postalcode(placename, err=0.5): # Error radius is 0.5 km geo = GeoNames(GEONAMES_SERVER, GEONAMES_USERNAME) response = geo.request('findNearbyPostalCodes', style='short', country='US', radius=err, placename=placename) if response: res = etree.parse(response) postals = [elmt.text for elmt in res.xpath('/geonames/code/postalcode')] if postals == []: return 'No postal code can be found for a place' return postals else: return 'No response from GeoNames'
def get_place_nearby(lat, lng, radius, num_rslt=10): geo = GeoNames(GEONAMES_SERVER, GEONAMES_USERNAME) response = geo.request('findNearbyPlaceName', style='short', lat=lat, lng=lng, maxRows=num_rslt, radius=radius) if response: res = etree.parse(response) placenames = [elmt.text for elmt in res.xpath('/geonames/geoname/toponymName')] if placenames == []: return 'No nearby place can be found for the search term' return placenames else: return 'No response from GeoNames'
def get_coordinate(name_code, err=0.5): # Error radius is 0.5 km geo = GeoNames(GEONAMES_SERVER, GEONAMES_USERNAME) try: int(name_code) response = geo.request('findNearbyPostalCodes', style='short', country='US', radius=err, postalcode=name_code) except ValueError: response = geo.request('findNearbyPostalCodes', style='short', country='US', radius=err, placename=name_code) if response: res = etree.parse(response) lats = [float(elmt.text) for elmt in res.xpath('/geonames/code/lat')] lngs = [float(elmt.text) for elmt in res.xpath('/geonames/code/lng')] if lats == [] or lngs == []: return 'No place can be found for the search term' return zip(lats, lngs) else: return 'No response from GeoNames'