Exemplo n.º 1
0
    def query(self, sw_lat, sw_lng, ne_lat, ne_lng, max_results=1000):
        bounds = geotypes.Box(float(ne_lat), float(ne_lng), float(sw_lat),
                              float(sw_lng))

        base_query = Shop.all()

        return Shop.bounding_box_fetch(base_query, bounds, max_results)
Exemplo n.º 2
0
 def get_user_data(self,
                   user=None,
                   lat_north=90,
                   lng_west=-180,
                   range_lat=-180,
                   range_lng=360,
                   max_results=2000):
     # log.info("GeoRange: (%6.4f, %6.4f) ZoomStep: (%6.4f, %6.4f)" % (lat_north, lng_west, range_lat, range_lng))
     # log.info("Range: (%6.4f - %6.4f), (%6.4f - %6.4f)" % (min(90, max(-90, lat_north + range_lat)), lat_north, min(180, max(-180, lng_west + range_lng)), lng_west))
     if user:
         # not sure why Google was giving latitudes outside of the allowable range near the International Date Line at zoom level 3,
         # but cap it to the max anyway here. this might result in incorrectly drawn tiles near there, but oh well.
         if lng_west < -180:
             lng_west = -180
         return UserVenue.bounding_box_fetch(
             UserVenue.all().filter('user ='******'-last_checkin_at'
             ),  #TODO find a way to specify this elsewhere!!
             geotypes.Box(min(90, max(-90, lat_north + range_lat)),
                          min(180, max(-180, lng_west + range_lng)),
                          lat_north, lng_west),
             max_results,
         )
     else:
         return []
Exemplo n.º 3
0
def nearby_items():
    response.content_type = 'application/json'

    if (nearby_param_validate(request) == False):
        return {'status': 'error-query-paras'}

    try:
        if (request.query.type == 'box'):
            bounds = geotypes.Box(float(request.query.north),
                                  float(request.query.east),
                                  float(request.query.south),
                                  float(request.query.west))
        elif (request.query.type == 'center'):
            center = geotypes.Point(float(request.query.lat),
                                    float(request.query.lon))
    except:
        return {'status': 'invalid-query-paras'}

    max_results = int(request.query.maxresults or '100')
    max_distance = float(request.query.maxdistance or '80000')  # 80 km ~ 50 mi

    try:
        base_query = Item.all()
        if (request.query.type == 'box'):
            results = Item.bounding_box_fetch(base_query,
                                              bounds,
                                              max_results=max_results)
        elif (request.query.type == 'center'):
            results = Item.proximity_fetch(base_query,
                                           center,
                                           max_results=max_results,
                                           max_distance=max_distance)
        return results_dump(results)
    except:
        return {'status': 'error-database-query'}
def getClosestRecording(lat, lon, search_radius, random_radius):
    import geoUtils

    qry = Recording.query(Recording.approved == REC_APPROVED_STATE_TRUE)
    latMin, lonMin, latMax, lonMax = geoUtils.getBoxCoordinates(lat, lon, search_radius)
    logging.debug("Lat={}, Lon={}, radius={}, latMin={}, lonMin={}, latMax={}, lonMax={}".format(
        lat, lon, search_radius, latMin, lonMin, latMax, lonMax))
    box = geotypes.Box(latMax, lonMax, latMin, lonMin)  # north, east, south, west

    recs = Recording.bounding_box_fetch(qry, box)
    num_results = len(recs)

    if num_results==0:
        return None
    if num_results==1:
        return recs[0]
    else:
        minDstRecs = []
        minDst = sys.maxint
        for r in qry:
            dst = geoUtils.distance((lat,lon),(r.location.lat, r.location.lon))
            if dst<(minDst-random_radius):
                minDst = dst
                minDstRecs = [r]
            elif dst<(minDst+random_radius):
                minDstRecs.append(r)
        size = len(minDstRecs)
        randomIndx = int(size*random.random())
        return minDstRecs[randomIndx]
Exemplo n.º 5
0
def square_bounding_box_centered_at(latitude, longitude, side_in_miles):
    side_in_meters = miles_to_meters(side_in_miles)
    latitude_halfside_in_degrees = latitudinal_degrees_from_meters(
        side_in_meters) / 2.0
    longitude_halfside_in_degrees = longitudinal_degrees_from_meters_at_latitude(
        side_in_meters, latitude) / 2.0
    return geotypes.Box(north=latitude + latitude_halfside_in_degrees,
                        east=longitude + longitude_halfside_in_degrees,
                        south=latitude - latitude_halfside_in_degrees,
                        west=longitude - longitude_halfside_in_degrees)
