Example #1
0
def xwalk_generic(form, advert):
    if not advert:
        advert = models.Advert()

    advert.set_owner(current_user.id)

    if form.category.data:
        advert.set_category(form.category.data)

    advert.set_title(form.title.data)

    if form.description.data:
        advert.set_description(form.description.data)

    if form.condition.data:
        advert.set_condition(form.condition.data)

    if form.price.data:
        advert.set_price(form.price.data)

    if form.location.data:
        advert.set_spot(form.location.data)
        if form.location.data == "home":
            if current_user.location:
                lat, lon = current_user.location
                advert.set_location(lat, lon)
            else:
                raise XWalkException(
                    "We do not have an address for your account. If you wish to use this option, please edit your information under My Account."
                )
        elif form.location.data == "uni":
            mail = current_user.id.split("@")
            domain = mail[-1]
            uni = domain_uni_lookup[domain]["address"]
            results = Geocoder.geocode(uni + ", United Kingdom")
            lat, lng = results[0].coordinates
            advert.set_location(lat, lng)
        elif form.location.data == "postcode":
            results = Geocoder.geocode(form.postcode.data + ", United Kingdom")
            lat, lng = results[0].coordinates
            advert.set_location(lat, lng)

    if form.keywords.data:
        advert.set_keywords(form.keywords.data)

    image = request.files["upload"]
    if image and allowed_file(image.filename):
        image_id = uuid.uuid4().hex
        name = image.filename.split(".")
        extension = name[-1]
        image_name = str(image_id) + "." + extension
        image.save(os.path.join(app.config["IMAGES_FOLDER"], image_name))
        advert.set_image_id(image_name)
    elif image and not allowed_file(image.filename):
        flash("This is not an allowed image type", "error")

    advert.expires_in(app.config.get("ADVERT_TIMEOUT", 604800))
    advert.save()
    advert.refresh()
    return advert
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
Example #3
0
def geoloc(request, entreprise_id=None):
	geocoder=Geocoder()
	try:
		proxy=os.environ['http_proxy']
		geocoder.set_proxy(proxy)
	except KeyError:
		pass
	entreprise = Entreprise.objects.get(pk=entreprise_id)
	adresseComplete = entreprise.adresse_propre+","+entreprise.ville_propre
	#testAdresse = "20 place de la Republique, Montargis"

	try:
		if geocoder.geocode(adresseComplete).valid_address :
			resultat = geocoder.geocode(adresseComplete)
			entreprise.latitude=resultat[0].coordinates[0]
			entreprise.longitude=resultat[0].coordinates[1]
			message = "adresse : "+str(resultat[0].coordinates)
			entreprise.save()
		else:
			message = "adresse non valide"
	except Exception as inst:
		message=inst.args
		
	return render(request, "entreprises/geolocalisation.html", {
		'entreprise': entreprise,
		'afficherAC': adresseComplete,
		'message':message
	})
Example #4
0
	def save(self):
		if not (self.latitude and self.longitude):
			geocoder = geocoders.GoogleV3()
			geocoding_results = None

			if self.address:
				try:
					query = '%(address)s, %(city)s, %(state)s' % self.__dict__
					g = Geocoder()
					if g.geocode(query).valid_address:
						geocoding_results = list(geocoder.geocode(query, exactly_one=False))
     					if geocoding_results:
						place, (latitude, longitude) = geocoding_results[0]
						self.latitude = latitude
						self.longitude = longitude
						super(Location, self).save()
					else:
						self.latitude = 0
						self.longitude = 0
						super(Location, self).save()
						self.delete()
						return 'address'
				except GeocoderError:
					return 'address'
		else:
			super(Location, self).save()
