Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def address_from_latlong(latlong):
"""Reverse geocode the given latitude and longitude.
`latlong` must be a string with two floats separated by a comma+space,
like: "44.842, -84.238".
Returns empty string on failure.
"""
if not latlong or type(latlong) not in utils.string_types:
return ''
point = latlong.split(', ')
if len(point) != 2:
return ''
geocoder = geopy.geocoders.GoogleV3(config.GOOGLE_SERVER_API_KEY)
res = None
try:
res = geocoder.reverse(point)
except Exception, e:
logging.error('Geocoder exception', exc_info=e)
if not res:
return ''
return res[0].address
def __init__(self, locationLookup, geo_key, noop=False):
# Blank location
if noop:
self.noop = True
self.geo_key = None
self.locator = None
self.latitude = None
self.longitude = None
self.altitude = None
return
self.noop = False
self.geo_key = geo_key
self.locator = GoogleV3()
if geo_key:
self.locator = GoogleV3(api_key=geo_key)
self.latitude, self.longitude, self.altitude = self.setLocation(locationLookup)
def set_location(location_name):
geolocator = GoogleV3()
loc = geolocator.geocode(location_name)
print('[!] Your given location: {}'.format(loc.address.encode('utf-8')))
print('[!] lat/long/alt: {} {} {}'.format(loc.latitude, loc.longitude, loc.altitude))
set_location_coords(loc.latitude, loc.longitude, loc.altitude)
def getGoogleResults(place_name):
if hasattr(settings, 'GOOGLE_SECRET_KEY'):
g = geocoders.GoogleV3(
client_id=settings.GOOGLE_API_KEY,
secret_key=settings.GOOGLE_SECRET_KEY
)
else:
g = geocoders.GoogleV3()
try:
results = g.geocode(place_name, exactly_one=False)
formatted_results = []
for result in results:
formatted_results.append(formatExternalGeocode('Google', result))
return formatted_results
except Exception:
return []
def _get_pos_by_name(self, location_name):
geolocator = GoogleV3(api_key=self.config.gmapkey)
loc = geolocator.geocode(location_name)
#self.log.info('Your given location: %s', loc.address.encode('utf-8'))
#self.log.info('lat/long/alt: %s %s %s', loc.latitude, loc.longitude, loc.altitude)
return (loc.latitude, loc.longitude, loc.altitude)
exp.expenseitem_set.create(name=it, price=price)
return exp
total = property(_get_total)
class ExpenseItem(models.Model):
name = models.CharField(max_length=50)
price = models.DecimalField(decimal_places=2, max_digits=10)
category = models.CharField(max_length=50, blank=True)
expense = models.ForeignKey(Expense, null=True, default=None)
def __unicode__(self):
return self.name + " for " + str(self.price)
geolocator = GoogleV3()
@receiver(pre_save, sender=Shop)
def my_handler(sender, instance, **kwargs):
"""
When editing a shop, do a geocoding request if address changed
"""
print(instance)
try:
obj = Shop.objects.get(pk=instance.pk)
except Shop.DoesNotExist:
try:
address, (latitude, longitude) = geolocator.geocode(instance.address, exactly_one=False)[0]
instance.lat = latitude
instance.lon = longitude
except GQueryError:
pass
return
def addresses_to_coords(self, addrs):
cachefn = os.path.join(self.cache, "address_coords.json")
coordmap = {}
if os.path.exists(cachefn):
with open(cachefn) as f:
try:
coordmap = json.load(f)
except:
coordmap = {}
g = geopy.geocoders.GoogleV3()
for addr in addrs:
if addr not in coordmap:
resp = g.geocode("%s, WASHINGTON, DC" % addr)
if resp is not None:
_, coord = resp
coordmap[addr] = coord
with open(cachefn, 'w') as f:
json.dump(coordmap, f)
return [coordmap[addr] for addr in addrs if coordmap[addr] is not None]
def nearby_locations(self, zipcode, count=None):
"""
Returns locations that fall inside zipcode.
If we can't find any in that zipcode, look within a 3-mile radius.
"""
locations = Location.objects.filter(zip=zipcode, accepted=True)[:count]
if len(locations) == 0:
try:
geocoder = geocoders.GoogleV3()
address, (lat, lng) = geocoder.geocode(zipcode, exactly_one=True)
origin = GEOSGeometry('POINT(%f %f)' % (lng, lat,))
locations = Location.objects.filter(geom__distance_lte=(origin, D(mi=3))).distance(origin).order_by('distance')[:8]
except:
pass
return locations