Example #1
0
def nearby():
	print 'geohash.bounding box'
	print geohash.bbox('tdr1w')
	print 'geohash neighbours'
	print geohash.neighbors('tdr1wxype953')
	print 'geohash expand'
	print geohash.expand('tdr1wxype953')
Example #2
0
 def do_geohashtogeojson(self, geoh):
     """Build GeoJSON corresponding to geohash given as parameter.
     GEOHASHTOGEOJSON u09vej04 [NEIGHBORS 0]"""
     geoh, with_neighbors = self._match_option('NEIGHBORS', geoh)
     bbox = geohash.bbox(geoh)
     north = bbox['n']
     south = bbox['s']
     east = bbox['e']
     west = bbox['w']
     if with_neighbors != '0':
         neighbors = geohash.neighbors(geoh)
         for neighbor in neighbors:
             bbox = geohash.bbox(neighbor)
             if bbox['n'] > north:
                 north = bbox['n']
             if bbox['s'] < south:
                 south = bbox['s']
             if bbox['e'] > east:
                 east = bbox['e']
             if bbox['w'] < west:
                 west = bbox['w']
     geojson = {
         "type": "Polygon",
         "coordinates": [[
             [west, north],
             [east, north],
             [east, south],
             [west, south],
             [west, north]
         ]]
     }
     print(white(json.dumps(geojson)))
Example #3
0
    def _get_named_neighbors(self, gh):
        ghs = {}
        gh_bbox = geohash.bbox(gh)
        for g in geohash.expand(gh):
            if gh == g:
                continue
            b = geohash.bbox(g)

            if gh_bbox['n'] == b['n'] and gh_bbox['w'] == b["e"]:
                ghs['L'] = g
            elif gh_bbox['n'] == b['n'] and gh_bbox['e'] == b["w"]:
                ghs['R'] = g

            elif gh_bbox['e'] == b['e'] and gh_bbox['n'] == b["s"]:
                ghs['U'] = g
            elif gh_bbox['e'] == b['e'] and gh_bbox['s'] == b["n"]:
                ghs['D'] = g

            elif gh_bbox['n'] == b['s'] and gh_bbox['w'] == b['e']:
                ghs['LU'] = g
            elif gh_bbox['n'] == b['s'] and gh_bbox['e'] == b['w']:
                ghs['RU'] = g

            elif gh_bbox['s'] == b['n'] and gh_bbox['w'] == b['e']:
                ghs['LD'] = g
            elif gh_bbox['s'] == b['n'] and gh_bbox['e'] == b['w']:
                ghs['RD'] = g

        return ghs
Example #4
0
def nearby():
    print 'geohash.bounding box'
    print geohash.bbox('tdr1w')
    print 'geohash neighbours'
    print geohash.neighbors('tdr1wxype953')
    print 'geohash expand'
    print geohash.expand('tdr1wxype953')
Example #5
0
def get_neighborhood_by_corners(corner_sw, corner_ne, precision=6):
    hashcode_sw = _get_geohash_from_tuple(corner_sw, precision)
    hashcode_ne = _get_geohash_from_tuple(corner_ne, precision)
    (delta_lat, delta_lon) = _get_delta_from_geohash(hashcode_sw)
    box_sw, box_ne = geohash.bbox(hashcode_sw), geohash.bbox(hashcode_ne)
    step_lat = int(math.ceil((box_ne['s'] - box_sw['s']) / delta_lat))
    step_lon = int(math.ceil((box_ne['e'] - box_sw['e']) / delta_lon))
    dir_set = [(i, j) for i in range(step_lat + 1)
               for j in range(step_lon + 1)]
    hashes = [
        get_neighbor_by_direction(hashcode_sw, dir_element)
        for dir_element in dir_set
    ]
    return hashes
Example #6
0
def geohash_rect(hashcode, point):
    #        (n,w) (n,p[1])--p1  (n,e)
    #          @------*---@----------@
    #          |      |              |
    #          |      |              |
    #          |      |              |
    #          |      |              |
    #          @      |   c          @
    #          |      |              |
    # (p[0],w) *------p--------------* (p[0], e)--p2
    #    |     |      |              |
    #    p4    |      |              |
    #          @------*---@----------@
    #       (s,w)  (s,p[1])--p3  (s,e)

    box = geohash.bbox(hashcode)
    p1 = [box['n'], point[1]]
    p2 = [point[0], box['e']]
    p3 = [box['s'], point[1]]
    p4 = [point[0], box['w']]
    top = spherical_distance(point, p1)
    bottom = spherical_distance(point, p3)
    left = spherical_distance(point, p4)
    right = spherical_distance(point, p2)
    return (top, bottom, left, right)
Example #7
0
    def get_cell(self, lon, lat):
        """Get the cell that a coordinate pair (lat, lon) falls within."""
        res = self.es.search(
            index=self.index,
            body={
                "query": {
                    "filtered": {
                        "filter": {
                            "geo_distance": {
                                "distance": '0.1km',
                                'geometry.coordinates': [lon, lat]  # lon, lat
                            }
                        },
                    },
                },
                'aggregations': {
                    'grid': {
                        'geohash_grid': {
                            'field': 'geometry.coordinates',
                            'precision': self.precision
                        }
                    }
                }
            }
        )

        buckets = res['aggregations']['grid']['buckets']

        if buckets:
            cell_hash = buckets[0]['key']
            cell = geohash.bbox(cell_hash)
        else:
            cell = None

        return cell
Example #8
0
def geohash_shape(shape, precision, mode='intersect', threshold=None):
    """
    Find list of geohashes to cover the shape
    :param shape: shape to cover
    :type shape: BaseGeometry
    :param precision: geohash precision
    :type precision: int
    :param mode: 'intersect' - all geohashes intersect the shape
                               use 'threashold' option to specify a percentage of least coverage
                 'inside' - all geohashes inside the shape
                 'center' - all geohashes whose center is inside the shape
    :type mode: str
    :param threshold: percentage of least coverage
    :type threshold: float
    :return: list of geohashes
    :rtype: list
    """
    (min_lon, min_lat, max_lon, max_lat) = shape.bounds

    hash_south_west = geohash.encode(min_lat, min_lon, precision)
    hash_north_east = geohash.encode(max_lat, max_lon, precision)

    box_south_west = geohash.decode_exactly(hash_south_west)
    box_north_east = geohash.decode_exactly(hash_north_east)

    per_lat = box_south_west[2] * 2
    per_lon = box_south_west[3] * 2

    lat_step = int(round((box_north_east[0] - box_south_west[0]) / per_lat))
    lon_step = int(round((box_north_east[1] - box_south_west[1]) / per_lon))

    hash_list = []

    for lat in range(0, lat_step + 1):
        for lon in range(0, lon_step + 1):
            next_hash = neighbor(hash_south_west, [lat, lon])
            if mode == 'center':
                (lat_center, lon_center) = decode(next_hash)
                if shape.contains(Point(lon_center, lat_center)):
                    hash_list.append(next_hash)
            else:
                next_bbox = geohash.bbox(next_hash)
                next_bbox_geom = box(next_bbox['w'], next_bbox['s'],
                                     next_bbox['e'], next_bbox['n'])

                if mode == 'inside':
                    if shape.contains(next_bbox_geom):
                        hash_list.append(next_hash)
                elif mode == 'intersect':
                    if shape.intersects(next_bbox_geom):
                        if threshold is None:
                            hash_list.append(next_hash)
                        else:
                            intersected_area = shape.intersection(
                                next_bbox_geom).area
                            if (intersected_area /
                                    next_bbox_geom.area) >= threshold:
                                hash_list.append(next_hash)

    return hash_list