Example #5
0
def testCreate(request):
	if request.POST:
		form = suggestTest(request.POST)
		#I think this is where we would set the field for latLon
		#request = request.POST.copy()
		#request.setitem('latLon',latLon)
		if form.is_valid():
			address = form.cleaned_data['street']
			latLon = Geocoder.geocode(address)
			form = form.save(commit=False)
			coords = Geocoder.geocode(address)
			coords = coords[0].coordinates
			lat = coords[0]
			lon = coords[1]
			latLon = str(lat)+","+str(lon)
			form.latLon = latLon
			form.save()
			return HttpResponseRedirect(reverse('playgroundapp_home'))
	else:
		form = suggestTest()
	args = {}
	args.update(csrf(request))

	args['form'] = form
	args['dropdown'] = SchoolDistrict.objects.all()
	return render_to_response('playgroundapp/create_playground.html', args)
Example #6
0
 def geolocate(self):
     """Determines the latitude and longitude of the location."""
     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
Example #7
0
    def test_business_auth(self):
        """Test Business API access.

        This query fails on purpose, but we inspect and verify the signed URL is correct."""

        # Create the query parameters to sign. The order matters.
        params_to_sign = OrderedDict()
        params_to_sign['address'] = '1600 amphitheatre mountain view ca'
        params_to_sign['components'] = ''
        params_to_sign['bounds'] = ''
        params_to_sign['region'] = ''
        params_to_sign['language'] = ''
        params_to_sign['sensor'] = 'false'

        request_to_sign = requests.Request(
            'GET',
            url=Geocoder.GEOCODE_QUERY_URL,
            params=params_to_sign,
            headers={
                'User-Agent': Geocoder.USER_AGENT
            })
        client_id = 'gme-businessname'
        crypto_key = 'vNIXE0xscrmjlyV-12Nj_BvUPaw='
        g = Geocoder(client_id=client_id, private_key=crypto_key)
        signed_request = g.add_signature(request_to_sign)
        self.assertRegexpMatches(signed_request.url, r'&signature=[a-zA-Z0-9-=]+$', 'Signature must be at end of URL.')
        self.assertRegexpMatches(signed_request.url, r'&client=gme-businessname', 'URL must containg client id.')
        # Verified against https://m4b-url-signer.appspot.com/
        self.assertRegexpMatches(signed_request.url, r'&signature=7bVsUv6kyRHlG0DBAIhKHfX-96M=', 'Incorrect signature')
