def post(self): stopID = self.request.get('stopID') lat = self.request.get('lat') lon = self.request.get('lon') stop = StopLocation() stop.stopID = stopID stop.routeID = '00' stop.intersection = self.request.get('intersection').upper() stop.location = GeoPt(lat, lon) stop.update_location() stop.direction = '00' logging.debug('created new stoplocation for %s' % stopID) stop.put() routeQ = db.GqlQuery("SELECT * FROM RouteListing WHERE stopID = :1", stopID) routes = routeQ.fetch(100) if len(routes) > 0: for r in routes: logging.debug('updating route %s with new location' % r.route) r.stopLocation = stop r.put() self.redirect('http://smsmybus.com/labs/displaystops')
def add_place(self, location, accuracy, name, types, language='en-EN', sensor=False): from google.appengine.ext.db import GeoPt if not isinstance(location, GeoPt): location = GeoPt(location) dict = { 'location': { 'lat': location.lat, 'lng': location.lon, }, 'accuracy': accuracy, 'name': name, 'language': language, } if types is not None: dict['types'] = types url = self._add_url + self._parse_get( '&sensor=%s&key=%s' % ('true' if sensor else 'false', self.key)) raise Exception(url) return self._do_request(url, method='POST', body=dict.__str__())
def post(self): stop_list = [] stopID = self.request.get('stopID') if len(stopID) == 1: stopID = "000" + stopID if len(stopID) == 2: stopID = "00" + stopID if len(stopID) == 3: stopID = "0" + stopID name = self.request.get('name') description = self.request.get('description') lat = self.request.get('lat') lon = self.request.get('lon') direction = self.request.get('direction') # if it doesn't, create a new one s = StopLocation() s.stopID = stopID s.intersection = name.split('(')[0].rstrip() s.direction = direction s.description = description s.location = GeoPt(lat, lon) s.update_location() stop_list.append(s) # put the new stop in the datastore db.put(stop_list) logging.info('done updating stop locations for stopID %s' % stopID) self.response.set_status(200)
def mod_searchconfig_google(request): from google.appengine.ext.db import GeoPt sconfig = request.user.settings.searchconfig_google sconfig.region_code = request.POST['region_code'] sconfig.location = GeoPt(request.POST['location']) sconfig.radius = int(request.POST['radius']) sconfig.type = request.POST['type'] sconfig.put() return HttpResponse()
def post(self): cookie = self.request.get('cookie') if not cookie: logging.warning('Submit to /geocode without cookie.') self.redirect('/') return user = labeler_db.User.get(cookie) assert user assert self.request.get('id') photo = labeler_db.ImageRecord.get_by_key_name(self.request.get('id')) assert photo geocode = labeler_db.Geocode(user=user, photo=photo) lat = self.request.get('lat') lon = self.request.get('lon') if lat and lon: geocode.location = GeoPt(lat=float(lat), lon=float(lon)) if self.request.get('impossible'): geocode.feasibility = 'no' elif self.request.get('notme'): geocode.feasibility = 'maybe' elif self.request.get('notsf'): geocode.feasibility = 'notsf' elif self.request.get('success'): geocode.feasibility = 'yes' else: logging.warning('Got rating w/o feasibility') self.redirect('/') return setting = self.request.get('setting') if setting: geocode.setting = setting rating = self.request.get('rating') if rating: rating = int(rating) if rating >= 1 and rating <= 5: geocode.rating = rating else: logging.warning('Got odd rating: %s' % rating) comments = self.request.get('comments') if comments: geocode.comments = comments geocode.put() logging.info('Geocode %s for %s by %s' % (geocode.feasibility, photo.photo_id, user.key())) # Take them to another random image. id = labeler.randomImage(user) self.redirect('/?id=%d' % id)
def get(self): r = FlowerbedExplore() user = users.get_current_user() gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id()) gamer = GqlQuery('SELECT * FROM Gamer WHERE ANCESTOR IS :1', gamer_key).get() if self.request.get('lat') and self.request.get('lon'): r.timestamp = int(time.time()) lat = float(self.request.get('lat')) / 1000000 lon = float(self.request.get('lon')) / 1000000 gamer.point = GeoPt(lat, lon) #update user position #take adjacent tiles tiles = [] requests = [] tile = geocell.compute(GeoPt(lat, lon), RULES['GEO_RESOLUTION']) tiles.append(tile) tiles.extend(geocell.all_adjacents(tile)) kind = kloombaDb.Flowerbed.kind() #prepare async requests for i in tiles: request = GqlQuery( 'SELECT * FROM Flowerbed WHERE ANCESTOR IS :1', Key.from_path(kind, i)).run() requests.append(request) for i in requests: for j in i: fb = r.flowerbed.add() fb.timestamp = int(time.mktime(j.timestamp.timetuple())) fb.id = str(j.key()) fb.latitude = int(j.point.lat * 1000000) fb.longitude = int(j.point.lon * 1000000) fb.owner = j.owner_public_id fb.flowers = j.flowers gamer.put() if self.request.get('debug', False): self.response.out.write(r) else: self.response.out.write(r.SerializeToString())
def viewAirportsCloseTo2(request, countries, queryType, query, searchDone, nrAirports=10): try: location = query.replace("(", "").replace(")", "") firstToken = location.split(",")[0] lastToken = location.split(",")[1] #logging.error("Tokens %s %s", firstToken,lastToken ) point = GeoPt(float(firstToken), float(lastToken)) except: logging.error("Failed to convert %s", location) return viewAirportsFailed( request, countries, queryType, query, searchDone, "Failed to convert location" + query + " to valid point") pointLat = int(point.lat) pointLon = int(point.lon) maxLat = int(pointLat + 5) minLat = int(pointLat - 5) maxLon = int(pointLon + 5) minLon = int(pointLon - 5) logging.debug("First searcg WHERE pointLon < %s AND pointLon > %s", maxLon, minLon) airportQuery1 = models.Airport.gql( "Where pointLat < :1 AND pointLat > :2 ", maxLat, minLat).fetch(1000) airports = [] for qAirport in airportQuery1: if qAirport.pointLon < maxLon and qAirport.pointLon > minLon: airports.append(qAirport) logging.debug("After toArray and Lat filtering length=%s", len(airports)) airports.sort(cmp=lambda x, y: models.Airport.closestToPointSimple( x, y, pointLat, pointLon)) closeAirports = airports[0:nrAirports] closeAirports.sort( cmp=lambda x, y: models.Airport.closestToPointExact(x, y, point)) closeAirports = closeAirports[0:nrAirports] return render_to_response( 'viewAirport.html', { 'pointCloseTo': point, 'airports': closeAirports, 'countries': countries, 'searchDone': searchDone, 'title': 'Flyingsim.com: ' + searchDone })
def DoPost(self): logging.info("Updating player info") pseudonym = escape(self.request.get('pseudonym')) if pseudonym != self.player.pseudonym and len(pseudonym) > 15: raise Exception( "If you update a pseudonym, it must be no more thn 15 characters long." ) self.player.pseudonym = pseudonym (lat, lon) = self.request.get('location').split(',') self.player.location = GeoPt(lat, lon) self.player.put() self.redirect('/profile')
def get(self): if self.request.get('cat'): gc = GeoCode() gc.cat = self.request.get('cat') gc.feasible = not not self.request.get('success') if gc.feasible: lat = self.request.get('lat') lon = self.request.get('lon') assert lat and lon gc.location = GeoPt(lat=float(lat), lon=float(lon)) logging.info('%s, %s : %s' % (gc.feasible, gc.location, gc.cat)) gc.put() folders = load_folders() discard = {} success = {} for geocode in GeoCode.all(): discard[geocode.cat] = True if geocode.feasible: success[geocode.cat] = True chosen_fold = None for count, fold in folders: if fold in discard: continue subs = fold.split(" / ") should_discard = False for i in range(1, len(subs)): if ' / '.join(subs[0:i]) in discard: should_discard = True break if should_discard: continue chosen_fold = fold break total_done = 0 for count, fold in folders: subs = fold.split(" / ") for i in range(1, 1 + len(subs)): if ' / '.join(subs[0:i]) in success: total_done += count break template_values = { 'category': chosen_fold, 'frequency': count, 'total_done': total_done } path = os.path.join(os.path.dirname(__file__), 'mainpage.tpl') self.response.out.write(template.render(path, template_values))
def _dichotomy_lon(points, list=[]): ''' Añade puntos en la mitad, pero solo modificando la longitud ''' if len(list) > 25: return list if points[0] == points[1]: return list dLon = round((points[0].lon - points[1].lon), 3) / 2 if fabs(dLon) < 0.001: return list pointN = GeoPt(lat=points[0].lat, lon=round(points[0].lon - dLon, 3)) _dichotomy_lon((points[0], pointN), list=list) _dichotomy_lon((pointN, points[1]), list=list) list.append(pointN) return list
def save(self, **kwargs): lat, long = self.cleaned_data['location'].split(',') poi = PrivatePlace.get_or_insert(id = self.cleaned_data['poi_id'], name = '', location = GeoPt(float(lat), float(long)), address = kwargs.get('address', ''), user = kwargs['user']) alert = Alert.update_or_insert( id = kwargs.get('id', None), name = self.cleaned_data['name'], description = self.cleaned_data['description'], date_starts = self.cleaned_data['starts'], date_ends = self.cleaned_data['ends'], poi = poi, user = kwargs['user'], done = self.cleaned_data.get('done', False), active = None # self.cleaned_data.get('active', True) ) return alert
def _dichotomy(points, list=[]): ''' Añade puntos en la mitad, similar a una diagonal ''' if len(list) > 25: return list if points[0] == points[1]: return list dLat = round((points[0].lat - points[1].lat), 3) / 2 dLon = round((points[0].lon - points[1].lon), 3) / 2 if fabs(dLat) < 0.001 and fabs(dLon) < 0.001: return list pointN = GeoPt(lat=round(points[0].lat - dLat, 3), lon=round(points[0].lon - dLon, 3)) _dichotomy((points[0], pointN), list=list) _dichotomy((pointN, points[1]), list=list) list.append(pointN) return list
def get(self, request): if request.name is not None and len(request.name) < 3: raise ApplicationError("Name too small") from google.appengine.ext.db import GeoPt poi = GeoPt(request.lat, request.lon) from libs.httplib2 import Http import memcache mem = memcache.mem.Client() r = Http(cache=mem) if request.name is not None: from urllib import quote_plus name = quote_plus(request.name.strip()) url = 'http://andaluciapeople.com/granada/sitios.json/lat/%s/lng/%s/?q=%s' % (poi.lat, poi.lon, name) else: url = 'http://andaluciapeople.com/granada/sitios.json/lat/%s/lng/%s/' % (poi.lat, poi.lon) response, content = r.request(url, method='GET', headers={ 'User-Agent' : 'Georemindme:0.1' } ) # from mapsServices.places.GPRequest import GPRequest # google_places = GPRequest() # results = google_places.do_search(pos=poi, name=request.name) # response = [Site(name=r['name'], # lat=r['geometry']['location']['lat'], # lon=r['geometry']['location']['lng'], # address=r.get('formatted_address') # ) for r in results['results'][0:8] # ] if response['status'] != 200: raise ApplicationError("Error in request") try: import json as simplejson except: from django.utils import simplejson json = simplejson.loads(content) results = [Site(name=r['nombre'], lat=r['lat'], lon=r['lng'], ) for r in json[:7] ] return Sites(sites=results)
def ask(request): """ API Method - /ask Creates a new Question and adds it to the datastore @method POST @param question: the text of the question @param latitude: latitude of the location @param longitude: longitude of the location @param pay_key: the pay key from a successful PayPal purchase @returns stock success or failure JSON response along with the question and user objects. """ # authenticated user user = Session().get("user") # required parameters question = request.REQUEST.get("question") latitude = float(request.REQUEST.get("latitude")) longitude = float(request.REQUEST.get("longitude")) pay_key = request.REQUEST.get("pay_key") # Using the PayKey you could validate it using PayPal APIs # to confirm that a user paid and the transaction is complete. # This is left up to the curious coder to implement :) # Create the question with the required fields and tie it # to the authenticated user q = Question(question=question, location=GeoPt(latitude, longitude), user=user) q.update_location() q.put() # return stock JSON with the Question object details return _json_response(question=q.to_json(), user=user.to_json())
def get(self): user = users.get_current_user() r = FlowerbedAdd() if self.request.get('lat') and self.request.get('lon'): #TODO: check if flowerbed is far enough from others #TODO: check if flowerbed is close enough to user lat = int(self.request.get('lat')) / 1000000.0 lon = int(self.request.get('lon')) / 1000000.0 gamer_key = Key.from_path(kloombaDb.Gamer.kind(), user.user_id()) gamer_hash = hashlib.md5(user.user_id() + SALT).hexdigest() r.timestamp = int(time.time()) #get backpack bp_beds = GqlQuery( 'SELECT * FROM Backpack WHERE ANCESTOR IS :1 AND name=:2', gamer_key, 'flowerbed').get() if bp_beds.amount: #lower backpack bp_beds.amount -= 1 bp_beds.put() #add flowerbed point = GeoPt(lat, lon) cell = geocell.compute(point, RULES['GEO_RESOLUTION']) flowerbed = kloombaDb.Flowerbed( parent=Key.from_path(kloombaDb.Flowerbed.kind(), cell)) flowerbed.point = point flowerbed.tile = cell flowerbed.owner = user.user_id() flowerbed.owner_public_id = gamer_hash flowerbed.put() #save to memcache memcache.set(str(flowerbed.key()), flowerbed) #add possession possession = kloombaDb.Possession(parent=gamer_key) possession.flowerbed = flowerbed possession.put() backpack = GqlQuery( 'SELECT * FROM Backpack WHERE ANCESTOR IS :1', gamer_key).run() #set timestamps r.flowerbed.timestamp = int(time.time()) r.backpack.timestamp = int(time.time()) #set flowerbed r.flowerbed.id = str(flowerbed.key()) r.flowerbed.latitude = int(self.request.get('lat')) r.flowerbed.longitude = int(self.request.get('lon')) r.flowerbed.owner = gamer_hash r.flowerbed.flowers = 0 #set backpack for i in backpack: bp = r.backpack.item.add() bp.name = i.name bp.amount = i.amount if self.request.get('debug', False): self.response.out.write(r) else: self.response.out.write(r.SerializeToString())