Example #9
0
 def addGeohashToCountry(self, countryCode, geohash):
     ''' using some complex geometry unioning here! '''
     if geohash is None:
         return
     # Here's an optimisation - without which a 45M POI run was taking well over
     # 12 hours. We're drawing the largest regions using 3-digit geohashs, and
     # each POI will live in one of these. The calculation of "within" is really
     # expensive and I'd like to avoid doing it - so to dramatically cut the
     # time, the best way is to dramatically cut the number of times it's done.
     if len(geohash) != 3:
         return
     b = geohasher.bbox(geohash)
     polygon = Polygon([
         (b['e'], b['n']), \
         (b['w'], b['n']), \
         (b['w'], b['s']), \
         (b['e'], b['s']), \
         (b['e'], b['n']) ])
     try:
         countryPolygon = self.countrysPolygon[countryCode]
         if not polygon.within(countryPolygon):
             #multipoly = cascaded_union([countryPolygon, polygon])
             multipoly = countryPolygon.union(polygon)
             self.countrysPolygon[countryCode] = multipoly
     except KeyError:
         self.countrysPolygon[countryCode] = polygon
Example #10
0
 def addGeohashToCountry(self, countryCode, geohash):
   ''' using some complex geometry unioning here! '''
   if geohash is None:
     return
   # Here's an optimisation - without which a 45M POI run was taking well over
   # 12 hours. We're drawing the largest regions using 3-digit geohashs, and
   # each POI will live in one of these. The calculation of "within" is really
   # expensive and I'd like to avoid doing it - so to dramatically cut the
   # time, the best way is to dramatically cut the number of times it's done.
   if len(geohash) != 3:
     return
   b = geohasher.bbox(geohash)
   polygon = Polygon([
       (b['e'], b['n']), \
       (b['w'], b['n']), \
       (b['w'], b['s']), \
       (b['e'], b['s']), \
       (b['e'], b['n']) ])
   try:
     countryPolygon = self.countrysPolygon[countryCode]
     if not polygon.within(countryPolygon):
       #multipoly = cascaded_union([countryPolygon, polygon])
       multipoly = countryPolygon.union(polygon)
       self.countrysPolygon[countryCode] = multipoly
   except KeyError:
     self.countrysPolygon[countryCode] = polygon
Example #11
0
    def geohash_lonlac(self, geohash_code: str, location: str = 's') -> float:
        """
        求geohash字符串的边界经度/维度

        Parameters
        ----------
        geohash_code : str
            目标geohash字符串
        location : str, optional
            geohash字符串对应的栅格
            s: 最小纬度, n: 最大纬度, e: 最大经度, w: 最小经度

        Returns
        ----------
        float
            所求的最大(最小)的经(维)度

        Example
        ---------
        >>> G = GeohashOperator()
        >>> G.geohash_lonlac('wx4ervz', 'n'), G.geohash_lonlac('wx4ervz', 'e')
        39.979248046875, 116.3671875

        >>> G.geohash_lonlac('wx4ervz', 's'), G.geohash_lonlac('wx4ervz', 'w')
        39.977874755859375, 116.36581420898438

        分别求一个geohash字符串对应围栏的最大纬度、最大经度; 最小维度、最小经度
        """
        return geohash.bbox(geohash_code)[location]
Example #12
0
    def get_edge_points(self):

        # search for edges
        edge_points = []
        edge_detection = [
            dict(empty='LU', notempty='', edge=('n', 'w')),
            dict(empty='RU', notempty='', edge=('n', 'e')),
            dict(empty='LD', notempty='', edge=('s', 'w')),
            dict(empty='RD', notempty='', edge=('s', 'e')),
            dict(empty=('LU',), notempty='LU', edge=('n', 'w')),
            dict(empty=('RU',), notempty='RU', edge=('n', 'e')),
            dict(empty=('LD',), notempty='LD', edge=('s', 'w')),
            dict(empty=('RD',), notempty='RD', edge=('s', 'e')),
        ]

        for gh in self.geohashes:
            neighbors = self._get_named_neighbors(gh)

            for detect in edge_detection:
                empty_passes = all(neighbors[direction] not in self.geohashes
                                   for direction in detect['empty'])
                notempty_passes = all(neighbors[direction] in self.geohashes
                                      for direction in detect['notempty'])

                if empty_passes and notempty_passes:
                    x_name, y_name = detect['edge']
                    b = geohash.bbox(gh)
                    edge_points.append((b[x_name], b[y_name]))

        return edge_points
Example #13
0
 def test_empty(self):
     self.assertEqual(geohash.bbox(''), {
         's': -90.0,
         'n': 90.0,
         'w': -180.0,
         'e': 180.0
     })
 def makeGoogleEarthBox(self,geo):
     bbox = geohash.bbox(geo)
     lowerleft = "%s,%s,elevation"%(bbox['w'],bbox['s'])
     upperleft = "%s,%s,elevation"%(bbox['w'],bbox['n'])
     lowerright = "%s,%s,elevation"%(bbox['e'],bbox['s'])
     upperright = "%s,%s,elevation"%(bbox['e'],bbox['n'])
     polygon = "%s %s %s %s %s"%(lowerleft,upperleft,upperright,lowerright,lowerleft)
     return polygon
Example #15
0
def geohash_polygon(gh):
    """
    Creates a polygon object given geohash alphanumeric string
    Args:
        gh: Geohash string
    """
    b = geohash.bbox(gh)
    box = [(b['w'], b['s']), (b['w'], b['n']), (b['e'], b['n']), (b['e'], b['s'],), (b['w'], b['s'])]
    return Polygon([box])