Example #8
0
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 geo(request,city1,city2):
    context = RequestContext(request)

    citydata1=Geocoder.geocode(city1)
    codtuple1=citydata1[0].coordinates
    codtuple1=list(codtuple1)

    citydata2=Geocoder.geocode(city2)
    codtuple2=citydata2[0].coordinates
    codtuple2=list(codtuple2)

    #Calculate Distance
    lat1, lon1 = codtuple1
    lat2, lon2 = codtuple2
    R = 6371 #Earth's Radius in Kms.

    lat_diff_radians = math.radians(lat2-lat1)
    long_diff_radians = math.radians(lon2-lon1)
    #Haversine formula to calculate distance between a pair of cordinates
    a = math.sin(lat_diff_radians/2) * math.sin(long_diff_radians/2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(long_diff_radians/2) * math.sin(long_diff_radians/2)
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
    distance = R * c
    
    context_dict = {'cood1':codtuple1,'cood2':codtuple2,'distance':distance}
    

    return render_to_response('coods.html',context_dict,context)
def geocode(address):
    try:
        return Geocoder.geocode(address)[0].coordinates
    except:
        rep = re.match(r"((.+-\d+)|(.+\d+号))", ad).group()
        print('%sのgeocodeが見つかりませんでした。調整します。→%s' % (ad, rep))
        return Geocoder.geocode(rep)[0].coordinates
Example #11
0
 def get_geocode(self):
     ad = self._get_address()
     try:
         return Geocoder.geocode("福岡県" + ad)[0].coordinates
     except:
         rep = re.match(r"((.+-\d+)|(.+\d+号))", ad).group()
         print('%sのgeocodeが見つかりませんでした。調整します。→%s' % (ad, rep))
         return Geocoder.geocode("福岡県" + rep)[0].coordinates
Example #12
0
def geocode_address(address):
    if address.cord is None:
        business_geocoder = Geocoder()
        results = business_geocoder.geocode(address.text)
        address.cord = results
    else:
        results = address.cord
    return Coordinate(results[0].coordinates[0], results[0].coordinates[1])
Example #13
0
def dist_address(addr1, addr2):
    ''' given two address, return distance in miles '''
    result1 = Geocoder.geocode(addr1)
    result2 = Geocoder.geocode(addr2)
    if (result1.count==1)&(result2.count==1): ## if only one valid address
        return dist(result1.coordinates, result2.coordinates) ## dist(coordinate1, coordinate2)
    else:
        print 'Error'
        return None
Example #14
0
def validate_location(self):
    g = Geocoder()
    isvalid = False
    try:
        isvalid = g.geocode(self).valid_address
    except:
        raise ValidationError("No address was found.")
    if not isvalid:
        raise ValidationError("Please enter a valid address.")
Example #15
0
def find_Path(MAP, model):
    gmaps = GoogleMaps()
    
    home = raw_input("Enter your starting address: ")
    end =  raw_input("Enter your destination address: ")
    results = Geocoder.geocode(home)
    results2 = Geocoder.geocode(end)
    #results = Geocoder.reverse_geocode(41.96786329,-87.71349889)
    #results2 = Geocoder.reverse_geocode(41.763258, -87.61172601)

    print '---Finding Path from ', results, ' to ', results2

    dirs  = gmaps.directions(results, results2)

    time  = dirs['Directions']['Duration']['seconds']
    dist  = dirs['Directions']['Distance']['meters']
    route = dirs['Directions']['Routes'][0]
    
    PATH = []
    EVALUATION = []
    
    for step in route['Steps']:
        position = (step['Point']['coordinates'][1], step['Point']['coordinates'][0])
        if position in MAP:
            for i in range(4): PATH.append('H')
            PATH.append('no')
        else:
            for i in range(4):PATH.append('L')
            PATH.append('yes')
        
        #PREDICT FOR EACH CITY IN THE INTERMEDIATE STEPS
        with open("predict.arff", "a") as myfile:
            for elem in PATH:
                if elem == 'yes' or elem == 'no': myfile.write(elem)
                else: myfile.write(elem  + ',')
            myfile.write('\n')
        PATH = []

    EVALUATION = model.TestClassifier("predict.arff")
    #mark current place as SAFE since you're already at that location anyways
    EVALUATION[0] = 'yes'
    
    #Print Final Results At this Point
    k = 0
    for step in route['Steps']:
        position = (step['Point']['coordinates'][1], step['Point']['coordinates'][0])
        print step['Point']['coordinates'][1], step['Point']['coordinates'][0] ,  '===========================>SAFE? ', EVALUATION[k]
        print step['descriptionHtml']
        k +=1
    
    #UPDATE THE FILES
    delete("predict.arff")
    filename2 = "predict.arff"
    shutil.copy("predict_start.arff", filename2)
    if os.path.isfile (filename2): print "Have a Safe Journey"
    else: print "#####Problem Here: Error 99. Engineeer Will Fix the Bug ASAP"
def get_county_name(longitude, latitude, placeID = None):
    url_prefix = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='
    #placeID and longitude and latitude
    key = 'AIzaSyAw-2MPkd3FbwnTjNpsaai1tsIzUk-B2aA'
    geocoder_obj = Geocoder(None, key)
    print "Lookup of Address Begin"
    results = geocoder_obj.reverse_geocode(longitude, latitude)
    print type(results)
    address = results.split()
    print address
Example #17
0
    def test_simple_auth(self):
        """Test Simple API access. May be flacky is too many people test with the test key"""

        addr = '1600 amphitheatre mountain view ca'
        api_key = 'AIzaSyBUnYj-u24fsbWdftSwbos7XcyQVqiuSao'  # a throwaway test key
        g = Geocoder(api_key=api_key)
        result = g.geocode(addr)

        self.assertEqual(result.state, 'California')
        self.assertEqual(result.country, 'United States')
Example #18
0
def determine_estimate():

    ### Gets addresses, converts them to coordinates, requests estimates from API, creates dictionary, saves to a session to use later

    uber_prices = []

    app_start_address = request.args.get("start_address")
    app_end_address = request.args.get("end_address")

    ### This is a fix for the problem that arose from the geocode lbirary, fixes SSL restrictions. See site for more details: https://urllib3.readthedocs.org/en/latest/security.html#pyopenssl

    # try:
    # 	import urllib3.contrib.pyopenssl
    # 	urllib3.contrib.pyopenssl.inject_into_urllib3()
    # except ImportError:
    # 	pass

    ### If the server receives correct input, it will convert to coordinates, make reuqest from Uber API, if not it will display an error message

    # try:
    geo_start_address = Geocoder.geocode(app_start_address)
    geo_end_address = Geocoder.geocode(app_end_address)
    if geo_start_address.valid_address and geo_end_address.valid_address:

        start_coordinates = geo_start_address[0].coordinates
        end_coordinates = geo_end_address[0].coordinates

        start_lat = start_coordinates[0]
        start_long = start_coordinates[1]

        end_lat = end_coordinates[0]
        end_long = end_coordinates[1]

        AUTH = Uber(ENV.CLIENT_ID, ENV.SERVER_TOKEN, ENV.SECRET)

        estimate = AUTH.get_price_estimate(start_lat, start_long, end_lat, end_long)

        services_and_prices = estimate["prices"]

        for i in range(len(services_and_prices)):
            uber_price = {}
            uber_price["service"] = services_and_prices[i]["display_name"]
            uber_price["price"] = services_and_prices[i]["estimate"]
            uber_prices.append(uber_price)

        session["user_travel"] = uber_prices

        return render_template("results.html")

    else:

        message = "Something went wrong. Please make sure you entered valid addresses."

        return render_template("index.html", message=message)
Example #19
0
def map(location,destination):
	api_key=open('api_key').read()
	url="https://maps.googleapis.com/maps/api/js?key=%s"%api_key
	geoOrig=Geocoder.geocode(location)
	geoDest=Geocoder.geocode(destination)
	lat1,lng1=geoOrig[0].coordinates
	lat2,lng2=geoDest[0].coordinates
	directionsurl=("https://maps.googleapis.com/maps/api/directions/json?origin=%s&destination=%s&key=%s")%(location, destination, api_key)
	directions=requests.get(directionsurl)
	print directions.content
	return render_template("base.html", url=url, lat1=lat1, lng1=lng1, lat2=lat2,lng2=lng2)
Example #20
0
def geocode():
    '''
    geocoder = GoogleV3(
        client_id='416144311414-9sa4usu4f9dsuvn8urbhprq3stdisq3k.apps.googleusercontent.com', 
        secret_key='0LGqN8vGa_xfEd4us9Y_VXKC',
        api_key='AIzaSyAc0R7DULyiZPWAcBTrCyFJM38WCepWrEU')
        '''
    #geocoder = GoogleV3(api_key='AIzaSyBBnPI_YDy1V51NfXAvHsVKWhq0Po31L24')	
    geocoder = Geocoder();
        
    #load geocode cache
    try:
        with open('process/geocache.json') as data_file:    
            cache = json.load(data_file)
    except:
        cache = {}

    #load properties
    with open('app/properties.json') as data_file:    
        properties = json.load(data_file)

    #geocode property addresses
    with stdchannel_redirected(sys.stderr, os.devnull):
        i = 0
        for p in properties:
            i += 1
            if p["id"] in cache:
                p["latlong"] = cache[p["id"]]
            else:
                try:
                    address = p["address"] + " " + p["city"] + " " + p["state"]
                    l = geocoder.geocode(address)
                    latlong = [ l.latitude, l.longitude]
                    p["latlong"] = latlong
                    cache[p["id"]] = latlong
                except: 
                    print('\nERROR: GeoCoding Failure, API Limit most likely reached')
                    break
                
                    

            #print percent progress
            sys.stdout.write("\r%d%%" % (float(i)/len(properties) *100.0))
            sys.stdout.flush()

    print ("\nGeoCoding Complete")

    #dump properties
    with open('app/properties.json', 'w') as outfile:
        json.dump(properties, outfile)

    #dump cache
    with open('process/geocache.json', 'w') as outfile:
        json.dump(cache, outfile)
Example #21
0
	def _geocode(self, address,city,state,zipcode):
		# prepare geocoder
		from pygeocoder import Geocoder
		myg=Geocoder(api_key='AIzaSyAJmxEb1O6GJMxP9QuhCc4-HV2aae2FolA')
		addrstr = "%s %s, %s %s" %(address,city, state, zipcode)
		try:
			loc = myg.geocode(addrstr)
		except Exception, e:
			print "GEOCODER FAIL: %s. Maybe try setting the proxy?" %(e)
			myg.set_proxy('mtaweb.metro.net:8118')
			loc = myg.geocode(addrstr)
Example #22
0
def getGeocodedLocation(location, language='en'):
    if location is None:
        return None
    try:
        google_api = getUtility(IPasswordManager, 'googleapi')
        geocoder = Geocoder(api_key=google_api.password)
        locations = geocoder.geocode(location, language=language)
    except GeocoderError, e:
        if e.status == u'ZERO_RESULTS':
            return None
        else:
            raise e
Example #23
0
    def test_geocode_with_components(self):
        """Test pygeocoder geocode()"""

        addr = 'East London'
        components = 'country:ZA'
        g = Geocoder()

        bare_result = g.geocode(addr)
        self.assertEqual(bare_result.city, 'London')
        self.assertEqual(bare_result.country, 'United Kingdom')

        za_result = g.geocode(addr, components=components)
        self.assertEqual(za_result.city, 'East London')
        self.assertEqual(za_result.country, 'South Africa')
Example #24
0
 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
Example #25
0
def restaurant():
    #Get input arguments
    restaurant = request.args.get("restaurant", "")
    miles = request.args.get("miles", '')
    zipcode = request.args.get("zipcode", "")
    try:
        miles = str(int(float(miles)))
        if miles=="0":
            miles = "1"
    except ValueError:
        return json.dumps(["Please enter a number into the miles field"])

    try:
        location = Geocoder.geocode(zipcode)
    except:
        return json.dumps(["I couldn't recognize that address. Could you enter another one?"])

    zipcode = location.formatted_address

    query = restaurant + " " + miles + " " + zipcode
    sql = ('SELECT Result FROM Cached WHERE Query = "' + query + '";')
    db.cursor.execute(sql)
    results = db.cursor.fetchall()
    if len(results)>0:
        result = ast.literal_eval(results[0][0])
    else:
        result = predict_rest.predict_rest(restaurant, miles, location)
        sql = ('INSERT INTO Cached (Query, Result) VALUES ("' + query + '", %s);')
        db.cursor.execute(sql, (str(result),))
        db.commit()

    return json.dumps(result)
Example #26
0
def _update_account(account, form):
    account.set_name(form.name.data)

    if form.degree.data:
        account.set_degree(form.degree.data)
    elif form.degree.data == "":
        del account.degree

    if form.postcode.data:
        account.set_postcode(form.postcode.data)

        results = Geocoder.geocode(form.postcode.data + ', United Kingdom')
        lat, lng = results[0].coordinates
        account.set_location(lat, lng)
    elif form.postcode.data == "":
        del account.postcode
        account.unset_location()

    if form.phone.data:
        account.set_phone(form.phone.data)
    elif form.phone.data == "":
        del account.phone

    if form.graduation.data:
        account.set_graduation(form.graduation.data)
    elif form.graduation.data == "":
        del account.graduation
Example #27
0
    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)