Exemplo n.º 6
0
    def test_Box(self):
        # an invalid box
        self.assertRaises(ValueError, geotypes.Box, 95, 0, 0, 0)

        # a valid box
        box = geotypes.Box(37, -122, 34, -125)
        self.assertEquals(37, box.north)
        self.assertEquals(34, box.south)
        self.assertEquals(-122, box.east)
        self.assertEquals(-125, box.west)

        # assert north can't be under south
        self.assertRaises(ValueError, box._set_north, 32)
        self.assertRaises(ValueError, box._set_south, 39)

        self.assertTrue(isinstance(box.__str__(), str))

        # valid boxes
        self.assertEquals(geotypes.Box(37, -122, 34, -125),
                          geotypes.Box(34, -122, 37, -125))
Exemplo n.º 7
0
def getClosestActiveFermata(lat, lon, radius):
    origin_point = (lat, lon)
    latMin, lonMin, latMax, lonMax = geoUtils.getBoxCoordinates(
        lat, lon, radius)
    box = geotypes.Box(latMax, lonMax, latMin,
                       lonMin)  # north, east, south, west
    qry = Fermata.query(Fermata.active == True)
    fermate = Fermata.bounding_box_fetch(qry, box)
    if fermate:
        return min(
            fermate,
            key=lambda f: geoUtils.distance(origin_point,
                                            (f.location.lat, f.location.lon)))
Exemplo n.º 8
0
 def get_data(self, zoom, layer, lat_north, lng_west, range_lat, range_lng,
              category, metro):
     log.info("GeoRange: (%6.4f, %6.4f) ZoomStep: (%6.4f, %6.4f)" %
              (lat_north, lng_west, range_lat, range_lng))
     log.info("Range: (%6.4f - %6.4f), (%6.4f - %6.4f)" %
              (min(90, max(-90, lat_north + range_lat)), lat_north,
               min(180, max(-180, lng_west + range_lng)), lng_west))
     return DataPoint.bounding_box_fetch(
         DataPoint.all().filter('category',
                                category).filter('metro', metro),
         geotypes.Box(min(90, max(-90, lat_north + range_lat)),
                      min(180, max(-180, lng_west + range_lng)), lat_north,
                      lng_west),
         max_results=1000)
Exemplo n.º 9
0
 def get_all_data(self,
                  user=None,
                  lat_north=90,
                  lng_west=-180,
                  range_lat=-180,
                  range_lng=360,
                  max_results=2000):
     if user:
         self.get_user_data(user, lat_north, lng_west, range_lat, range_lng,
                            max_results)
     else:
         return UserVenue.bounding_box_fetch(
             UserVenue.all().order('-last_checkin_at'),
             geotypes.Box(min(90, max(-90, lat_north + range_lat)),
                          min(180, max(-180, lng_west + range_lng)),
                          lat_north, lng_west),
             max_results,
         )
Exemplo n.º 10
0
    def get(self):
        def _simple_error(message, code=400):
            self.error(code)
            self.response.out.write(
                simplejson.dumps({
                    'status': 'error',
                    'error': {
                        'message': message
                    },
                    'results': []
                }))
            return None

        self.response.headers['Content-Type'] = 'application/json'
        query_type = self.request.get('type')
        user = self.request.get('user')

        if not query_type in ['proximity', 'bounds', 'user', 'default']:
            return _simple_error(
                'type parameter must be '
                'one of "proximity", "bounds", "user".',
                code=400)

        if query_type == 'proximity':
            try:
                center = geotypes.Point(float(self.request.get('lat')),
                                        float(self.request.get('lon')))
            except ValueError:
                return _simple_error(
                    'lat and lon parameters must be valid latitude '
                    'and longitude values.')
        elif query_type == 'bounds':
            try:
                bounds = geotypes.Box(float(self.request.get('north')),
                                      float(self.request.get('east')),
                                      float(self.request.get('south')),
                                      float(self.request.get('west')))
            except ValueError:
                return _simple_error(
                    'north, south, east, and west parameters must be '
                    'valid latitude/longitude values.')

        max_results = 100
        if self.request.get('maxresults'):
            max_results = int(self.request.get('maxresults'))

        max_distance = 8000000  # 80 km ~ 50 mi
        if self.request.get('maxdistance'):
            max_distance = float(self.request.get('maxdistance'))

        results = []
        try:
            # Can't provide an ordering here in case inequality filters are used.
            base_query = Listing.all()

            #if property_type:
            #base_query.filter('property_type =', property_type)

            # Natural ordering chosen to be public school enrollment.
            #base_query.order('-')

            # Perform proximity or bounds fetch.
            if query_type == 'proximity':
                results = Listing.proximity_fetch(base_query,
                                                  center,
                                                  max_results=max_results,
                                                  max_distance=max_distance)

            elif query_type == 'bounds':
                results = Listing.bounding_box_fetch(base_query,
                                                     bounds,
                                                     max_results=max_results)

            elif query_type == 'user':
                limit = self.request.get("limit")
                offset = self.request.get("offset")
                if not limit:
                    limit = 1000
                else:
                    limit = int(limit)
                if not offset:
                    offset = 0
                else:
                    offset = int(offset)
                results = base_query.fetch(limit, offset)

            public_attrs = Listing.public_attributes()

            results_obj = [
                _merge_dicts(
                    {
                        'lat': result.location.lat,
                        'lng': result.location.lon,
                    },
                    dict([(attr, getattr(result, attr))
                          for attr in public_attrs])) for result in results
            ]

            self.response.out.write(
                simplejson.dumps({
                    'status': 'success',
                    'results': results_obj,
                }))
        except:
            return _simple_error(str(sys.exc_info()[1]), code=500)