Example #16
0
  def render(self,ax,alpha=.7,usePyLeaflet=False,
      minValueThreshold=-float('Inf'),logScale=True,colormapname='BlueRed'):
    if not usePyLeaflet or colormapname=='nothingRed':
      alpha=1.0

    patches = []
    values = []
    colorvalues = []
    for d in self.countPerGeohash.keys():
      try:
        if (self.countPerGeohash[d]>minValueThreshold):
          bbox = geohash.bbox(d)
          rect = mpatches.Rectangle([ bbox['w'],
                        bbox['s']],
                        bbox['e'] - bbox['w'],
                        bbox['n'] - bbox['s'],
                        ec='none', lw=.1, fc='red', alpha=alpha)
          patches.append(rect)
          # values.append(self.countPerGeohash[d] \
          #   if self.countPerGeohash[d]<3 else self.countPerGeohash[d]+10)
          # colorvalues.append(self.countPerGeohash[d] \
          #   if self.countPerGeohash[d]<3 else self.countPerGeohash[d]+10)
          values.append(self.countPerGeohash[d])
          colorvalues.append(self.countPerGeohash[d])
      except KeyError:
        print("'"+d +"' is not a valid geohash.")

    try:
      maxval = max(values)
      minval = min(values)
    except ValueError:
      print('heatmap appears to be empty...')
      maxval = 1
      minval = 0

    p = PatchCollection(patches,cmap=plt.get_cmap(colormapname),alpha=alpha)
  #   if usePyLeaflet:
    if (len(values)<100):
      p.set_edgecolors(np.array(['black' for x in values]))
    else:
      p.set_edgecolors(np.array(['#333333' if x<=2 \
        else ('#666666' if x<=10 else 'black') for x in values]))
  #   else:
  #     p.set_edgecolors(np.array(['white' for x in values]))
    p.set_array(np.array(colorvalues))
    if logScale:
      p.set_norm(colors.LogNorm(vmin=.01, vmax=maxval))
    else:
      p.set_norm(colors.Normalize(vmin=0, vmax=maxval))
    ax.add_collection(p)
    ax.set_xlim(self.bbox['w'], self.bbox['e'])
    ax.set_ylim(self.bbox['s'], self.bbox['n'])
    divider = make_axes_locatable(ax)
    cbar = plt.colorbar(p)
    cbar.set_clim(vmin=max(0,minval),vmax=maxval)
    cbar.update_normal(p)
    return
Example #17
0
def geohash_h_w(hashcode):
    box = geohash.bbox(hashcode)
    hp1 = [box['n'], box['w']]
    hp2 = [box['s'], box['w']]
    wp1 = hp1
    wp2 = [box['n'], box['e']]
    h = spherical_distance(hp1, hp2)
    w = spherical_distance(wp1, wp2)
    return (h, w)
Example #18
0
def _geohash_to_shape(geohash):
    box = gh.bbox(geohash)
    coords = [
        [box["w"], box["s"]],
        [box["w"], box["n"]],
        [box["e"], box["n"]],
        [box["e"], box["s"]],
        [box["w"], box["s"]],
    ]
    return shape({"type": "Polygon", "coordinates": [coords]})
    def get_geocodes(self, bbox):
        """Return a list of keys covering a given area.

        Parameters:

        bbox -- Bounding box of the desired region.
        """

        # TODO: Make this more efficient for sparse areas of the map.
        w, s, e, n = map(float, bbox)

        n = min(C.MAXGHLAT, n)  # work around a geohash library
        s = min(C.MAXGHLAT, s)  # limitation

        assert(w <= e and s <= n)

        gcset = set()
        gc = geohash.encode(s, w, self.precision)

        bl = geohash.bbox(gc)   # Box containing point (s,w).

        s_ = bl['s'];
        while s_ < n:           # Step south to north.
            w_ = bl['w']

            gc = geohash.encode(s_, w_, self.precision)
            bb_sn = geohash.bbox(gc) # bounding box in S->N direction

            while w_ < e:       # Step west to east.
                gcset.add(gc)

                bb_we = geohash.bbox(gc) # in W->E direction
                w_ = bb_we['e']

                gc = geohash.encode(s_, w_, self.precision)

            s_ = bb_sn['n']

        assert(len(gcset) > 0)

        return [gc for gc in gcset]
Example #20
0
    def get_geocodes(self, bbox):
        """Return a list of keys covering a given area.

        Parameters:

        bbox -- Bounding box of the desired region.
        """

        # TODO: Make this more efficient for sparse areas of the map.
        w, s, e, n = map(float, bbox)

        n = min(C.MAXGHLAT, n)  # work around a geohash library
        s = min(C.MAXGHLAT, s)  # limitation

        assert (w <= e and s <= n)

        gcset = set()
        gc = geohash.encode(s, w, self.precision)

        bl = geohash.bbox(gc)  # Box containing point (s,w).

        s_ = bl['s']
        while s_ < n:  # Step south to north.
            w_ = bl['w']

            gc = geohash.encode(s_, w_, self.precision)
            bb_sn = geohash.bbox(gc)  # bounding box in S->N direction

            while w_ < e:  # Step west to east.
                gcset.add(gc)

                bb_we = geohash.bbox(gc)  # in W->E direction
                w_ = bb_we['e']

                gc = geohash.encode(s_, w_, self.precision)

            s_ = bb_sn['n']

        assert (len(gcset) > 0)

        return [gc for gc in gcset]
Example #21
0
def bbox2hash_one(bbox, hash_length):
    # just verify that the resulting hash boxes cover the whole bbox
    hashes = bbox2hash(bbox = bbox, hash_length = hash_length)

    arr = np.array\
        ([[x['s'],x['w'],x['n'],x['e']] \
          for x in [geohash.bbox(x) \
                    for x in bbox2hash(bbox,hash_length)]])
    assert min(arr[:,0]) <= bbox[0]
    assert min(arr[:,1]) <= bbox[1]
    assert max(arr[:,2]) >= bbox[2]
    assert max(arr[:,3]) >= bbox[3]
Example #22
0
 def test_intersects(self):
     bboxes = {
         "u09wj5": False,  # out
         "u09tvy": True,  # partially in
         "u09tvz": True,  # partially in
         "u09wj0": True,  # partially in
         "u09wj2": False,  # in
         "u09wje": True,  # edge crosses
     }
     for hashcode, expected in bboxes.items():
         bbox = geohash.bbox(hashcode)
         self.assertEqual(expected, self.polygon.intersects(bbox))
def random_latlong(geohash):
    dic = gh.bbox(geohash)
    # getting min, max lat/lng
    min_lng = dic.get('w')
    min_lat = dic.get('s')
    max_lng = dic.get('e')
    max_lat = dic.get('n')
    # generate random float between [min_lng, max_lng)
    long = np.random.uniform(min_lng, max_lng)
    # generate random float between [min_lat, max_lat)
    lat = np.random.uniform(min_lat, max_lat)
    return lat, long
Example #24
0
def get_bounding_geohash(n, w, s, e):
    """Get the bounding geohash for a given geobox. The geohash will be the
    smallest geohash that completely contains the given geobox (and will usually
    be quite a bit larger).
    """
    lat = 0.5 * (n + s)
    lng = 0.5 * (w + e)
    gh = geohash.encode(lat, lng)
    for x in xrange(12, 0, -1):
        hash_part = gh[:x]
        bbox = geohash.bbox(hash_part)
        if (bbox['n'] >= n and bbox['s'] <= s and bbox['w'] <= w and bbox['e'] >= e):
            return hash_part
    return ''
Example #25
0
 def expand(bbox, geoh, depth):
     neighbors = geohash.neighbors(geoh)
     for neighbor in neighbors:
         other = geohash.bbox(neighbor)
         if with_neighbors > depth:
             expand(bbox, neighbor, depth + 1)
         else:
             if other['n'] > bbox['n']:
                 bbox['n'] = other['n']
             if other['s'] < bbox['s']:
                 bbox['s'] = other['s']
             if other['e'] > bbox['e']:
                 bbox['e'] = other['e']
             if other['w'] < bbox['w']:
                 bbox['w'] = other['w']
