def google_v3(address): try: g = geocoders.GoogleV3(EASY_MAPS_GOOGLE_KEY) results = g.geocode(smart_str(address), exactly_one=False) if results is not None: return results[0] else: return "notfound" except (UnboundLocalError, ValueError, GeocoderServiceError) as e: return "notfound"
def gps_query(loc): """can throw GeopyError""" coder = geocoders.GoogleV3() partial = coder.geocode(loc, exactly_one=False) if (partial is None): result = None else: place, (lat, lon) = partial[0] result = {'lat': lat, 'lon': lon} return result
def geocode(): """ Geocode location """ data = json.loads(request.data) from geopy import geocoders g = geocoders.GoogleV3() place, (lat, lng) = g.geocode(data['location']) response_data = {'place': place, 'latitude': lat, 'longitude': lng} response = Response(json.dumps(response_data), status=200, mimetype='application/json') return response
def find_lat_lng(locations): g = geocoders.GoogleV3(domain='maps.google.pl') for l in locations: # location_coord is a list [location,coordintae] location_coord = g.geocode(l) # if coordintae found from 1st location done[pass] else continue loop if location_coord: pass # print(location_coord[1]) return location_coord[1]
def _load_name(self): from geopy import geocoders g = geocoders.GoogleV3() try: place, (lat, lng) = g.reverse((self.latitude, self.longitude), exactly_one=True) self.name = self._parse_place(place) except geopy.exc.GeocoderServiceError, e: self.name = 'Error'
def save(self, force_insert=False): location = "%s %s %s %s" % (self.street_address, self.city, self.state, self.zipcode) g = geocoders.GoogleV3() if not self.lat or not self.lng or not self.geo_address: geo_address, (lat, lng) = g.geocode("%s" %(location)) self.lat = lat self.lng = lng self.geo_address = geo_address super(Entry, self).save()
def rgeocode(): """ Reverse geocode location """ data = json.loads(request.data) from geopy import geocoders g = geocoders.GoogleV3() print(g.reverse((data['lat'], data['lon']), exactly_one=True)) place, (lat, lng) = g.reverse((data['lat'], data['lon']), exactly_one=True) response_data = {'place': parse_place(place), 'latitude': lat, 'longitude': lng} response = Response(json.dumps(response_data), status=200, mimetype='application/json') return response
def get_lat_long(address): res = {} try: g = geocoders.GoogleV3() #api_key=GOOGLE_MAPS_API_KEY) place, (lat, lng) = g.geocode(address) res['latitude'] = lat res['longitude'] = lng return res except Exception as e: print "%s , %s" % (e, address) return None
def gcode(address): """ takes an address and retrieves the latitude and longitude coordinates from the google maps geocoding service @param address - address in the format: " number road postcode" e.g. "23 Bay Tree Way RG215QG" @return tuple of the lat, long coordinates """ g = geocoders.GoogleV3(api_key='AIzaSyDT2i1GLDJsTZ_RD6H1HqWGAn1RpAXVZ3Y') inputAddress = address location = g.geocode(inputAddress, timeout=10) return (location.latitude, location.longitude)
def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google Geocoding API v3. """ try: g = geocoders.GoogleV3() address = smart_str(address) return g.geocode(address, exactly_one=False)[0] except (UnboundLocalError, ValueError, GeocoderResultError) as e: raise Error(e)
def getGoogleResults(place_name): g = geocoders.GoogleV3(client_id=settings.GOOGLE_API_KEY, secret_key=settings.GOOGLE_SECRET_KEY) if settings.GOOGLE_SECRET_KEY is not None else 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 start_geo_listener(address, rad): gc = geocoders.GoogleV3() place, (lat, lng) = gc.geocode(address) loc = [ bound(lng, lat, rad)[0], bound(lng, lat, rad)[1], bound(lng, lat, rad)[2], bound(lng, lat, rad)[3] ] twitterStream = Stream(auth, Geo_listener(), timeout=5000) twitterStream.filter(locations=loc)
def getTimePais(pais): try: g = geocoders.GoogleV3() place, (lat, lng) = g.geocode(pais) timezone = g.timezone((lat, lng)) # return pytz timezone object print(timezone.zone) now = datetime.now(pytz.timezone(timezone.zone)) # you could pass `timezone` object here print (now) return now, timezone.zone except ValueError: return " Hora sin poder consultar"
def create_success(request): if request.method == 'POST': event_form = EventForm() creator = request.POST['creator'] name = request.POST['name'] slug = request.POST['slug'] num_people = request.POST['num_people'] event_type = request.POST['event_type'] location_entry = str(request.POST['location']) try: geolocator = geocoders.GoogleV3() location, (lat, lng) = geolocator.geocode(location_entry, timeout=20) except: location = request.POST['location'] max_invit = request.POST['max_invit'] num_girl = request.POST['num_girl'] num_boy = request.POST['num_boy'] sp_score_req = request.POST['sp_score_req'] byo = request.POST['byo'] cash = request.POST['cash'] other = request.POST['other'] active = request.POST['active'] if event_form.is_valid: event = Event() event.creator = request.user event.name = name event.slug = slug event.num_people = num_people event.event_type = event_type event.location = location event.max_invit = max_invit event.num_girl = num_girl event.num_boy = num_boy event.sp_score_req = sp_score_req event.byo = byo event.cash = cash event.other = other event.active = active try: event.lat = lat event.lng = lng except: pass try: event.create() except: event.save() context = {} return render(request, "events/create_success.html", context) else: return render(request, "events/create_failure.html", context)
def geocode_address(self): if settings.GEOCODE_ADDRESSES: try: g = geocoders.GoogleV3() address = smart_str("{}, {}, {}, {}".format( self.address, self.city, self.postal_code, self.country)) location = g.geocode(address) self.latitude = location.latitude self.longitude = location.longitude except: self.latitude = None self.longitude = None
def atualizarCoordenadaChegadaGoogle(self): self.dlg.lineEdit_7.clear() self.dlg.lineEdit_8.clear() inputAddress = self.dlg.lineEdit_4.text() api_geocd_google = 'AIzaSyDIxergITTwdpMSMYdT7yAFyI6mrP3XDi0' api_key = self.dlg.lineEdit_13.text() g = geocoders.GoogleV3(api_key=api_key) location2 = g.geocode(inputAddress, timeout=10) CoordPartida = self.dlg.lineEdit_7.insert('{}'.format( location2.latitude)) CoordPartida = self.dlg.lineEdit_8.insert('{}'.format( location2.longitude))
def __init__(self): #initialize geocoders once: self.google = geocoders.GoogleV3() #doesn't look like yahoo supports free api any longer: #http://developer.yahoo.com/forum/General-Discussion-at-YDN/Yahoo-GeoCode-404-Not-Found/1362061375511-7faa66ba-191d-4593-ba63-0bb8f5d43c06 #yahoo = geocoders.Yahoo('PCqXY9bV34G8P7jzm_9JeuOfIviv37mvfyTvA62Ro_pBrwDtoIaiNLT_bqRVtETpb79.avb0LFV4U1fvgyz0bQlX_GoBA0s-') self.usgeo = geocoders.GeocoderDotUS() self.geonames = geocoders.GeoNames() self.bing = geocoders.Bing('AnFGlcOgRppf5ZSLF8wxXXN2_E29P-W9CMssWafE1RC9K9eXhcAL7nqzTmjwzMQD') self.openmq = geocoders.OpenMapQuest() self.mq = geocoders.MapQuest('Fmjtd%7Cluub2hu7nl%2C20%3Do5-9uzg14')
def save(self): self.slug = slugify(self.name) from geopy import geocoders google = geocoders.GoogleV3() address, (self.latitude, self.longitude) = google.geocode(' '.join( [self.street_address, self.city, self.state, self.zipcode])) if address: self.street_address, self.city, state_zip, country = address.split( ',') self.city = self.city[1:] waste, self.state, self.zipcode = state_zip.split(' ') super(Location, self).save()
def generateLatLong(self): if self.latitude == 0.0 or self.longitude == 0.0: g = geocoders.GoogleV3() if self.city == None: place, (lat, lng) = g.geocode("{0}".format(self.state), exactly_one=False)[0] else: place, (lat, lng) = g.geocode("{0} {1}".format( self.state, self.city), exactly_one=False)[0] self.latitude = lat self.longitude = lng sleep(.5)
def geocode_location(location): """Geocode a location string using Google geocoder.""" geocoder = geocoders.GoogleV3() try: result = geocoder.geocode(location, exactly_one=False) except Exception: return None, None try: ctr_lat, ctr_lng = result[0][1] except IndexError: return None, None return clean_coords(coords=(ctr_lat, ctr_lng))
def time_zone(self): """Formating timezone for given location""" g = geocoders.GoogleV3() #Gives the name of the timezone, ex: Africa/Luanda timezone_name = str( g.timezone((self.latitude_value(), self.longitude_value()))) #Returns the numeric value of the timezone, ex: +0100 return int( pytz.timezone(timezone_name).localize(datetime.datetime( 2011, 1, 1)).strftime('%z')) / 100
def save(self, **kwargs): if not self.location: address = u"%s %s" % (self.city, self.address) address = address.encode("utf-8") geocoder = geocoders.GoogleV3(domain='maps.google.fr') try: place, latlon = geocoder.geocode(address) except (URLError, GQueryError, ValueError): pass else: point = "POINT(%s %s)" % (latlon[1], latlon[0]) self.location = geos.fromstr(point) super(Shop, self).save()
def photosearch(): if request.method == 'POST': print "POST" search = request.form['searchText'] print search goo = geocoders.GoogleV3() print "GOO:", goo geocodes = goo.geocode(search, exactly_one=False) l2 = str(geocodes) latitude = lat2(l2) longitude = lon2(l2) return jsonify(latitude=latitude, longitude=longitude)
def query_google(latitude, longitude): coordinates = "%s, %s" % (latitude, longitude) Logger.log_more_verbose("Querying Google Geocoder for: %s" % coordinates) try: g = geocoders.GoogleV3() r = g.reverse(coordinates) if r: return r[0][0].encode("UTF-8") except Exception, e: fmt = traceback.format_exc() Logger.log_error_verbose("Error: %s" % str(e)) Logger.log_error_more_verbose(fmt)
def geocode_addresses(address_dicts): geocoder = geocoders.GoogleV3() for address_dict in address_dicts: address_dict["error"] = "" try: time.sleep(1) address, (lat, lon) = geocoder.geocode(address_dict["fulladdress"]) address_dict["fulladdress"] = address address_dict["latitude"] = lat address_dict["longitude"] = lon except ValueError as e: address_dict["error"] = e return address_dicts
def create(self, validated_data): g = geocoders.GoogleV3(django_settings.GOOGLE_API_KEY) try: res = g.geocode(validated_data['address'], exactly_one=False) address, (lat, lng) = res[0] except: lat = 0 lng = 0 coordinate = GEOSGeometry('POINT(%f %f)' % (lat, lng)) location = Location.objects.create(address=validated_data['address'], geometry=coordinate) location.save() return location
def from_name(name): """ Get a place instance from name Geeocdes the place """ from geopy import geocoders g = geocoders.GoogleV3() response = g.geocode(name) if response: place, (lat, lng) = response p = Place(lat, lng) else: p = Place.empty_place() return p
def main(): g = geocoders.GoogleV3() place, (lat, lng) = g.geocode(adress) location = [ boundingBox(lng, lat, halfradius)[0], boundingBox(lng, lat, halfradius)[1], boundingBox(lng, lat, halfradius)[2], boundingBox(lng, lat, halfradius)[3] ] # print "Location of "+ adress+" :",lng,lat auth = OAuthHandler(ckey, csecret) auth.set_access_token(atoken, asecret) twitterStream = Stream(auth, listener()) twitterStream.filter(locations=location)
def main(): try: print("\nThis program calculate the distance between two city\n" "Please enter the name of the cities:\n") gn = geocoders.GoogleV3() city1 = gn.geocode(raw_input("--> "), exactly_one=False)[0] city2 = gn.geocode(raw_input("--> "), exactly_one=False)[0] print("\nthe distance between {} and {} " "is : {} m").format(city1[0], city2[0], geo_distance(city1[1], city2[1])) return 0 except Exception, e: print(e) return 1
def location_to_tz(country, state): try: from datetime import datetime import pytz # $ pip install pytz from geopy import geocoders # $ pip install geopy # find timezone given country and subdivision g = geocoders.GoogleV3() location_str = '{0}/{1}'.format(country, state) place, (lat, lng) = g.geocode(location_str) timezone = g.timezone((lat, lng)) return timezone except: return None