Exemplo n.º 11
0
    def doSearch(self, cursor_key, **kwargs):
        query_type = self.request["query_type"]

        if not query_type in ['proximity', 'bounds']:
            return _simple_error(
                'El parámetro de búsqueda debe ser "proximity" o "bounds".',
                code=400)

        if query_type == 'proximity':
            try:
                center = geotypes.Point(float(self.request['lat']),
                                        float(self.request['lon']))
            except ValueError:
                return _simple_error(
                    'lat and lon parameters must be valid latitude and longitude values.',
                    code=400)

        elif query_type == 'bounds':
            try:
                bounds = geotypes.Box(float(self.request['north']),
                                      float(self.request['east']),
                                      float(self.request['south']),
                                      float(self.request['west']))
            except ValueError:
                return _simple_error(
                    'north, south, east, and west parameters must be valid latitude/longitude values.',
                    code=400)

        max_distance = 80000  # 80 km ~ 50 mi
        if self.request.has_key('max_distance'):
            max_distance = float(self.request['max_distance'])

        #---extirpado--
        base_query, price_data = create_query_from_dict(
            self.request, PropertyIndex)
        #---extirpado--

        max_results = MAX_QUERY_RESULTS
        if self.request.has_key('max_results'):
            max_results = int(self.request['max_results'])

        results, the_box, new_cursor_key = Property.bounding_box_fetch(
            base_query,
            bounds,
            max_results=max_results,
            cost_function=None,
            cursor_key=cursor_key)

        total_count = 'cientos'
        viewing_count = len(results)

        return {
            'properties':
            results,
            'total_count':
            total_count,
            'viewing':
            viewing_count,
            'the_box':
            '<br/>' + the_box + '<br/><br/>cursor_key:' + str(cursor_key),
            'cursor_key':
            new_cursor_key,
            'price_data':
            price_data
        }
Exemplo n.º 12
0
    def select(self, action):
        obj_list = []
        max_features = action.maxfeatures or 1000
        if action.id:
            obj = self.model.get_by_id(action.id)
            if obj:
                obj_list = [obj]
        else:
            obj_list = self.model.all()
            if action.attributes:
                current_key = None
                for key, value in action.attributes.items():
                    if isinstance(value, dict):
                        obj_list = obj_list.filter(
                            "%s %s" %
                            (value['column'],
                             self.query_action_string[value['type']]),
                            value['value'])
                    else:
                        try:
                            value = int(value)
                        except:
                            pass
                        obj_list = obj_list.filter("%s =" % key, value)

            if action.bbox:
                #geocell likes N,E,S,W bbox with
                W, S, E, N = action.bbox
                #also needs to be valid wgs84 coords
                W = max(W, -180)
                E = min(E, 180)
                S = max(S, -90)
                N = min(N, 90)
                obj_list = self.model.bounding_box_fetch(
                    obj_list,
                    geotypes.Box(N, E, S, W),
                    max_results=max_features)

        return_list = []
        for obj in obj_list[:max_features]:
            props = {}
            #get attribs for model
            for key in self.model.fields():
                if not key in self.excluded_fields:
                    try:
                        props[key] = getattr(obj, key)
                    except:
                        props[key] = None
            #get additional attribs for expando stuff
            for key in obj.dynamic_properties():
                try:
                    props[key] = getattr(obj, key)
                except:
                    props[key] = None
            try:
                geom = from_wkt(obj.geometry)
            except:
                logging.error('fail on obj %s' % key)
                continue
            return_list.append(
                Feature(id=action.id,
                        geometry=from_wkt(obj.geometry),
                        srs=self.srid_out,
                        props=props))
        return return_list