Example #26
0
 def expand(bbox, geoh, depth):
     neighbors = geohash.neighbors(geoh)
     for neighbor in neighbors:
         other = geohash.bbox(neighbor)
         if with_neighbors > depth:
             expand(bbox, neighbor, depth + 1)
         else:
             if other['n'] > bbox['n']:
                 bbox['n'] = other['n']
             if other['s'] < bbox['s']:
                 bbox['s'] = other['s']
             if other['e'] > bbox['e']:
                 bbox['e'] = other['e']
             if other['w'] < bbox['w']:
                 bbox['w'] = other['w']
Example #27
0
 def geohashCoordinates(self, geohash, alt=0):
   """ Returns a string representing the coordinates of a geohash in a style
       suitable for using with Polygons, starting at the NE corner and moving
       in an anti-clockwise direction."""
   height = self.heightMultiplier * float(alt)
   bbox = geohasher.bbox(geohash)
   return """%s,%s,%d
           %s,%s,%d
           %s,%s,%d
           %s,%s,%d
           %s,%s,%d""" % ( \
         bbox['e'], bbox['n'], height, \
         bbox['w'], bbox['n'], height, \
         bbox['w'], bbox['s'], height, \
         bbox['e'], bbox['s'], height, \
         bbox['e'], bbox['n'], height )
Example #28
0
 def test_one(self):
     seq = '0123456789bcdefghjkmnpqrstuvwxyz'
     sws = [(-90.0, -180.0), (-90.0, -135.0), (-45.0, -180.0),
            (-45.0, -135.0), (-90.0, -90.0), (-90.0, -45.0), (-45.0, -90.0),
            (-45.0, -45.0), (0.0, -180.0), (0.0, -135.0), (45.0, -180.0),
            (45.0, -135.0), (0.0, -90.0), (0.0, -45.0), (45.0, -90.0),
            (45.0, -45.0), (-90.0, 0.0), (-90.0, 45.0), (-45.0, 0.0),
            (-45.0, 45.0), (-90.0, 90.0), (-90.0, 135.0), (-45.0, 90.0),
            (-45.0, 135.0), (0.0, 0.0), (0.0, 45.0), (45.0, 0.0),
            (45.0, 45.0), (0.0, 90.0), (0.0, 135.0), (45.0, 90.0),
            (45.0, 135.0)]
     for i in zip(seq, sws):
         x = geohash.bbox(i[0])
         self.assertEqual((x['s'], x['w']), i[1])
         self.assertEqual(x['n'] - x['s'], 45)
         self.assertEqual(x['e'] - x['w'], 45)
Example #29
0
 def geohashCoordinates(self, geohash, alt=0):
     """ Returns a string representing the coordinates of a geohash in a style
     suitable for using with Polygons, starting at the NE corner and moving
     in an anti-clockwise direction."""
     height = self.heightMultiplier * float(alt)
     bbox = geohasher.bbox(geohash)
     return """%s,%s,%d
         %s,%s,%d
         %s,%s,%d
         %s,%s,%d
         %s,%s,%d""" % ( \
           bbox['e'], bbox['n'], height, \
           bbox['w'], bbox['n'], height, \
           bbox['w'], bbox['s'], height, \
           bbox['e'], bbox['s'], height, \
           bbox['e'], bbox['n'], height )
Example #30
0
    def geohash_shape(self,
                      shape,
                      precision=12,
                      mode='center',
                      level=1,
                      prefix=''):
        geohashes = []

        for char in self._get_geohash_chars():
            hash = prefix + char

            p = bbox(hash)
            box_shape = box(p['w'], p['s'], p['e'], p['n'])

            if mode == 'inside':
                if shape.contains(box_shape):
                    geohashes.extend([hash])
                elif level < precision and box_shape.intersects(shape):
                    geohashes.extend(
                        self.geohash_shape(shape, precision, mode, level + 1,
                                           hash))

            elif mode == 'center':
                if shape.contains(box_shape):
                    geohashes.extend([hash])
                elif level < precision and box_shape.intersects(shape):
                    sub_shape = box_shape.intersection(shape)
                    geohashes.extend(
                        self.geohash_shape(sub_shape, precision, mode,
                                           level + 1, hash))
                elif level == precision:
                    (lat, lon) = decode(str(hash))

                    if shape.contains(Point(lon, lat)):
                        geohashes.append(hash)

            elif mode == 'intersect':
                if shape.contains(box_shape):
                    geohashes.extend([hash])
                elif level < precision and box_shape.intersects(shape):
                    geohashes.extend(
                        self.geohash_shape(shape, precision, mode, level + 1,
                                           hash))
                elif level == precision and box_shape.intersects(shape):
                    geohashes.append(hash)

        return geohashes
Example #31
0
    def debug(self, items,
              size=(800, 600), return_only=False, maptype="hybrid"):

            if maptype not in ('roadmap', 'satellite', 'hybrid', 'terrain'):
                raise TypeError('maptype not supported')

            polyenc = gpolyencode.GPolyEncoder()
            url = 'http://maps.googleapis.com/maps/api/staticmap?'
            url += 'size={}x{}&maptype={}&sensor=false&scale=2'.format(
                size[0], size[1], maptype)

            for (color_name, color_hex), item in zip(colornames, items):


                if isinstance(item, Area):
                    polygons = item.get_polygons()
                    for points in polygons:
                        p = polyenc.encode([(p[1], p[0]) for p in points])
                        polyline_encoded = p['points']
                        url += '&path=fillcolor:0x{}|weight:0|enc:{}'.format(
                            color_hex[1:], polyline_encoded)
                    print "{}: {}".format(item, color_name)

                elif isinstance(item, basestring):
                    gh = self.geohash(item)
                    if gh:
                        bbox = geohash.bbox(gh)
                        points = [(bbox['n'], bbox['w']),
                                  (bbox['n'], bbox['e']),
                                  (bbox['s'], bbox['e']),
                                  (bbox['s'], bbox['w']),
                                  (bbox['n'], bbox['w'])]
                        p = polyenc.encode([(p[1], p[0]) for p in points])
                        polyline_encoded = p['points']
                        url += '&path=color:0x{}|enc:{}'.format(
                            color_hex[1:], polyline_encoded)
                    print "{}: {}".format(item, color_name)

                else:
                    raise TypeError()

            webbrowser.open_new_tab(url)
Example #32
0
    def geohash_to_multipolygon(self, geohashes, simplify=False):
        polys = []

        for g in geohashes:
            box = bbox(g)

            polys.append(
                Polygon([
                    (box['w'], box['n']),
                    (box['e'], box['n']),
                    (box['e'], box['s']),
                    (box['w'], box['s']),
                ]))

        if simplify:
            polys = cascaded_union(polys)
        else:
            polys = MultiPolygon(polys)

        return mapping(polys)
