def test_google_maps_request(self): geo = Geocoder(api_key=GEOCODE_API) self.assertEqual(geo.geocode("Dallas, Texas").coordinates, (32.7766642, -96.79698789999999)) self.assertEqual(geo.geocode("Austin, Texas").coordinates, (30.267153, -97.7430608)) self.assertEqual(geo.geocode("University of Texas at Austin").coordinates, (30.2849185, -97.7340567)) self.assertEqual(geo.geocode("UT Austin").coordinates, (30.2849185, -97.7340567))
def test_time_google_api(self): geo = Geocoder(api_key=GEOCODE_API) start=time.time() geo.geocode("University of Texas at Austin") end = time.time() self.assertTrue(1 > end-start, "Single geocoder is Slower than 1s")
def test_google_lyft_uber_pipe(self): geo = Geocoder(api_key=GEOCODE_API) sessionu = Session(server_token='hVj-yE_w4iJQ5-rbp8hmKZSNekOzLV1cvnF_BrNl') clientu = UberRidesClient(sessionu) auth_flow = ClientCredentialGrant( 'd-0DVSBkAukU', 'I-yZZtV1WkY_903WKVqZEfMEls37VTCa', 'rides.request', ) session = auth_flow.get_session() client = LyftRidesClient(session) start = time.time() dlat,dlong = geo.geocode("UT Austin").coordinates alat,along = geo.geocode("Round Rock, TX").coordinates response = client.get_cost_estimates(dlat,dlong,alat,along) response = clientu.get_price_estimates( start_latitude=dlat, start_longitude=dlong, end_latitude=alat, end_longitude=along, seat_count=2 ) end = time.time() self.assertTrue(10 > end-start)
def main(): countystate = "Bedford County, Va" gc = Geocoder("") gc.set_proxy("http://*****:*****@cdcwsa02.commscope.com:3128") lastid = findlastid() if os.path.isfile(csv_read): with open(csv_read, 'rb') as csvfile: reader = csv.DictReader(csvfile) for row in reader: if objectkey in row and row[objectkey] < lastid: continue street = row[addresskey].strip() position = street.find('&') while position > 0: street = street[position + 1:] position = street.find('&') street.strip() if addresskey in row and len(street) > 0: fulladdress = street + ", " + countystate result = gc.geocode(fulladdress) if result.count > 0 and result.administrative_area_level_2 == "Bedford County": writeobjectid(row[objectkey], row[addresskey], result.postal_code) else: writeobjectid(row[objectkey], row[addresskey], 77777) else: writeobjectid(row[objectkey], row[addresskey], 33333) else: print "No File :(\n" return None
def get_lat_longs(location): """ :param location: :return: """ geocode = Geocoder() return geocode.geocode(location)[0].coordinates
def fix_address(address): coder = Geocoder(settings.GOOGLE_API_KEY) try: parsed = coder.geocode(address.raw) except GeocoderError: # print(" !!! Bad address") address.delete() return None # print(" ", address.raw, parsed.formatted_address, sep="\n ") postal_code = parsed.postal_code if parsed.postal_code_suffix: postal_code = f"{postal_code}-{parsed.postal_code_suffix}" parsed_values = dict( raw=address.raw, country=parsed.country, state=parsed.state, locality=parsed.locality, sublocality=parsed.county, postal_code=postal_code, street_number=parsed.street_number, route=parsed.route, formatted=parsed.formatted_address, latitude=parsed.latitude, longitude=parsed.longitude, ) try: address = update_address(parsed_values, address) except InconsistentDictError: # print(" !!! Bad address") address.delete() return None return address
def create_map(profiles): options = ("no", "don't", "not", u"❌", "sorry", u"🚫", u"✋", "paypal", "pp", "negociable", "negotiable", "negoatiating", "negotiate", "offer", "deal", "lower") kml = simplekml.Kml() coords_map = {} g = Geocoder() for p in profiles: location = p["location"] # Check if it's just a message and not a location if any(o in location for o in options): continue # We can't hit the API too hard time.sleep(6) try: coords = coords_map[location] except KeyError: try: results = g.geocode(location) lat, lng = results.coordinates coords = [(lng, lat)] coords_map[location] = coords pnt = kml.newpoint() pnt.style.labelstyle.scale = 2 # Make the text twice as big pnt.name = p["user_name"] pnt.coords = coords # Save the KML kml.save("poshmark.kml") except GeocoderError as e: print e
def host(): cur = get_db() if request.method == "GET": return render_template("auth/host.html") elif request.method == "POST": # Validate user information for Registrant table if not request.form.get("password") or not request.form.get("email") or not request.form.get("first") or not request.form.get("last"): return render_template("resp/error.html") if not request.form.get("propname") or not request.form.get("address") or not request.form.get("zipcode"): return render_template("resp/error.html") email = request.form.get("email") cur.execute("INSERT INTO Registrant (hash, email, first, last, type) Values(:hash, :email, :first, :last, :type)", {"hash": pwd_context.hash(request.form.get("password")), "email": email, "first": request.form.get("first"), "last": request.form.get("last"), "type": "Host"}) cur.commit() print("INSERT success") host_id = query_db("SELECT * FROM Registrant WHERE email = ?", [email], one = True) # Generate geocoordinates for property's address - to be used with googlemaps on details page street = request.form.get("address") zip = request.form.get("zipcode") addr = ", ".join([street, zip]) value = Geocoder('AIzaSyA_8dKMvm9l98sJMLFv-G6eV7K3vUPUat0').geocode(addr) coords = value[0].coordinates lat = coords[0] lng = coords[1] cur.execute("INSERT INTO Property (name, address, zip, desc, owner_id, lat, lng) Values(:name, :address, :zip, :desc, :owner_id, :lat, :lng)", {"name": request.form.get("propname"), "address": street, "zip": zip, "desc": request.form.get("desc"), "owner_id": host_id[0], "lat": lat, "lng": lng}) cur.commit() print("INSERT success") # Log in user # Assign session variables to user session["user_id"] = host_id[0] session["type"] = host_id[5] session["name"] = request.form.get("propname") # Continue user to next section of property registration: Cover photo upload return render_template("upload_file.html")
def googleGetZipCode(self, latitude, longitude, zipCodes): count = 0 #if(time.time() - self.GoogleTimeLog < 1): time.sleep(1) self.GoogleTimeLog = time.time() while (True): try: address = Geocoder(self.keys[self.currentKey]).reverse_geocode( latitude, longitude) self.currentKey = self.currentKey + 1 if (self.currentKey >= len(self.keys)): self.currentKey = 0 break except GeocoderError as GeoError: print(GeoError) count = count + 1 time.sleep(10) if (count > 3): sys.exit() if (address.postal_code is not None and int(address.postal_code) in zipCodes): return address else: return 0
def geocoder(country, q, decimal_places=3): components = "country:" + country if settings.GOOGLE_MAPS_GEOCODING_API_KEY: geocoder = Geocoder(settings.GOOGLE_MAPS_GEOCODING_API_KEY) response = geocoder.geocode(q, components=components) else: response = Geocoder.geocode(q, components=components) results = [] for entry in response.raw: # The Google Geocoder API will return the country used in the components if # there is no match. Filter this from our results. if "country" in entry['types']: continue result = { "address": entry['formatted_address'], "latitude": entry['geometry']['location']['lat'], "longitude": entry['geometry']['location']['lng'], } # round to the require precision for key in ['latitude', 'longitude']: result[key] = round(result[key], decimal_places) # Check that the result has not already been added. This is possible # when several different areas evaluate to the same one (eg various # instances of South Africa's "Cape Town"). if result not in results: results.append(result) return results
def GetLocation(address): geocoder = Geocoder() try: result = geocoder.geocode(address, language="en") return result.coordinates except Exception as e: return (None, None)
def get_post_javascript_data(): global js_latitud global js_longitud js_latitud = request.form['js_latitud'] js_longitud = request.form['js_longitud'] results = Geocoder( api_key='AIzaSyCRjRkHf-0D28I2DFoZKRIyWIJJ_VoVrt4').reverse_geocode( float(js_latitud), float(js_longitud)) global coordenadas coordenadas = { 'dni': users['dni'], 'nombres': users['nombres'], 'apellido': users['apellidos'], 'direccion': results.formatted_address, 'email': users['correo'], 'mensaje_predeterminado': 'NECESITO DE TU AYUDA ESTOY EN UNA SITUACIÓN DESESPERANTE POR FAVOR VEN RAPIDO!!!!' } print(coordenadas) return jsonify(coordenadas)
def coordinate_generator(number_of_points): 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)) coordinate_list.append(gcode[0].coordinates) # output_file.write(fullstring.format(gcode.x, gcode.y, gcode.address)) except GeocoderError: continue print('Finished generating %d coordinate points' % counter) return coordinate_list
def search(): event = "https://cors-anywhere.herokuapp.com/https://api.yelp.com/v3/events" headers = { 'Authorization': 'Bearer %s' % API_KEY, 'X-Requested-With': 'XMLHttpRequest' } params = { 'limit': 9, 'sort_on': 'popularity', 'radius': 5000, 'location': request.args.get('location'), 'categories': request.args.get('categories'), 'is_free': checkbox() } response = requests.get(event, params=params, headers=headers) event_response = response.json() coord = Geocoder(GOOGLEMAPS_KEY).geocode(request.args.get('location')) lat = coord.coordinates[0] lng = coord.coordinates[1] # this is the map sndmap = Map( identifier="sndmap", zoom=12, lat=lat, lng=lng, markers=map_generator(event_response), style="height:350px; width:100%; margin:0;", ) return render_template('search.html', event_response=event_response['events'], sndmap=sndmap) pprint.pprint(response)
def get_geocoder(): global _geocoder if not _geocoder: if config.GEOCODE_API_PRIVATE_KEY and config.GEOCODE_API_CLIENT_ID: _geocoder = Geocoder(config.GEOCODE_API_CLIENT_ID, config.GEOCODE_API_PRIVATE_KEY) else: _geocoder = Geocoder return _geocoder
def get_coords(address): geo_addr = None geocoder = Geocoder() try: geo_addr = geocoder.geocode(address).coordinates except GeocoderError as e: return get_coords(address) return geo_addr
def impute_zip(df): geocoder = Geocoder('your-api-key') tqdm_notebook().pandas() df.loc[df["zipcode"].isnull(), "zipcode"] = df[df["zipcode"].isnull()].progress_apply( lambda row: geocoder.reverse_geocode(row['latitude'], row[ 'longitude'])[0].postal_code, axis=1) return (df)
def geocodeAddress(self, house): try: coords = Geocoder(client_id='AIzaSyAcpNzt48F8411wYZncqhGU2XTPxpW9X8Y').geocode(house.address).coordinates house.latitude = coords[0] house.longitude = coords[1] return True except pygeolib.GeocoderError as e: print e print 'trying again' return False
def geolocate(self): if self.geolocated: return self.geolocate_success the_address = self.address_for_geolocation() logmessage("Trying to geolocate " + str(the_address)) from pygeocoder import Geocoder google_config = get_config('google') if google_config and 'api key' in google_config: my_geocoder = Geocoder(api_key=google_config['api key']) else: my_geocoder = Geocoder() results = my_geocoder.geocode(the_address) self.geolocated = True if len(results): self.geolocate_success = True self.location.gathered = True self.location.known = True self.location.latitude = results[0].coordinates[0] self.location.longitude = results[0].coordinates[1] self.location.description = self.block() self.geolocate_response = results.raw geo_types = { 'administrative_area_level_2': 'county', 'neighborhood': 'neighborhood', 'postal_code': 'zip', 'country': 'country' } for geo_type, addr_type in geo_types.iteritems(): if hasattr(results[0], geo_type) and not hasattr(self, addr_type): logmessage("Setting " + str(addr_type) + " to " + str(getattr(results[0], geo_type)) + " from " + str(geo_type)) setattr(self, addr_type, getattr(results[0], geo_type)) #else: #logmessage("Not setting " + addr_type + " from " + geo_type) #logmessage(json.dumps(self.geolocate_response)) else: logmessage("valid not ok: result count was " + str(len(results))) self.geolocate_success = False return self.geolocate_success
def main(): """Find the time of a given location. :return: A namedtuple, TimeZoneResult with location and time. """ location = str(input('Location : ')) geocode_result = Geocoder(API_KEY).geocode(location) coordinates = geocode_result.data[0]['geometry']['location'] location = geocode_result.data[0]['formatted_address'] timezone = TimezoneFinder().timezone_at(**coordinates) time = datetime.now(pytz.timezone(timezone)) return TimeZoneResult(location=location, time=time)
def verify_address(data): try: results = Geocoder('AIzaSyDDLAMji-hY20cbBfOkB_88mEBtZxnerA8').geocode(data) #results = Geocoder().geocode(data) if results.coordinates: # Geocode.coordinates are lat, long, but we need long, lat return Point((results.longitude, results.latitude)) else: return "Error" except Exception as e: print e return "Error"
def getCityAddr(lat, lng): #'''Function that returns "city, state, country" from a geo-coordinate''' try: lat = float(lat) lng = float(lng) x = Geocoder(gmap_key).reverse_geocode(lat, lng) x = [x.city, x.state, x.country] x = ', '.join(filter(None, x)) print(x) return x except Exception as e: print(e) return 'NOT FOUND'
def try_reverse_geocode_until_success(latitude, longitude): success = False attempts = 2 results = [] geocoder = Geocoder() while not success and attempts < 3: try: results = geocoder.reverse_geocode(latitude, longitude) success = True except: attempts += 1 sleep(2) return results, success
def coord(): """ 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 = [] geocoder = Geocoder() lat = round(random.uniform(SOUTHERNMOST, NORTHERNMOST), 6) lng = round(random.uniform(EASTERNMOST, WESTERNMOST), 6) return (lat, lng)
def geo(address): geocoder = Geocoder(api_key=apikey) try: location = Geocoder.geocode(address) coords = [location.latitude, location.longitude] if location.valid_address: print(coords) return coords, 'success' else: #print('1st pass: Invalid address: ' + address) return coords, 'invalid address' except: #print('2nd pass: This one didn\'t work: ' + address) return [0.0, 0.0], 'failure'
def geo_find(addr, api_key=False): # link = 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY' # url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=' # url += urllib.quote(addr.encode('utf8')) res = [] api_key = 'AIzaSyDAPZqsalpxu0T5SPRBXSG8K2ZVnngmmUo' try: gcoder = Geocoder(api_key) results = gcoder.geocode(addr) print results[0].latitude print results[0].longitude res.append(results[0].latitude) res.append(results[0].longitude) except Exception, e: logger.info(' Error : %s', e.args) pass
def reverse_lookup(lat, long, key='YOURAPIKEY'): """Function for lookup of addresses from latitude, longitude details using Google Maps API Args: lat (float): latitude as float long (float): longitude as float key (str): (default='YOURAPIKEYHERE') google maps api key Returns: returns a tuple with address (str), zipcode (str) """ result = str(Geocoder(api_key=key).reverse_geocode(lat, long)) location_details = result.split(",") address = location_details[0] zipcode = location_details[-2] city = location_details[1] state = location_details[2].split(" ")[1] return address, zipcode, city, state
def __init__(self, lng, lat): self.lng = lng self.lat = lat self.valid = False self._country = None self._zones = None try: #TODO: not a good idea to expose this publicly... geocoder = Geocoder(api_key="AIzaSyB-QYiv1mtdZKf0kMtX_u947Y-0rP_WB50") self.geocoder_results = geocoder.reverse_geocode(self.lat, self.lng) except GeocoderError as ge: logging.error("reverse_geocode for ({0},{1}) failed: '{2}'".format( self.lat, self.lng, ge)) #TODO: CONSIDER: is this the best strategy here ? return if self.geocoder_results.count > 0: self.valid = True
def test_google_uber_pipe(self): geo = Geocoder(api_key=GEOCODE_API) dlat,dlong = geo.geocode("UT Austin").coordinates alat,along = geo.geocode("Round Rock, TX").coordinates session = Session(server_token='hVj-yE_w4iJQ5-rbp8hmKZSNekOzLV1cvnF_BrNl') client = UberRidesClient(session) start = time.time() response = client.get_price_estimates( start_latitude=dlat, start_longitude=dlong, end_latitude=alat, end_longitude=along, seat_count=2 ) end = time.time() self.assertTrue(response != None)
def geo_find(addr, api_key=False): '''Function to Geo Localise Patient location ''' #link = 'https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=API_KEY' # url = 'https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=' # url += urllib.quote(addr.encode('utf8')) # if api_key: # url += '&key=' # url += urllib.quote(api_key.encode('utf8')) res = [] api_key = 'AIzaSyDAPZqsalpxu0T5SPRBXSG8K2ZVnngmmUo' try: gcoder = Geocoder(api_key) results = gcoder.geocode(addr) print results[0].latitude print results[0].longitude res.append(results[0].latitude) res.append(results[0].longitude) except Exception, e: print "Exception.....", e.args pass