Example #28
0
def generate_user_home_work(user):
    user_home=detect_home(user)
    # print user_home
    zip_is_valid = _check_zip_validity(user_home, user)
    logging.debug('starting for %s' % user)
    if Profiles.find({'user_id':user}).count()==0:
        profile_todo={'source':'Shankari','user_id': user,'home':user_home}
        Profiles.insert(profile_todo)
    else:
        #TODO: make detect_home return something better than a N/A string
        Profiles.update({"$and":[{'source':'Shankari'},
                                     {'user_id':user}]},{"$set":{'home':user_home}})
    user_work=detect_work_office(user)
    Profiles.update({"$and":[{'source':'Shankari'},{'user_id':user}]},{"$set":{'work_place':user_work}})
    user_zip=get_userZipcode(user, zip_is_valid)
    Profiles.update({"$and":[{'source':'Shankari'},{'user_id':user}]},{"$set":{'zip':user_zip}})
    if user_zip!='N/A':
        geoinfo= Geocoder.geocode(user_zip)
        # geocoder returns data in lat,lng format.
        # we convert to lng,lat internally, since that is the format that the
        # rest of our code is in
        zipCen=[geoinfo[0].coordinates[1],geoinfo[0].coordinates[0]]
    else:
        zipCen='N/A'
    Profiles.update({"$and":[{'source':'Shankari'},{'user_id':user}]},{"$set":{'zip_centroid':zipCen}})


    for day in range(1,6):
        key='work'+str(day)
        Profiles.update({"$and":[{'source':'Shankari'},
                                     {'user_id':user}]},{"$set":{key:detect_daily_work_office(user,day)}})