Example #33
0
    def get_cells(self):
        """Get a mesh of geohash cells for all crimes in ElasticSearch at the
        chosen precision.
        """
        res = self.es.search(
            index=self.index,
            body={
                'aggregations': {
                    'grid': {
                        'geohash_grid': {
                            'field': 'geometry.coordinates',
                            'precision': self.precision
                        }
                    }
                }
            }
        )

        hashes = (bucket['key'] for bucket in res['aggregations']['grid']['buckets'])
        return (geohash.bbox(h) for h in hashes)
Example #34
0
 def test_one(self):
     seq = "0123456789bcdefghjkmnpqrstuvwxyz"
     sws = [
         (-90.0, -180.0),
         (-90.0, -135.0),
         (-45.0, -180.0),
         (-45.0, -135.0),
         (-90.0, -90.0),
         (-90.0, -45.0),
         (-45.0, -90.0),
         (-45.0, -45.0),
         (0.0, -180.0),
         (0.0, -135.0),
         (45.0, -180.0),
         (45.0, -135.0),
         (0.0, -90.0),
         (0.0, -45.0),
         (45.0, -90.0),
         (45.0, -45.0),
         (-90.0, 0.0),
         (-90.0, 45.0),
         (-45.0, 0.0),
         (-45.0, 45.0),
         (-90.0, 90.0),
         (-90.0, 135.0),
         (-45.0, 90.0),
         (-45.0, 135.0),
         (0.0, 0.0),
         (0.0, 45.0),
         (45.0, 0.0),
         (45.0, 45.0),
         (0.0, 90.0),
         (0.0, 135.0),
         (45.0, 90.0),
         (45.0, 135.0),
     ]
     for i in zip(seq, sws):
         x = geohash.bbox(i[0])
         self.assertEqual((x["s"], x["w"]), i[1])
         self.assertEqual(x["n"] - x["s"], 45)
         self.assertEqual(x["e"] - x["w"], 45)
	def test_one(self):
		seq = '0123456789bcdefghjkmnpqrstuvwxyz'
		sws = [
			(-90.0, -180.0),
			(-90.0, -135.0),
			(-45.0, -180.0),
			(-45.0, -135.0),
			(-90.0, -90.0),
			(-90.0, -45.0),
			(-45.0, -90.0),
			(-45.0, -45.0),
			(0.0, -180.0),
			(0.0, -135.0),
			(45.0, -180.0),
			(45.0, -135.0),
			(0.0, -90.0),
			(0.0, -45.0),
			(45.0, -90.0),
			(45.0, -45.0),
			(-90.0, 0.0),
			(-90.0, 45.0),
			(-45.0, 0.0),
			(-45.0, 45.0),
			(-90.0, 90.0),
			(-90.0, 135.0),
			(-45.0, 90.0),
			(-45.0, 135.0),
			(0.0, 0.0),
			(0.0, 45.0),
			(45.0, 0.0),
			(45.0, 45.0),
			(0.0, 90.0),
			(0.0, 135.0),
			(45.0, 90.0),
			(45.0, 135.0)
			]
		for i in zip(seq, sws):
			x = geohash.bbox(i[0])
			self.assertEqual((x['s'], x['w']), i[1])
			self.assertEqual(x['n']-x['s'], 45)
			self.assertEqual(x['e']-x['w'], 45)
Example #36
0
def prepare_sentiment_rects(date_start, date_end):
    rects = []
    for geo_sentiment in GeoSentiment.objects(date__gte=date_start,
                                              date__lt=date_end):
        bounds = geohash.bbox(geo_sentiment.geohash)
        sentiment = geo_sentiment.mean_sentiment
        rects.append({
            'fill_color':
            rgb2hex(sent2r(s=sentiment), sent2g(s=sentiment), 0),
            'stroke_weight':
            0,
            'fill_opacity':
            0.5,
            'bounds': {
                'north': bounds['n'],
                'west': bounds['w'],
                'south': bounds['s'],
                'east': bounds['e']
            }
        })
    return rects
Example #37
0
    def do_geohashtogeojson(self, geoh):
        """Build GeoJSON corresponding to geohash given as parameter.
        GEOHASHTOGEOJSON u09vej04 [NEIGHBORS 0|1|2]"""
        geoh, with_neighbors = self._match_option('NEIGHBORS', geoh)
        bbox = geohash.bbox(geoh)
        try:
            with_neighbors = int(with_neighbors)
        except TypeError:
            with_neighbors = 0

        def expand(bbox, geoh, depth):
            neighbors = geohash.neighbors(geoh)
            for neighbor in neighbors:
                other = geohash.bbox(neighbor)
                if with_neighbors > depth:
                    expand(bbox, neighbor, depth + 1)
                else:
                    if other['n'] > bbox['n']:
                        bbox['n'] = other['n']
                    if other['s'] < bbox['s']:
                        bbox['s'] = other['s']
                    if other['e'] > bbox['e']:
                        bbox['e'] = other['e']
                    if other['w'] < bbox['w']:
                        bbox['w'] = other['w']

        if with_neighbors > 0:
            expand(bbox, geoh, 0)

        geojson = {
            "type": "Polygon",
            "coordinates": [[
                [bbox['w'], bbox['n']],
                [bbox['e'], bbox['n']],
                [bbox['e'], bbox['s']],
                [bbox['w'], bbox['s']],
                [bbox['w'], bbox['n']]
            ]]
        }
        print(white(json.dumps(geojson)))
    def as_geo_json_bbox(self):
        """
        Returns a GeoJSON polygon dict representing bounding box that surrounds this bucket.

        :return: a GeoJSON polygon dict
        """
        bounding_box = geohash.bbox(self.key)
        return {
            "type":
            "Polygon",
            # note the reversal of the lat/lon and the double list wrap, it's cause this is GeoJSON
            "coordinates": [[
                # top left corner
                [bounding_box['w'], bounding_box['n']],
                # top right corner
                [bounding_box['e'], bounding_box['n']],
                # bottom right corner
                [bounding_box['e'], bounding_box['s']],
                # bottom left corner
                [bounding_box['w'], bounding_box['s']],
            ]],
        }
Example #39
0
 def innerGeohashKML(self, geohash, innerDir):
   bbox = geohasher.bbox(geohash)
   return """
 <NetworkLink>
   <name>%s</name>
   <Region>
     <LatLonAltBox>
       <north>%s</north>
       <south>%s</south>
       <east>%s</east>
       <west>%s</west>
     </LatLonAltBox>
     <Lod>
       <minLodPixels>32</minLodPixels>
       <maxLodPixels>768</maxLodPixels>
     </Lod>
   </Region>
   <Link>
     <href>./%s/index.kml</href>
     <viewRefreshMode>onRegion</viewRefreshMode>
   </Link>
  </NetworkLink>""" % (geohash, bbox['n'], bbox['s'], bbox['e'], bbox['w'], innerDir)
Example #40
0
   def innerGeohashKML(self, geohash, innerDir):
       bbox = geohasher.bbox(geohash)
       return """
 <NetworkLink>
   <name>%s</name>
   <Region>
     <LatLonAltBox>
       <north>%s</north>
       <south>%s</south>
       <east>%s</east>
       <west>%s</west>
     </LatLonAltBox>
     <Lod>
       <minLodPixels>32</minLodPixels>
       <maxLodPixels>768</maxLodPixels>
     </Lod>
   </Region>
   <Link>
     <href>./%s/index.kml</href>
     <viewRefreshMode>onRegion</viewRefreshMode>
   </Link>
  </NetworkLink>""" % (geohash, bbox['n'], bbox['s'], bbox['e'], bbox['w'],
                       innerDir)
