本文整理汇总了Python中pygeocoder.Geocoder.reverse_geocode方法的典型用法代码示例。如果您正苦于以下问题:Python Geocoder.reverse_geocode方法的具体用法?Python Geocoder.reverse_geocode怎么用?Python Geocoder.reverse_geocode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pygeocoder.Geocoder
的用法示例。
在下文中一共展示了Geocoder.reverse_geocode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_reverse_geo
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def get_reverse_geo(self,fileWithCoords):
from pygeocoder import Geocoder # sudo port select python python26
#fileWithAddresses='/Users/admin/Desktop/work_locations.txt'
f=open(fileWithCoords,'r')
x=f.read()
f.close()
z=x.split('\r')
pt=0
for i in range(0,len(z)):
a=z[i].split('\t')
print Geocoder.reverse_geocode(eval(a[0]),eval(a[1]))
pt+=1
if pt==10:
sleep(10)
pt=0
示例2: test_reverse_geocode
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def test_reverse_geocode(self):
"""
Test pygeocoder reverse_geocode()
"""
lat, lng = 38.897096, -77.036545
result = Geocoder.reverse_geocode(lat, lng)
self.assertEqual(result.country__short_name, 'US')
self.assertEqual(result.postal_code, '20500')
self.assertEqual(result.street_number, '1600')
self.assertEqual(result.route, 'Pennsylvania Avenue Northwest')
self.assertEqual(result.administrative_area_level_1, 'District of Columbia')
self.assertEqual(result.city, 'Washington, D.C.')
self.assertEqual(result.state, 'District of Columbia')
self.assertEqual(result.state__short_name, 'DC')
self.assertEqual(result.country, 'United States')
addr = result.formatted_address
self.assertEqual(addr, "1600 Pennsylvania Avenue Northwest, President's Park, Washington, D.C., DC 20500, USA")
lat2, lng2 = result.coordinates
self.assertAlmostEqual(lat, lat2, 3)
self.assertAlmostEqual(lng, lng2, 3)
self.assertAlmostEqual(lat, result.latitude, 3)
self.assertAlmostEqual(lng, result.longitude, 3)
self.assertTrue(result.count > 1)
示例3: get_geolocation_by_latlong
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def get_geolocation_by_latlong(latitude, longitude):
# call google geolocation service to get the location detail
results = Geocoder.reverse_geocode(latitude, longitude)
if results is not None and len(results) > 0:
google_location = results.raw[0]
location = Geolocation()
location.latitude = google_location['geometry']['location']['lat']
location.longitude = google_location['geometry']['location']['lng']
address_components = google_location['address_components']
for component in address_components:
if 'street_number' in component['types']:
location.street_num = component['long_name']
if 'route' in component['types']:
location.street_name = component['long_name']
if 'neighborhood' in component['types']:
location.lv1_district = component['long_name']
if 'locality' in component['types']:
location.city = component['long_name']
if 'administrative_area_level_1' in component['types']:
location.state = component['long_name']
if 'country' in component['types']:
location.country = component['long_name']
if 'postal_code' in component['types']:
location.zipcode = component['long_name']
return location
else:
return None
示例4: fetch_geo_details
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def fetch_geo_details(garden):
"""Reverse geocode to get garden's state, city, etc"""
results = Geocoder.reverse_geocode(garden.latitude, garden.longitude)
address_components = results[0].data[0]['address_components']
for component in address_components:
# Borough
if 'sublocality' in component['types']:
borough = component['long_name']
if not garden.borough and borough in [b[0] for b in Garden.BOROUGH_CHOICES]:
garden.borough = component['long_name']
# City
if 'locality' in component['types']:
if not garden.city:
garden.city = component['long_name']
# State
if 'administrative_area_level_1' in component['types']:
if not garden.state:
garden.state = component['short_name']
# Zip
if 'postal_code' in component['types']:
if not garden.zip:
garden.zip = component['long_name']
garden.save()
示例5: sos
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def sos():
data = json.loads(request.data)
name = data.get('name').upper()
lat = data.get('lat')
lng = data.get('lng')
description = data.get('description')
feed = Feed.query.filter(Feed.name==name, Feed.lat==lat, Feed.lng==lng,
Feed.state=='open').first()
result = None
if not feed:
try:
address = Geocoder.reverse_geocode(float(lat), float(lng))[0]
new_feed = Feed(name=name, lat=lat, lng=lng, address=address,
description=description)
db_session.add(new_feed)
db_session.commit()
result = {
'id': new_feed.id,
'lat': new_feed.lat,
'lng': new_feed.lng,
'createdAt':
new_feed.created_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
'name': new_feed.name,
'description': new_feed.description,
'state': new_feed.state
}
except:
result = { 'error_msg': 'DB Error' }
finally:
db_session.remove()
else:
result = {
'error_msg': 'Entry exists.'
}
return jsonify(result)
示例6: google_geotag_file
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def google_geotag_file(ifile):
print "\nGoogle:"
file_phi_psi = get_lat_long_file(ifile)
location = Geocoder.reverse_geocode(math.degrees(file_phi_psi.latitude()), math.degrees(file_phi_psi.longitude()))
admin = "administrative_area_level_"
location_attributes = list()
location_attributes.append(["country", "Country ","-country="])
location_attributes.append([admin + "1", "State ","-state="])
location_attributes.append(["locality", "City ","-city="])
location_attributes.append(["postal_code", "Zip Code ", "-Keywords+="])
location_attributes.append(["neighborhood", "Neighborhood ", "-Keywords+="]) # UWS
location_attributes.append(["political", "City? ", ""]) # great falls/uws
location_attributes.append([admin + "2", "County ", ""]) # county
location_attributes.append([admin + "3", "District ", ""]) # district?
location_attributes.append(["sublocality", "Sublocality ", ""]) # manhattan
location_attributes.append(["airport", "Airport ", ""])
location_attributes.append(["park", "Park ", ""])
location_attributes.append(["natural_feature", "Natural Feature ", ""])
location_attributes.append(["point_of_interest", "Point of Interest", ""])
location_attributes.append(["street_address", "Street Address ", ""])
location_attributes.append(["route", "Road ", ""])
location_attributes.append(["intersection", "Intersection ", ""])
location_attributes.append(["colloquial_area", "Colloquial Area ", ""])
location_attributes.append(["premise", "Premise ", ""])
location_attributes.append(["subpremise", "Subpremise ", ""])
for i in location_attributes[:5]:
this_attr = getattr(location[0], i[0])
if(this_attr != None):
print i[1], "\t", this_attr
示例7: coordinate_generator
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def coordinate_generator(number_of_points):
"""
Generate a number of random geographical points and then geocode them.
:param number_of_points: number of points to generate
:type number_of_points: int
:return: list of geographic point tuples
"""
coordinate_list = []
counter = 0
geocoder = Geocoder()
while counter < number_of_points:
lat = round(random.uniform(SOUTHERNMOST, NORTHERNMOST), 6)
lng = round(random.uniform(EASTERNMOST, WESTERNMOST), 6)
try:
gcode = geocoder.reverse_geocode(lat, lng)
if gcode[0].data[0]['formatted_address'][-6:] in ('Canada', 'Mexico'):
continue
elif 'unnamed road' in gcode[0].data[0]['formatted_address']:
continue
elif 'Unnamed Road' in gcode[0].data[0]['formatted_address']:
continue
else:
counter += 1
coordinate_list.append((gcode[0].coordinates, gcode[0].formatted_address))
# output_file.write(fullstring.format(gcode.x, gcode.y, gcode.address))
except GeocoderError:
continue
print 'Finished generating %d coordinate points' % counter
return coordinate_list
示例8: address_from_latlong
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def address_from_latlong(latitude, longitude):
"""Get human-readable address from (lat, long) location."""
try:
return Geocoder.reverse_geocode(latitude,longitude)[0]
except GeocoderError, e:
print "Error when converting address to (lat,long): %s" % e
return ''
示例9: detectCountry
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def detectCountry(lat,lng):
#url_geo = "http://ws.geonames.org/countryCode?lat=%s&lng=%s" %(lat,lng)
print "Detecting: ",lat,lng
results = Geocoder.reverse_geocode(lat, lng)
if "Brazil" == results:
results = "Brasil"
return results[0].country
示例10: generate_map_and_desc
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def generate_map_and_desc(gps_data,mode,marker_list):
ischina=False
api_key='AIzaSyBepV-5hoVd8xzwkdE93I0eRKf2jTlys3U'
gmaps = GoogleMaps(api_key)
gps=gps_data
try:
result = Geocoder.reverse_geocode(gps_data[0],gps_data[1])
destination = str(result)
except:
destination = 'N/A'
if mode==0:
dmap=DecoratedMap(size_x=400,size_y=400)
else:
dmap=DecoratedMap(size_x=400,size_y=400, maptype='satellite')
dmap.add_marker(LatLonMarker(lat=gps[0],lon=gps[1],label='A'))
for i in range(0, len(marker_list)):
dmap.add_marker(LatLonMarker(lat=marker_list[i][0],lon=marker_list[i][1],label=chr(66+i)))
cmap = CenterMap(lat=gps[0],lon=gps[1], zoom=12)
map_url=dmap.generate_url()
print(map_url)
f=open('tmp.png','wr')
f.write(urllib.urlopen(map_url).read())
f.close()
return destination
示例11: get_happiest_state
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def get_happiest_state(tweet_stream):
elements = {}
tweets_stream_file = open(tweet_stream)
for tweets_lines in tweets_stream_file:
# load the json data of tweet streams
tweetJSON=json.loads(tweets_lines)
#print tweetJSON
# iterate over each data in each tweets
for (key, value) in tweetJSON.items():
initial_score=1
## Analysing the user's location data against the cities in the United States
#'''
# using the geocoder from google map api (http://code.xster.net/pygeocoder/wiki/Home)
if key == 'coordinates' and tweetJSON['coordinates'] is not None:
geo_coordinate = value['coordinates'];
longitude = geo_coordinate[0]
latitude = geo_coordinate[1]
location=Geocoder.reverse_geocode(latitude, longitude)
print location
#https://dev.twitter.com/docs/platform-objects/tweets
# using the place hash in the tweet stream
elif key == 'place' and tweetJSON['place'] is not None:
if value["country"] == "United States" or value["country_code"] == "US":
# print value["name"]
if elements.has_key(value["name"]):
elements[value["name"]] += int(initial_score)
elements[value["country"]] = initial_score
# using the user hash in the tweet stream
elif key == 'user':
print "value"
示例12: get_rev_address
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def get_rev_address(lat, lng,method="geopy", district_only=False):
string=lat+','+lng
if 'geopy' in method:
location = geolocator.reverse(string)
return location.address
else:
lat=float(lat)
lng=float(lng)
#print str(lat)+" , "+ str(lng)
results=""
try:
rs=Geocoder.reverse_geocode(lat,lng)
except:
results=""
try:
results+="city:"
results+=rs.city
except:
results+=""
try:
results+=",district:"
results+=rs.county
except:
results+=""
try:
results+=",raw:"+rs.__str__()
except:
results+=""
if district_only:
return rs.county
return results
示例13: clean
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def clean(self):
cleaned_data = super(PointImportForm, self).clean()
lat, lon = cleaned_data.get('latitude'), cleaned_data.get('longitude')
# point geometry
geometry = cleaned_data.get('geometry')
if not geometry:
if not all((lat, lon)):
raise forms.ValidationError('Geometry fields require latitude and longitude')
geometry_field = self.fields['geometry']
pnt = geos.Point(lon, lat, srid=geometry_field.srid)
cleaned_data['geometry'] = geometry_field.clean(pnt)
# zipcode geocode
zipcode = cleaned_data.get('zip')
if not zipcode:
if not all((lat, lon)):
raise forms.ValidationError('Zipcode fields require latitude and longitude')
key = hash((lat, lon))
result_data = self._cache.get(key)
if result_data:
result = GeocoderResult(result_data)
else:
result = Geocoder.reverse_geocode(lat=lat, lng=lon)
self._cache.set(key, result.data)
zipcode = result[0].postal_code
cleaned_data['zip'] = self.fields['zip'].clean(zipcode)
return cleaned_data
示例14: getState
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def getState(coords_list):
lat = coords_list[0]
log = coords_list[1]
address = Geocoder.reverse_geocode(lat, log)
state = address.state.encode('ascii', 'ignore')
if state in states.states.items():
return state
return None
示例15: tweet
# 需要导入模块: from pygeocoder import Geocoder [as 别名]
# 或者: from pygeocoder.Geocoder import reverse_geocode [as 别名]
def tweet():
args = get_args()
creds = load_credentials()
shortener = Shortener('Google', api_key=creds[0])
tweet = Twitter(auth=OAuth(creds[1], creds[2], creds[3], creds[4]))
url = "http://127.0.0.1:" + str(args.port) + "/raw_data"
response = urllib.urlopen(url)
dump = json.loads(response.read())
new = copy.deepcopy(dump)
old = {
'pokemons': []
}
if os.path.isfile('data.json'):
with open('data.json') as data_file:
old = json.load(data_file)
# Deletes encounter id for next step
for e_new in new['pokemons']:
for e_old in old['pokemons']:
if e_new['encounter_id'] == e_old['encounter_id']:
del e_new['encounter_id']
break
# Existing encounter ids are rare pokemon
# This entire step is to parse the data for a tweet
for e_new in new['pokemons']:
if e_new['pokemon_id'] in rares:
if 'encounter_id' in e_new:
location = str(Geocoder.reverse_geocode(e_new['latitude'], e_new['longitude'])[0]).split(',')
destination = location[0]
if len(location) == 5:
destination += ", " + location[1]
time = datetime.datetime.fromtimestamp(e_new['disappear_time']/1000)
ampm = "AM"
hour = time.hour
gmap = 'https://www.google.com/maps/dir/Current+Location/' \
+ str(e_new['latitude']) + ',' + str(e_new['longitude'])
if hour > 12:
hour -= 12
ampm = "PM"
elif hour == 12:
ampm = "PM"
elif hour == 0:
hour = 12
tweeting = "{} at {} until {}:{}:{} {}. #PokemonGo {}".format( \
e_new['pokemon_name'], destination, \
hour, str(time.minute).zfill(2), str(time.second).zfill(2), ampm, \
shortener.short(gmap))
tweet.statuses.update(status=tweeting)
print tweeting
# Google api timeout
t.sleep(0.5)
with open('data.json', 'w') as outfile:
json.dump(dump, outfile)