Example #29
0
    def retrieve(self, city, attempt=1):
        """Try to grab json data in multiple ways"""
        r = get_json_or_timeout(self.api_url.format(self.APIKEY,
                                                    '/'.join(self._features),
                                                    self.lang,
                                                    city))

        # when service is unreachable or times out
        if r is None:
            raise WeatherError('Could not reach wunderground.com')
        # if service does not recognize city, it returns possible
        # zmw code, which is possible to search for city with
        elif 'results' in r['response']:
            return self.retrieve('zmw:' + r['response']['results'][0]['zmw'],
                                 attempt + 1)
        # some cities are not recognized and have to have `,country` at the end
        # or be searched based on latitude and longitude
        elif 'error' in r['response']:
            if attempt < 2:
                loc = Geocoder.geocode(city)
                return self.retrieve(','.join([str(loc[0].latitude),
                                               str(loc[0].longitude)]),
                                     attempt + 1)
            elif attempt < 3:
                return self.retrieve(city + ',' + self.country, attempt + 1)
            raise WeatherError(r['response']['error']['description'])
        else:
            return r
Example #30
0
File: views.py Project: MAPC/cedac
def geocode_property(obj):

    if obj.geocoded is False:

        attempts = 0
        success = False

        while success != True and attempts < 3:
            try:
                result = Geocoder.geocode(obj.address)
                attempts += 1

                if result.valid_address:
                    obj.lat = result[0].coordinates[0]
                    obj.lon = result[0].coordinates[1]
                    obj.geometry = Point(obj.lon, obj.lat)
                    obj.geocoded_address = str(result)
                    obj.geocoded_type = result.raw[0]['geometry']['location_type']
                    obj.geocoded = True

                # no geocoding error
                success = True

            except GeocoderError, e:
                if 'OVER_QUERY_LIMIT' in e:
                    time.sleep(2)
                    # retry
                    continue
                else:
                    # not really true, but stop trying
                    # not sure what happened
                    success = True 
                    break