Example #41
0
    def do_geohashtogeojson(self, geoh):
        """Build GeoJSON corresponding to geohash given as parameter.
        GEOHASHTOGEOJSON u09vej04 [NEIGHBORS 0|1|2]"""
        geoh, with_neighbors = self._match_option('NEIGHBORS', geoh)
        bbox = geohash.bbox(geoh)
        try:
            with_neighbors = int(with_neighbors)
        except TypeError:
            with_neighbors = 0

        def expand(bbox, geoh, depth):
            neighbors = geohash.neighbors(geoh)
            for neighbor in neighbors:
                other = geohash.bbox(neighbor)
                if with_neighbors > depth:
                    expand(bbox, neighbor, depth + 1)
                else:
                    if other['n'] > bbox['n']:
                        bbox['n'] = other['n']
                    if other['s'] < bbox['s']:
                        bbox['s'] = other['s']
                    if other['e'] > bbox['e']:
                        bbox['e'] = other['e']
                    if other['w'] < bbox['w']:
                        bbox['w'] = other['w']

        if with_neighbors > 0:
            expand(bbox, geoh, 0)

        geojson = {
            "type":
            "Polygon",
            "coordinates": [[[bbox['w'], bbox['n']], [bbox['e'], bbox['n']],
                             [bbox['e'], bbox['s']], [bbox['w'], bbox['s']],
                             [bbox['w'], bbox['n']]]]
        }
        print(white(json.dumps(geojson)))
Example #42
0
    def hashcodes(self, hashlength=10):
        west_set, east_set, hashcodes = set(), set(), set()

        row_hashcode = geohash.encode(latitude=self.__bbox["s"], longitude=self.__bbox["w"], precision=hashlength)
        row_bbox = geohash.bbox(row_hashcode)
        while row_bbox["s"] < self.__bbox["n"]:
            cell_hashcode = row_hashcode
            cell_bbox = row_bbox
            while is_west(cell_bbox["w"], self.__bbox["e"]):
                if self.__is_included(cell_bbox):
                    west_set.add(cell_hashcode)
                    break
                cell_hashcode = east(cell_hashcode)
                cell_bbox = geohash.bbox(cell_hashcode)
            row_hashcode = north(row_hashcode)
            row_bbox = geohash.bbox(row_hashcode)

        row_hashcode = geohash.encode(latitude=self.__bbox["s"], longitude=self.__bbox["e"], precision=hashlength)
        row_bbox = geohash.bbox(row_hashcode)
        while row_bbox["s"] < self.__bbox["n"]:
            cell_hashcode = row_hashcode
            cell_bbox = row_bbox
            while not is_west(cell_bbox["e"], self.__bbox["w"]):
                if self.__is_included(cell_bbox):
                    east_set.add(cell_hashcode)
                    break
                cell_hashcode = west(cell_hashcode)
                cell_bbox = geohash.bbox(cell_hashcode)
            row_hashcode = north(row_hashcode)
            row_bbox = geohash.bbox(row_hashcode)

        for hashcode in west_set:
            current = hashcode
            while current not in east_set:
                hashcodes.add(current)
                current = east(current)
        hashcodes.update(west_set)
        hashcodes.update(east_set)
        return hashcodes
Example #43
0
 def test_ezs42(self):
     x = geohash.bbox('ezs42')
     self.assertEqual(round(x['s'], 3), 42.583)
     self.assertEqual(round(x['n'], 3), 42.627)
import sys
import time
from math import cos, sqrt

x = 25
y = 25
pre_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24]


source = osr.SpatialReference()
source.ImportFromEPSG(4326)
target = osr.SpatialReference()
target.ImportFromEPSG(26912)
transform = osr.CoordinateTransformation(source, target)

def dist_km(bbox1):  #coords = (w,n) (w,s), (w, n) (e, n)
    R = 6371
    x1 = (lon2 - lon1) * cos( 0.5*(lat2+lat1) )
    y1 = lat2 - lat1
    d1 = R * sqrt( x*x + y*y )
    return d1

for i in pre_list:
    
    ghash = geohash.encode(x, y, precision=i)
    bboxname = "bbox_" + str(i)
    bboxname = geohash.bbox(ghash)
    print(bboxname)
    #dist = dist_km(bboxname)
    #print(dist)
Example #45
0
import geohash

print(geohash.bbox(geohash.encode(28.3613369, 75.5855657, precision=1)))
print(geohash.bbox(geohash.encode(28.3613369, 75.5855657, precision=2)))
print(geohash.bbox(geohash.encode(28.3613369, 75.5855657, precision=3)))
print(geohash.bbox(geohash.encode(28.3613369, 75.5855657, precision=4)))
print(geohash.bbox(geohash.encode(28.3613369, 75.5855657, precision=5)))
print(geohash.bbox(geohash.encode(28.3613369, 75.5855657, precision=6)))
print(geohash.bbox(geohash.encode(28.3613369, 75.5855657, precision=7)))
print(geohash.bbox(geohash.encode(28.3613369, 75.5855657, precision=8)))
            real_area = area(create_geojson(
                mapping(polygon)["coordinates"][0])) / 1000000

            geohashes_polygon = polygon_to_geohashes(polygon, precision, False)
            polygon = geohashes_to_polygon(geohashes_polygon)

            perc_area = 100 * (
                area(create_geojson(mapping(polygon)["coordinates"][0])) /
                1000000) / real_area
            p_area.append(perc_area)
            geohash_num.append(len(compress(list(geohashes_polygon))))

            if points:
                ps = []
                for hash in compress(list(geohashes_polygon)):
                    bbox = geohash.bbox(hash)
                    lat1 = bbox['s']
                    lat2 = bbox['n']
                    lon1 = bbox['w']
                    lon2 = bbox['e']
                    ps.append(lat1)
                    ps.append(lon1)
                    ps.append(lat2)
                    ps.append(lon1)
                    ps.append(lat2)
                    ps.append(lon2)
                    ps.append(lat1)
                    ps.append(lon2)
                f = open("fences_points.txt", "a")
                f.write(str(ps))
                f.close()
Example #47
0
 def test_empty(self):
     self.assertEqual(geohash.bbox(""), {"s": -90.0, "n": 90.0, "w": -180.0, "e": 180.0})
