コード例 #1
0
ファイル: tests.py プロジェクト: pombredanne/lizard-map
 def test_float_to_string8(self):
     """Let's input a string."""
     st = float_to_string('1000')
     self.assertEquals(st, '1000.00')
コード例 #2
0
ファイル: layers.py プロジェクト: pombredanne/lizard-shape
    def search(self, x, y, radius=None):
        """
        Search area, line or point.

        Make sure that value_field, search_property_id,
        search_property_name are valid columns in your shapefile.

        x,y are google coordinates

        Note: due to mapnik #503 (http://trac.mapnik.org/ticket/503)
        the search does not work for lines and points. So the
        implementation was done with shapely.

        """
        logger.debug("Searching coordinates (%0.2f, %0.2f) radius %r..." %
                     (x, y, radius))

        if not self.search_property_name:
            # We don't have anything to return, so don't search.
            return []

        if radius is not None:
            # Manually make radius smaller

            # RG, way later: it used to say 0.2 on the line below, but
            # there were complaints saying that this was too
            # small. From some manual testing, 1 (the default) is too
            # large. I'll put 0.8. Obviously a very well argued value.
            logger.debug("Adjusting radius...")
            radius = radius * 0.8

        transformed_x, transformed_y = transform(
            google_projection, Proj(detect_prj(self.prj)), x, y)
        query_point = Point(transformed_x, transformed_y)

        ds = osgeo.ogr.Open(self.layer_filename)
        try:
            lyr = ds.GetLayer()
        except AttributeError:
            # #3033
            # This one occurs when the file does not exist.
            logger.error("The search function crashed. Probably due "
                         "to a missing shapefile.")
            return []

        if radius is not None:

            # The radius needs to be transformed as well, but how?
            # A transformed square will no longer be a square!
            # This needs further attention...

            transformed_x_radius, transformed_y_radius = transform(
                google_projection, Proj(detect_prj(self.prj)),
                x + radius, y + radius)

            radius = max(abs(transformed_x - transformed_x_radius),
                         abs(transformed_y - transformed_y_radius))

            lyr.SetSpatialFilterRect(
                transformed_x - radius,
                transformed_y - radius,
                transformed_x + radius,
                transformed_y + radius)

        lyr.ResetReading()
        feat = lyr.GetNextFeature()

        results = []

        while feat is not None:
            geom = feat.GetGeometryRef()
            if geom:
                item = loads(geom.ExportToWkt())
                distance = query_point.distance(item)
                feat_items = feat.items()

                if not radius or (radius is not None and distance < radius):
                    # Add stripped keys, because column names can contain
                    # spaces after the 'real' name.
                    for key in feat_items.keys():
                        feat_items[key.strip()] = feat_items[key]

                    # Found an item.
                    if self.search_property_name not in feat_items:
                        # This means that the search_property_name is not a
                        # valid field in the shapefile dbf.
                        logger.error(
                            ('Search: The field "%s" cannot be found in '
                             'shapefile "%s". Available fields: %r'
                             'Check your settings in '
                             'lizard_shape.models.Shape.') %
                            (self.search_property_name, self.layer_name,
                             feat_items.keys()))
                        break  # You don't have to search other rows.
                    name = str(feat_items[self.search_property_name])

                    if self.display_fields:
                        if self.display_fields[0]['field'] not in feat_items:
                            # This means that the value_field is not a
                            # valid field in the shapefile dbf.
                            logger.error(
                                ('Search: The field "%s" cannot be found in '
                                 'shapefile "%s". Check display_fields. '
                                 'Options are: %s') %
                                (self.display_fields[0]['field'],
                                 self.layer_name,
                                 feat_items.keys()))
                            break  # You don't have to search other rows.
                        name += ' - %s=%s' % (
                            self.display_fields[0]['name'],
                            str(float_to_string(feat_items[
                                        self.display_fields[0]['field']])))

                    result = {'distance': distance,
                              'name': name,
                              'workspace_item': self.workspace_item}
                    try:
                        result.update(
                            {'google_coords':
                                 transform(Proj(detect_prj(self.prj)),
                                           google_projection,
                                           *item.coords[0])})
                    except NotImplementedError:
                        logger.warning(
                            "Got a NotImplementedError while transforming "
                            "coordinates from %s to google with pyproj "
                            "for shapefile %s. Not returning google "
                            "coordinates.",
                            self.prj, self.shape)

                    if (self.search_property_id and
                        self.search_property_id in feat_items):
                        result.update(
                            {'identifier':
                                 {'id': feat_items[self.search_property_id]}})
                    else:
                        logger.error("Problem with search_property_id: %s. "
                                     "List of available properties: %r" %
                                     (self.search_property_id,
                                      feat_items.keys()))
                    results.append(result)
            feat = lyr.GetNextFeature()
        results = sorted(results, key=lambda a: a['distance'])
        if len(results) > MAX_SEARCH_RESULTS:
            logger.info('A lot of results found (%d), just taking top %s.',
                        len(results), MAX_SEARCH_RESULTS)
        return results[:MAX_SEARCH_RESULTS]
コード例 #3
0
ファイル: tests.py プロジェクト: pombredanne/lizard-map
 def test_float_to_string7(self):
     """Let's input a string."""
     self.assertEquals(float_to_string('string'), 'string')
コード例 #4
0
ファイル: tests.py プロジェクト: pombredanne/lizard-map
 def test_float_to_string6(self):
     """Let's input some nice floats."""
     st = float_to_string(999999999.99)
     self.assertTrue(len(st) <= 10)
     self.assertEquals(st[:4], '1000')
コード例 #5
0
ファイル: tests.py プロジェクト: pombredanne/lizard-map
 def test_float_to_string5(self):
     """Let's input some nice floats."""
     st = float_to_string(123456789012345)
     self.assertTrue(len(st) <= 10)
     self.assertEquals(st[:4], '1.23')
     self.assertTrue('e' in st)
コード例 #6
0
ファイル: tests.py プロジェクト: pombredanne/lizard-map
 def test_float_to_string2(self):
     """Let's input some nice floats."""
     st = float_to_string(12345.678)
     self.assertTrue(len(st) <= 10)
     self.assertEquals(st[:4], '1234')
コード例 #7
0
ファイル: workspaces.py プロジェクト: lizardsystem/lizard-map
def float_or_exp(value):
    """Show number with 2 decimals or with an exponent if too small."""
    return float_to_string(value)