Exemplo n.º 13
0
  def get(self):
    def _simple_error(message, code=400):
      self.error(code)
      self.response.out.write(simplejson.dumps({
        'status': 'error',
        'error': { 'message': message },
        'results': []
      }))
      return None
      
    
    self.response.headers['Content-Type'] = 'application/json'
    query_type = self.request.get('type')
    
    if not query_type in ['proximity', 'bounds']:
      return _simple_error('type parameter must be '
                           'one of "proximity", "bounds".',
                           code=400)
    
    if query_type == 'proximity':
      try:
        center = geotypes.Point(float(self.request.get('lat')),
                                float(self.request.get('lon')))
      except ValueError:
        return _simple_error('lat and lon parameters must be valid latitude '
                             'and longitude values.')
    elif query_type == 'bounds':
      try:
        bounds = geotypes.Box(float(self.request.get('north')),
                              float(self.request.get('east')),
                              float(self.request.get('south')),
                              float(self.request.get('west')))
      except ValueError:
        return _simple_error('north, south, east, and west parameters must be '
                             'valid latitude/longitude values.')
    
    max_results = 100
    if self.request.get('maxresults'):
      max_results = int(self.request.get('maxresults'))
    
    max_distance = 80000 # 80 km ~ 50 mi
    if self.request.get('maxdistance'):
      max_distance = float(self.request.get('maxdistance'))

    school_type = None
    if self.request.get('schooltype'):
      try:
        school_type = int(self.request.get('schooltype'))
      except ValueError:
        return _simple_error('If schooltype is provided, '
                             'it must be a valid number, as defined in '
                             'http://nces.ed.gov/ccd/psadd.asp#type')

    grade_range = None
    if self.request.get('mingrade') or self.request.get('maxgrade'):
      try:
        grade_range = (int(self.request.get('mingrade')),
                       int(self.request.get('maxgrade')))
        if grade_range[0] > grade_range[1]:
          return _simple_error('mingrade cannot exceed maxgrade.')
      except ValueError:
        return _simple_error('If mingrade or maxgrade is provided, '
                             'both must be valid integers.')
      
    try:
      # Can't provide an ordering here in case inequality filters are used.
      base_query = PublicSchool.all()

      # Add in advanced options (rich query).
      if grade_range:
        if grade_range[0] == grade_range[1]:
          # WARNING: don't forget to build this edge case index!
          base_query.filter('grades_taught =', grade_range[0])
        else:
          (base_query.filter('grades_taught >=', grade_range[0])
                     .filter('grades_taught <=', grade_range[1]))
        
        # App Engine requires inequality filtered properties to be
        # the first ordering. Also apply this ordering for grades_taught =
        # filters to simplify indexes.
        base_query.order('grades_taught')
      
      if school_type:
        base_query.filter('school_type =', school_type)
      
      # Natural ordering chosen to be public school enrollment.
      base_query.order('-enrollment')
      
      # Perform proximity or bounds fetch.
      if query_type == 'proximity':
        results = PublicSchool.proximity_fetch(
            base_query,
            center, max_results=max_results, max_distance=max_distance)
      elif query_type == 'bounds':
        results = PublicSchool.bounding_box_fetch(
            base_query,
            bounds, max_results=max_results)
      
      public_attrs = PublicSchool.public_attributes()
      
      results_obj = [
          _merge_dicts({
            'lat': result.location.lat,
            'lng': result.location.lon,
            'lowest_grade_taught':
              min(result.grades_taught) if result.grades_taught else None,
            'highest_grade_taught':
              max(result.grades_taught) if result.grades_taught else None,
            },
            dict([(attr, getattr(result, attr))
                  for attr in public_attrs]))
          for result in results]

      self.response.out.write(simplejson.dumps({
        'status': 'success',
        'results': results_obj
      }))
    except:
      return _simple_error(str(sys.exc_info()[1]), code=500)