Example #48
0
    def get_polygons(self):

        # search for edges
        edge_lines = []
        edge_detection = [
            ('U', (('n', 'w'), ('n', 'e'))),
            ('D', (('s', 'w'), ('s', 'e'))),
            ('L', (('n', 'w'), ('s', 'w'))),
            ('R', (('n', 'e'), ('s', 'e'))),
        ]

        for gh in self.geohashes:
            neighbors = self._get_named_neighbors(gh)

            for empty, ((x1_name, y1_name),
                        (x2_name, y2_name)) in edge_detection:
                if neighbors[empty] not in self.geohashes:
                    b = geohash.bbox(gh)
                    edge_lines.append(((b[x1_name], b[y1_name]),
                                       (b[x2_name], b[y2_name])))

        # merge all the lines to one path
        lines = list(edge_lines)
        while True:
            break_ = False
            found = False
            for (from_point1, to_point1) in lines:
                if break_:
                    break
                for (from_point2, to_point2) in lines:
                    if break_:
                        break
                    if (from_point1, to_point1) == (from_point2, to_point2):
                        continue
                    if to_point1 == from_point2 and (
                            from_point1[0] == to_point2[0]
                            or from_point1[1] == to_point2[1]):
                        new = (from_point1, to_point2)
                        remove1 = (from_point1, to_point1)
                        remove2 = (from_point2, to_point2)
                        break_ = True
                        found = True
            if not found:
                break
            lines.remove(remove1)
            lines.remove(remove2)
            lines.append(new)

        def get_next_line(all_lines, p):
            for (p1, p2) in all_lines:
                if p == p1:
                    all_lines.remove((p1, p2))
                    return p2
                if p == p2:
                    all_lines.remove((p1, p2))
                    return p1
            raise ValueError('no next line found')

        polygons = []
        while True:
            polygon_points = []
            try:
                # choose any point to begin with
                next_point = lines[0][0]
            except IndexError:
                break

            # aggregate all polygons
            while True:

                # find next point
                found = False
                for (p1, p2) in lines:
                    if next_point == p1:
                        lines.remove((p1, p2))
                        next_point = p2
                        found = True
                        break
                    if next_point == p2:
                        lines.remove((p1, p2))
                        next_point = p1
                        found = True
                        break
                if not found:
                    break

                polygon_points.append(next_point)

            # "close the circle"
            polygon_points.append(polygon_points[0])

            polygons.append(polygon_points)

        return polygons
Example #49
0
    def debug(self, *items, **kw):
        from string import ascii_uppercase
        import webbrowser
        import gpolyencode

        size = kw.get('size', (800, 600))
        return_only = kw.get('return_only', False)
        maptype = kw.get('maptype', 'hybrid')

        assert maptype in ('roadmap', 'satellite', 'hybrid', 'terrain')

        ascii_labels = list(ascii_uppercase)
        number_labels = list('123456789')
        polyenc = gpolyencode.GPolyEncoder()
        draw_geohashes = []

        for item in items:
            if isinstance(item, Area):
                use_label = True
                for gh in sorted(item.geohashes, reverse=True):
                    draw_geohashes.append(('rect', gh, use_label, item))
                    use_label = False
            else:
                gh = self.geohash(item)
                draw_geohashes.append(('fill', gh, True, item))

        used_labels = {}
        label_description = {}
        url = 'http://maps.googleapis.com/maps/api/staticmap?'
        url += 'size={}x{}&maptype={}&sensor=false&scale=2'.format(size[0], size[1], maptype)
        for cmd, gh, use_label, obj, in draw_geohashes:
                if use_label:
                    # get the corresponding label
                    label = used_labels.get(gh)
                    if not label:
                        try:
                            label = (ascii_labels.pop(0) if cmd == 'fill'
                                    else number_labels.pop(0))
                        except IndexError:
                            # * will be showed as a cirlce in google maps
                            label = '*'
                        used_labels[gh] = label

                if cmd == 'fill':

                    latlon = geohash.decode(gh)
                    url += '&markers=label:{label}|{lat},{lon}'.format(
                            lat=round(latlon[0], 5), lon=round(latlon[1], 5), label=label)
                    url += '&path=fillcolor:red|weight:0|'

                elif cmd == 'rect':
                    if use_label:
                        bbox = geohash.bbox(gh)
                        url += '&markers=label:{label}|color:blue|{lat},{lon}'.format(
                                lat=round(bbox['n'], 5), lon=round(bbox['e'], 5), label=label)
                    url += '&path='
                else:
                    assert False

                bbox = geohash.bbox(gh)
                points = [(bbox['n'], bbox['w']),
                        (bbox['n'], bbox['e']),
                        (bbox['s'], bbox['e']),
                        (bbox['s'], bbox['w']),
                        (bbox['n'], bbox['w'])]
                p = polyenc.encode([(p[1], p[0]) for p in points])
                polyline_encoded = p['points']
                url += 'enc:{}'.format(polyline_encoded)

                if use_label:
                    label_description.setdefault(label, [])
                    label_description[label].append(obj)

        if return_only:
            return label_description, url
        else:
            # maybe the browser autocodes charachters so actually more are used
            print 'image: {} ({} chars, 2048 allowed)'.format(url, len(url)) 
            print
            print 'image legend'
            print '------------'
            for label, objs in label_description.items():
                print ' {} | {}'.format(label, ', '.join(str(i) for i in objs))
            print '------------'
            webbrowser.open_new_tab(url)
Example #50
0
 def test_ezs42(self):
     x = geohash.bbox("ezs42")
     self.assertEqual(round(x["s"], 3), 42.583)
     self.assertEqual(round(x["n"], 3), 42.627)
Example #51
0
 def bboxes(self):
     return tuple(geohash.bbox(gh) for gh in self.geohashes)
Example #52
0
 def bbox(self, pin_id):
     # is this method a good idea?
     """Return the location of a pin as a bbox of the underlying geohash."""
     gh = self.geohash(pin_id)
     return geohash.bbox(gh)
Example #53
0
 def bbox_scan(self, buffer=50):
     """Analog to :py:meth:`geohash_scan` return a bbox instead of the geohash."""
     return ((pin, geohash.bbox(gh))
             for pin, gh in self.geohash_scan(buffer))
Example #54
0
 def __init__(self, region):
     super(OSMGeoDoc, self).__init__(C.GEODOC, region)
     # Fill in default values for 'standard' fields.
     self.__setitem__(C.NODES, set())
     self.__setitem__(C.BBOX, geohash.bbox(region))
Example #55
0
 def bbox_scan(self, buffer=50):
     return ((pin, geohash.bbox(gh))
             for pin, gh in self.geohash_scan(buffer))
def decode_extent(extent):
    decoded = geohash.bbox(extent)
    return [decoded['w'], decoded['e'], decoded['s'], decoded['n']]
Example #57
0
    def get(self):
        motordb = self.settings['motordb']
        print 'processing request'
        ### Process Bounds and Center arguments

        view_bounds_str = self.get_argument("bounds")
        view_center_str = self.get_argument("center")
        view_zoom_str = self.get_argument("zoom")
        view_zoom = int(view_zoom_str)

        if not view_bounds_str or not view_center_str:
            self.write([])
            self.finish()
            return

        view_bounds_south, view_bounds_west, view_bounds_north, view_bounds_east = [float(x) for x in view_bounds_str.split(',')]

        view_center_lat, view_center_long = [float(x) for x in view_center_str.split(',')]

        view_bounds_width = abs(view_bounds_north - view_bounds_south)
        view_bounds_height = abs(view_bounds_east - view_bounds_west)

        #Do not use spacial reference system so that calculations are faster.. not needed 
        view_bounds_ring = osgeo.ogr.Geometry(osgeo.ogr.wkbLinearRing)
        view_bounds_ring.TransformTo(WGS_84)
        view_bounds_ring.AddPoint(view_bounds_west, view_bounds_north)
        view_bounds_ring.AddPoint(view_bounds_east, view_bounds_north)
        view_bounds_ring.AddPoint(view_bounds_east, view_bounds_south)
        view_bounds_ring.AddPoint(view_bounds_west, view_bounds_south)
        view_bounds_ring.AddPoint(view_bounds_west, view_bounds_north)

        view_bounds_geom = osgeo.ogr.Geometry(osgeo.ogr.wkbPolygon)
        view_bounds_geom.TransformTo(WGS_84)
        view_bounds_geom.AddGeometry(view_bounds_ring)
        view_bounds_area = view_bounds_geom.Area()
        
        view_center_hash = geohash.encode(view_center_lat, view_center_long, precision=32)

        ###print "VIEW %.64f" % view_bounds_area

        possible_hashes = set(list('0123456789bcdefghjkmnpqrstuvwxyz'))

        if view_zoom == 5: end_precision = 0
        if view_zoom == 6: end_precision = 0
        if view_zoom == 7: end_precision = 1
        if view_zoom == 8: end_precision = 2
        if view_zoom == 9: end_precision = 2
        if view_zoom == 10: end_precision = 3
        if view_zoom == 11: end_precision = 4
        if view_zoom == 12: end_precision = 5
        if view_zoom == 13: end_precision = 6
        if view_zoom == 14: end_precision = 6
        if view_zoom == 15: end_precision = 7

        end_precision = (view_zoom / 3) #perfect
        if end_precision > PRECISION:
            end_precision = PRECISION
        if end_precision < 0:
            end_precision = 0

        if view_zoom < 8:
            end_precision = 0
        ##print end_precision, '!!!'

        for precision in range(1,end_precision+1):
            new_possible_hashes = set([])

            for possible_hash in possible_hashes:
                possible_hash_bbox = geohash.bbox(possible_hash)
                #Do not use spacial reference system
                possible_hash_ring = osgeo.ogr.Geometry(osgeo.ogr.wkbLinearRing)
                possible_hash_ring.TransformTo(WGS_84)
                possible_hash_ring.AddPoint(possible_hash_bbox['w'], possible_hash_bbox['n'])
                possible_hash_ring.AddPoint(possible_hash_bbox['e'], possible_hash_bbox['n'])
                possible_hash_ring.AddPoint(possible_hash_bbox['e'], possible_hash_bbox['s'])
                possible_hash_ring.AddPoint(possible_hash_bbox['w'], possible_hash_bbox['s'])
                possible_hash_ring.AddPoint(possible_hash_bbox['w'], possible_hash_bbox['n'])
            
                possible_hash_geom = osgeo.ogr.Geometry(osgeo.ogr.wkbPolygon)
                possible_hash_geom.TransformTo(WGS_84)
            
                possible_hash_geom.AddGeometry(possible_hash_ring)

                possible_hash_geom_intersection = view_bounds_geom.Intersection(possible_hash_geom)
                possible_hash_geom_intersection.TransformTo(WGS_84)
                possible_hash_area = possible_hash_geom_intersection.Area()

                if possible_hash_area or view_center_hash.startswith(possible_hash):
                    ##print "!!!!", possible_hash, view_center_hash
                    for hash_char in '0123456789bcdefghjkmnpqrstuvwxyz':
                        new_possible_hashes.add(possible_hash + hash_char)

            possible_hashes = new_possible_hashes


        new_possible_hashes = set([])
        new_possible_grandparent_hashes = set([])

        for possible_hash in possible_hashes:
            possible_hash_bbox = geohash.bbox(possible_hash)
            #Do not use spacial reference system
            possible_hash_ring = osgeo.ogr.Geometry(osgeo.ogr.wkbLinearRing)
            possible_hash_ring.TransformTo(WGS_84)
            possible_hash_ring.AddPoint(possible_hash_bbox['w'], possible_hash_bbox['n'])
            possible_hash_ring.AddPoint(possible_hash_bbox['e'], possible_hash_bbox['n'])
            possible_hash_ring.AddPoint(possible_hash_bbox['e'], possible_hash_bbox['s'])
            possible_hash_ring.AddPoint(possible_hash_bbox['w'], possible_hash_bbox['s'])
            possible_hash_ring.AddPoint(possible_hash_bbox['w'], possible_hash_bbox['n'])
        
            possible_hash_geom = osgeo.ogr.Geometry(osgeo.ogr.wkbPolygon)
            possible_hash_geom.TransformTo(WGS_84)
        
            possible_hash_geom.AddGeometry(possible_hash_ring)

            possible_hash_geom_intersection = view_bounds_geom.Intersection(possible_hash_geom)
            possible_hash_geom_intersection.TransformTo(WGS_84)
            possible_hash_area = possible_hash_geom_intersection.Area()

            if possible_hash_area or view_center_hash.startswith(possible_hash):
                new_possible_hashes.update(geohash.expand(possible_hash))
                new_possible_grandparent_hashes.add(possible_hash[0:-1])

        possible_hashes = new_possible_hashes


        centroids = []

        for hash in sorted(list(possible_hashes)):
            _lat, _long = geohash.decode(hash)
            centroids.append({
                'hash': hash,
                'arg': True,
                'lat': _lat,
                'long': _long,
            })

        lots = []
        regions = []
        region_set = set([])

        query = {'parent': {'$in': list(possible_hashes)}}
        cursor = motordb.lots.find(query)
        print query

        self.update_region_cache()

        while (yield cursor.fetch_next):
            lot = cursor.next_object()
            lot['lot'] = True
            lot['bbox'] = geohash.bbox(lot['hash'])
            outline = osgeo.ogr.Geometry(wkb=str(lot['geom']['outline']))
            outline.TransformTo(WGS_84)
            lot['geom']['outline'] = json.loads(osgeo.ogr.ForceToPolygon(outline).ExportToJson())
            #geom = osgeo.ogr.ForceToPolygon(osgeo.ogr.Geometry(json.dumps(lot['geom']['outline'])).ConvexHull())
            geom = outline.ConvexHull()

            if view_bounds_geom.Contains(geom) or view_bounds_geom.Intersects(geom) or view_zoom == 5:
                region_set.add(lot['region']['_id'])
                if view_zoom != 5:
                    lots.append(lot)

        for region_oid in region_set:
            region = copy.deepcopy(self.settings['cache']['region']['map']['_id'][region_oid])
            region['region'] = True
            outline = osgeo.ogr.Geometry(wkb=str(region['geom']['outline']))
            outline.TransformTo(WGS_84)
            region['geom']['outline'] = json.loads(osgeo.ogr.ForceToPolygon(outline).ExportToJson())
            regions.append(region)
        

        self.write(bson.json_util.dumps(sorted(regions, key=lambda x: x['order']) + lots))
        self.finish()
        return
Example #58
0
 def bbox(self, pin_id):
     # is this method a good idea?
     gh = self.geohash(pin_id)
     return geohash.bbox(gh)