django.contrib.gis.geos.LineString

Here are the examples of the python api django.contrib.gis.geos.LineString taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

133 Examples 7

Example 1

Project: Geotrek-admin Source File: test_models.py
    def test_is_publishable(self):
        t = TrekFactory.create()
        t.geom = LineString((0, 0), (1, 1))
        self.assertTrue(t.has_geom_valid())

        t.description_teaser = ''
        self.assertFalse(t.is_complete())
        self.assertFalse(t.is_publishable())
        t.description_teaser = 'ba'
        t.departure = 'zin'
        t.arrival = 'ga'
        self.assertTrue(t.is_complete())
        self.assertTrue(t.is_publishable())

        t.geom = MultiLineString([LineString((0, 0), (1, 1)), LineString((2, 2), (3, 3))])
        self.assertFalse(t.has_geom_valid())
        self.assertFalse(t.is_publishable())

Example 2

Project: django-geojson Source File: tests.py
    def test_geometry_property(self):
        class Basket(models.Model):

            @property
            def geom(self):
                return GeometryCollection(LineString((3, 4, 5), (6, 7, 8)), Point(1, 2, 3), srid=4326)

        serializer = Serializer()
        features = json.loads(
            serializer.serialize([Basket()], crs=False, force2d=True))
        expected_content = {"type": "FeatureCollection", "features": [{"geometry": {"type": "GeometryCollection", "geometries": [{"type": "LineString", "coordinates": [[3.0, 4.0], [6.0, 7.0]]}, {"type": "Point", "coordinates": [1.0, 2.0]}]}, "type": "Feature", "properties": {"id": None}}]}
        self.assertEqual(features, expected_content)

Example 3

Project: Geotrek-admin Source File: test_fields.py
    def test_geom_is_snapped_if_path_pk_is_provided(self):
        path = PathFactory.create()
        value = '{"geom": "%s", "snap": [null, %s]}' % (self.wktgeom, path.pk)
        self.assertTrue(self.f.clean(value).equals_exact(
            LineString((100000, 100000), (700000, 6600000),
                       srid=settings.SRID), 0.1))

Example 4

Project: Geotrek-admin Source File: test_topology.py
    def test_deserialize_serialize(self):
        path = PathFactory.create(geom=LineString((1, 1), (2, 2), (2, 0)))
        before = TopologyFactory.create(offset=1, no_path=True)
        before.add_path(path, start=0.5, end=0.5)

        # Deserialize its serialized version !
        after = Topology.deserialize(before.serialize())

        self.assertEqual(len(before.paths.all()), len(after.paths.all()))
        start_before = before.aggregations.all()[0].start_position
        end_before = before.aggregations.all()[0].end_position
        start_after = after.aggregations.all()[0].start_position
        end_after = after.aggregations.all()[0].end_position
        self.assertTrue(almostequal(start_before, start_after), '%s != %s' % (start_before, start_after))
        self.assertTrue(almostequal(end_before, end_after), '%s != %s' % (end_before, end_after))

Example 5

Project: Geotrek-admin Source File: test_models.py
    def test_snapping_is_idempotent(self):
        PathFactory.create(geom=LineString((0, 0), (9.8, 0), (9.9, 0), (10, 0)))
        path_snapped = PathFactory.create(geom=LineString((10, 0.1), (10, 10)))
        old_geom = path_snapped.geom
        path_snapped.geom = old_geom
        path_snapped.save()
        self.assertEqual(path_snapped.geom.coords, old_geom.coords)

Example 6

Project: Geotrek-admin Source File: test_elevation.py
    def setUp(self):
        # Create a simple fake DEM
        conn = connections[DEFAULT_DB_ALIAS]
        cur = conn.cursor()
        cur.execute('CREATE TABLE mnt (rid serial primary key, rast raster)')
        cur.execute('INSERT INTO mnt (rast) VALUES (ST_MakeEmptyRaster(100, 125, 0, 125, 25, -25, 0, 0, %s))', [settings.SRID])
        cur.execute('UPDATE mnt SET rast = ST_AddBand(rast, \'16BSI\')')
        demvalues = [[0, 0, 3, 5], [2, 2, 10, 15], [5, 15, 20, 25], [20, 25, 30, 35], [30, 35, 40, 45]]
        for y in range(0, 5):
            for x in range(0, 4):
                cur.execute('UPDATE mnt SET rast = ST_SetValue(rast, %s, %s, %s::float)', [x + 1, y + 1, demvalues[y][x]])
        self.path = Path.objects.create(geom=LineString((1, 101), (81, 101), (81, 99)))

Example 7

Project: Geotrek-admin Source File: test_models.py
    def test_save_with_same_geom(self):
        geom = LineString(((700000, 6600000), (700100, 6600100)), srid=2154)
        self.trek.geom = geom
        self.trek.save()
        retrieve_trek = Trek.objects.get(pk=self.trek.pk)
        self.assertTrue(retrieve_trek.geom.equals_exact(geom, tolerance=0.00001))

Example 8

Project: django-multi-gtfs Source File: shape.py
Function: update_geometry
    def update_geometry(self, update_parent=True):
        """Update the geometry from the related ShapePoints"""
        original = self.geometry
        points = self.points.order_by(
            'sequence').values_list('point', flat=True)
        if len(points) > 1:
            self.geometry = LineString([pt.coords for pt in points])
            if self.geometry != original:
                self.save()
                if update_parent:
                    for trip in self.trip_set.all():
                        trip.update_geometry()

Example 9

Project: linz2osm Source File: test_line_reverse.py
Function: test_simple
    def test_simple(self):
        l = geos.LineString(((0,0), (1,1)))
        
        p = ReverseLine()
        l2 = p.handle(l)
        
        self.assertEqual(((1,1), (0,0)), l2.tuple)

Example 10

Project: django-nonrel Source File: tests.py
    @no_mysql
    @no_spatialite
    def test28_reverse(self):
        "Testing GeoQuerySet.reverse_geom()."
        coords = [ (-95.363151, 29.763374), (-95.448601, 29.713803) ]
        Track.objects.create(name='Foo', line=LineString(coords))
        t = Track.objects.reverse_geom().get(name='Foo')
        coords.reverse()
        self.assertEqual(tuple(coords), t.reverse_geom.coords)
        if oracle:
            self.assertRaises(TypeError, State.objects.reverse_geom)

Example 11

Project: Geotrek-admin Source File: test_topology.py
    def test_trek_all_reverse(self):
        """

        +----<===+=======+====|----->

        """
        p1 = PathFactory.create(geom=LineString((0, 0), (10, 0)))
        p2 = PathFactory.create(geom=LineString((10, 0), (20, 0)))
        p3 = PathFactory.create(geom=LineString((20, 0), (30, 0)))

        topo = TopologyFactory.create(no_path=True)
        topo.add_path(p3, start=0.2, end=0)
        topo.add_path(p2, start=1, end=0)
        topo.add_path(p1, start=1, end=0.9)
        topo.save()
        self.assertEqual(topo.geom, LineString((22.0, 0.0), (20.0, 0.0), (10.0, 0.0), (9.0, 0.0)))

Example 12

Project: Geotrek-admin Source File: test_topology.py
    def test_point_at_end_of_path_not_moving_after_mutate(self):
        PathFactory.create(geom=LineString((400, 400), (410, 400),
                                           srid=settings.SRID))
        self.assertEqual(1, len(Path.objects.all()))

        father = Topology.deserialize({'lat': -1, 'lng': -1})

        poi = Point(500, 600, srid=settings.SRID)
        poi.transform(settings.API_SRID)
        son = Topology.deserialize({'lat': poi.y, 'lng': poi.x})
        father.mutate(son)
        self.assertTrue(almostequal(father.geom.x, 500))
        self.assertTrue(almostequal(father.geom.y, 600))

Example 13

Project: Geotrek-admin Source File: test_elevation.py
    def test_elevation_svg_output(self):
        geom = LineString((1.5, 2.5, 8), (2.5, 2.5, 10),
                          srid=settings.SRID)
        profile = AltimetryHelper.elevation_profile(geom)
        svg = AltimetryHelper.profile_svg(profile)
        self.assertIn('Generated with pygal', svg)
        self.assertIn(settings.ALTIMETRIC_PROFILE_BACKGROUND, svg)
        self.assertIn(settings.ALTIMETRIC_PROFILE_COLOR, svg)

Example 14

Project: Geotrek-admin Source File: test_triggers.py
    def test_smart_makeline_unordered(self):
        merged = self.smart_makeline([
            LineString((2, 0), (4, 0)),
            LineString((4, 0), (8, 0)),
            LineString((8, 0), (9, 0)),
            LineString((9, 0), (10, 0)),
            LineString((9, 0), (8, 0)),
            LineString((10, 0), (9, 0)),
            LineString((8, 0), (4, 0)),
            LineString((4, 0), (2, 0)),
        ])
        self.assertEqual(merged,
                         LineString((2, 0), (4, 0), (8, 0), (9, 0), (10, 0), (9, 0), (8, 0), (4, 0), (2, 0)),
                         merged.coords)

Example 15

Project: splunk-webframework Source File: test_geos.py
    def test_length(self):
        "Testing the length property."
        # Points have 0 length.
        pnt = Point(0, 0)
        self.assertEqual(0.0, pnt.length)

        # Should be ~ sqrt(2)
        ls = LineString((0, 0), (1, 1))
        self.assertAlmostEqual(1.41421356237, ls.length, 11)

        # Should be circuemfrence of Polygon
        poly = Polygon(LinearRing((0, 0), (0, 1), (1, 1), (1, 0), (0, 0)))
        self.assertEqual(4.0, poly.length)

        # Should be sum of each element's length in collection.
        mpoly = MultiPolygon(poly.clone(), poly)
        self.assertEqual(8.0, mpoly.length)

Example 16

Project: Geotrek-admin Source File: test_models.py
    def test_deleted_services(self):
        p1 = PathFactory.create(geom=LineString((0, 0), (4, 4)))
        trek = TrekFactory.create(no_path=True)
        trek.add_path(p1)
        service = ServiceFactory.create(no_path=True)
        service.type.practices.add(trek.practice)
        service.add_path(p1, start=0.6, end=0.6)
        self.assertItemsEqual(trek.services, [service])
        service.delete()
        self.assertItemsEqual(trek.services, [])

Example 17

Project: Geotrek-admin Source File: models.py
Function: reverse
    def reverse(self):
        """
        Reverse the geometry.
        We keep track of this, since we will have to work on topologies at save()
        """
        reversed_coord = self.geom.coords[-1::-1]
        self.geom = LineString(reversed_coord)
        self.is_reversed = True
        return self

Example 18

Project: Geotrek-admin Source File: test_models.py
    def test_path_touching_land_layer(self):
        p1 = PathFactory.create(geom=LineString((3, 3), (4, 4), srid=settings.SRID))
        City.objects.create(code='005177', name='Trifouillis-les-oies',
                            geom=MultiPolygon(Polygon(((0, 0), (2, 0), (2, 2), (0, 2), (0, 0)),
                                                      srid=settings.SRID)))
        p1.geom = LineString((2, 2), (4, 4), srid=settings.SRID)
        p1.save()

Example 19

Project: PyClassLessons Source File: tests.py
Function: test_reverse_geom
    @no_mysql
    @no_spatialite
    def test_reverse_geom(self):
        "Testing GeoQuerySet.reverse_geom()."
        coords = [(-95.363151, 29.763374), (-95.448601, 29.713803)]
        Track.objects.create(name='Foo', line=LineString(coords))
        t = Track.objects.reverse_geom().get(name='Foo')
        coords.reverse()
        self.assertEqual(tuple(coords), t.reverse_geom.coords)
        if oracle:
            self.assertRaises(TypeError, State.objects.reverse_geom)

Example 20

Project: linz2osm Source File: test_centroid.py
Function: test_line
    def test_line(self):
        g = geos.LineString((0,0), (0,10), (10,10))

        p = PointOnSurface()
        g2 = p.handle(g)

        self.assertEqual(g2.geom_type, 'Point')
        self.assert_(g2.tuple in g.tuple)

Example 21

Project: Geotrek-admin Source File: test_graph.py
    def test_json_graph_headers(self):
        """
        Last modified depends on
        """
        PathFactory(geom=LineString((0, 0), (1, 1)))
        response = self.client.get(self.url)
        last_modified = response['Last-Modified']
        expires = response['Expires']
        self.assertNotEqual(expires, None)
        self.assertEqual(expires, last_modified)

Example 22

Project: Geotrek-admin Source File: test_models.py
    def test_overlap_geometry(self):
        PathFactory.create(geom=LineString((0, 0), (60, 0)))
        p = PathFactory.create(geom=LineString((40, 0), (50, 0)))
        self.assertTrue(p.is_overlap())
        # Overlaping twice
        p = PathFactory.create(geom=LineString((20, 1), (20, 0), (25, 0), (25, 1),
                                               (30, 1), (30, 0), (35, 0), (35, 1)))
        self.assertTrue(p.is_overlap())

        # But crossing is ok
        p = PathFactory.create(geom=LineString((6, 1), (6, 3)))
        self.assertFalse(p.is_overlap())
        # Touching is ok too
        p = PathFactory.create(geom=LineString((5, 1), (5, 0)))
        self.assertFalse(p.is_overlap())
        # Touching twice is ok too
        p = PathFactory.create(geom=LineString((2.5, 0), (3, 1), (3.5, 0)))
        self.assertFalse(p.is_overlap())

Example 23

Project: django-multi-gtfs Source File: trip.py
Function: update_geometry
    def update_geometry(self, update_parent=True):
        """Update the geometry from the Shape or Stops"""
        original = self.geometry
        if self.shape:
            self.geometry = self.shape.geometry
        else:
            stoptimes = self.stoptime_set.order_by('stop_sequence')
            if stoptimes.count() > 1:
                self.geometry = LineString(
                    [st.stop.point.coords for st in stoptimes])
        if self.geometry != original:
            self.save()
            if update_parent:
                self.route.update_geometry()

Example 24

Project: Geotrek-admin Source File: test_topology.py
    def test_point_geom_moving(self):
        p1 = PathFactory.create(geom=LineString((0, 0),
                                                (0, 5)))
        poi = Point(0, 2.5, srid=settings.SRID)
        poi.transform(settings.API_SRID)
        poitopo = Topology.deserialize({'lat': poi.y, 'lng': poi.x})
        self.assertTrue(almostequal(0.5, poitopo.aggregations.all()[0].start_position))
        self.assertTrue(almostequal(0, poitopo.offset))
        self.assertTrue(almostequal(0, poitopo.geom.x))
        self.assertTrue(almostequal(2.5, poitopo.geom.y))
        p1.geom = LineString((10, 0),
                             (10, 5))
        p1.save()
        poitopo.reload()
        self.assertTrue(almostequal(10, poitopo.geom.x))
        self.assertTrue(almostequal(2.5, poitopo.geom.y))

Example 25

Project: Geotrek-admin Source File: test_elevation.py
    def setUp(self):
        # Create a simple fake DEM
        conn = connections[DEFAULT_DB_ALIAS]
        cur = conn.cursor()
        cur.execute('CREATE TABLE mnt (rid serial primary key, rast raster)')
        cur.execute('INSERT INTO mnt (rast) VALUES (ST_MakeEmptyRaster(100, 125, 0, 125, 25, -25, 0, 0, %s))', [settings.SRID])
        cur.execute('UPDATE mnt SET rast = ST_AddBand(rast, \'16BSI\')')
        demvalues = [[0, 0, 3, 5], [2, 2, 10, 15], [5, 15, 20, 25], [20, 25, 30, 35], [30, 35, 40, 45]]
        for y in range(0, 5):
            for x in range(0, 4):
                cur.execute('UPDATE mnt SET rast = ST_SetValue(rast, %s, %s, %s::float)', [x + 1, y + 1, demvalues[y][x]])

        self.path = Path.objects.create(geom=LineString((78, 117), (3, 17)))

Example 26

Project: Geotrek-admin Source File: test_topology.py
    def test_trek_loop(self):
        """
                            =========
                           ||       ||
        +-------===========+=========+----------+
        """
        p1 = PathFactory.create(geom=LineString((0, 0), (10, 0)))
        p2 = PathFactory.create(geom=LineString((10, 0), (30, 0)))
        p3 = PathFactory.create(geom=LineString((10, 0), (10, 5),
                                                (20, 5), (20, 0)))
        topo = TopologyFactory.create(no_path=True)
        topo.add_path(p1, start=0.3, end=1)
        topo.add_path(p3)
        topo.add_path(p2, start=1, end=0)
        topo.add_path(p1, start=1, end=0.3)
        topo.save()
        self.assertEqual(topo.geom, LineString((3, 0), (10, 0), (10, 5), (20, 5), (20, 0),
                                               (10, 0), (3, 0)))

Example 27

Project: Geotrek-admin Source File: test_topology.py
    def test_topology_geom_should_not_be_sampled(self):
        coords = [(x, math.sin(x)) for x in range(100)]
        sampled_3d = [(x, math.sin(x), math.cos(x)) for x in range(0, 100, 5)]
        p1 = PathFactory.create(geom=LineString(*coords))
        p1.geom_3d = LineString(*sampled_3d)
        p1.save(update_fields=['geom_3d'])

        t = TopologyFactory.create(no_path=True)
        t.add_path(p1, start=0.0, end=1.0)
        t.save()

        self.assertEqual(len(t.geom.coords), 100)

Example 28

Project: Geotrek-admin Source File: test_elevation.py
    def test_elevation_profile_wrong_geom(self):
        geom = MultiLineString(LineString((1.5, 2.5, 8), (2.5, 2.5, 10)),
                               LineString((2.5, 2.5, 6), (2.5, 0, 7)),
                               srid=settings.SRID)

        profile = AltimetryHelper.elevation_profile(geom)
        self.assertEqual(len(profile), 4)

Example 29

Project: Geotrek-admin Source File: test_topology.py
    def test_deserialize_multiple_lines(self):
        # Multiple paths
        p1 = PathFactory.create(geom=LineString((0, 0), (2, 2)))
        p2 = PathFactory.create(geom=LineString((2, 2), (2, 0)))
        p3 = PathFactory.create(geom=LineString((2, 0), (4, 0)))
        pks = [p.pk for p in [p1, p2, p3]]
        topology = Topology.deserialize('{"paths": %s, "positions": {"0": [0.0, 1.0], "2": [0.0, 1.0]}, "offset": 1}' % (pks))
        for i in range(3):
            self.assertEqual(topology.aggregations.all()[i].start_position, 0.0)
            self.assertEqual(topology.aggregations.all()[i].end_position, 1.0)

        topology = Topology.deserialize('{"paths": %s, "positions": {"0": [0.3, 1.0], "2": [0.0, 0.7]}, "offset": 1}' % (pks))
        self.assertEqual(topology.aggregations.all()[0].start_position, 0.3)
        self.assertEqual(topology.aggregations.all()[0].end_position, 1.0)
        self.assertEqual(topology.aggregations.all()[1].start_position, 0.0)
        self.assertEqual(topology.aggregations.all()[1].end_position, 1.0)
        self.assertEqual(topology.aggregations.all()[2].start_position, 0.0)
        self.assertEqual(topology.aggregations.all()[2].end_position, 0.7)

Example 30

Project: splunk-webframework Source File: test_geos.py
Function: test_distance
    def test_distance(self):
        "Testing the distance() function."
        # Distance to self should be 0.
        pnt = Point(0, 0)
        self.assertEqual(0.0, pnt.distance(Point(0, 0)))

        # Distance should be 1
        self.assertEqual(1.0, pnt.distance(Point(0, 1)))

        # Distance should be ~ sqrt(2)
        self.assertAlmostEqual(1.41421356237, pnt.distance(Point(1, 1)), 11)

        # Distances are from the closest vertex in each geometry --
        #  should be 3 (distance from (2, 2) to (5, 2)).
        ls1 = LineString((0, 0), (1, 1), (2, 2))
        ls2 = LineString((5, 2), (6, 1), (7, 0))
        self.assertEqual(3, ls1.distance(ls2))

Example 31

Project: Geotrek-admin Source File: test_triggers.py
    def test_smart_makeline(self):
        self.assertEqual(self.smart_makeline([
            LineString((0, 0), (1, 0)),
            LineString((2, 0), (1, 0)),
            LineString((2, 0), (2, 4)),
            LineString((2, 4), (2, 0)),
            LineString((2, 0), (3, 0))]), LineString((0, 0), (1, 0), (2, 0), (2, 4), (2, 0), (3, 0)))

Example 32

Project: Geotrek-admin Source File: test_elevation.py
    def test_elevation_altimetry_limits(self):
        geom = LineString((1.5, 2.5, 8), (2.5, 2.5, 10),
                          srid=settings.SRID)
        profile = AltimetryHelper.elevation_profile(geom)
        limits = AltimetryHelper.altimetry_limits(profile)
        self.assertEqual(limits[0], 1108)
        self.assertEqual(limits[1], -92)

Example 33

Project: Geotrek-admin Source File: models.py
    @classproperty
    def geomfield(cls):
        from django.contrib.gis.geos import LineString
        # Fake field, TODO: still better than overkill code in views, but can do neater.
        c = GeometryCollection([LineString((0, 0), (1, 1))], srid=settings.SRID)
        c.name = 'geom'
        return c

Example 34

Project: PyClassLessons Source File: tests.py
    def _load_interstate_data(self):
        # Interstate (2D / 3D and Geographic/Projected variants)
        for name, line, exp_z in interstate_data:
            line_3d = GEOSGeometry(line, srid=4269)
            line_2d = LineString([l[:2] for l in line_3d.coords], srid=4269)

            # Creating a geographic and projected version of the
            # interstate in both 2D and 3D.
            Interstate3D.objects.create(name=name, line=line_3d)
            InterstateProj3D.objects.create(name=name, line=line_3d)
            Interstate2D.objects.create(name=name, line=line_2d)
            InterstateProj2D.objects.create(name=name, line=line_2d)

Example 35

Project: Geotrek-admin Source File: test_models.py
    def test_deleted_pois(self):
        p1 = PathFactory.create(geom=LineString((0, 0), (4, 4)))
        trek = TrekFactory.create(no_path=True)
        trek.add_path(p1)
        poi = POIFactory.create(no_path=True)
        poi.add_path(p1, start=0.6, end=0.6)
        self.assertItemsEqual(trek.pois, [poi])
        poi.delete()
        self.assertItemsEqual(trek.pois, [])

Example 36

Project: Geotrek-admin Source File: factories.py
def getRandomLineStringInBounds(*args, **kwargs):
    """Return an horizontal line with 2 in bounds random points"""

    srid = settings.SRID
    minx, miny, maxx, maxy = kwargs.pop('bbox', settings.SPATIAL_EXTENT)

    assert srid == 2154, "Following code will use math fns that depends on this srid (floor)"

    # SRID 2154 use integer values. Substract 1 to maxx and maxy to be sure to be in bounds
    def get_in_bound_x():
        return math.floor(random.random() * ((maxx - minx) + 1) + minx)

    def get_in_bound_y():
        return math.floor(random.random() * ((maxy - miny) + 1) + miny)

    p1_x, p2_x = get_in_bound_x(), get_in_bound_x()
    p1_y = p2_y = get_in_bound_y()  # make a straight line to be easily identified

    return LineString([Point(p1_x, p1_y), Point(p2_x, p2_y)], srid=srid)

Example 37

Project: Geotrek-admin Source File: test_models.py
    def test_city_departure(self):
        trek = TrekFactory.create(no_path=True)
        p1 = PathFactory.create(geom=LineString((0, 0), (5, 5)))
        trek.add_path(p1)
        self.assertEqual(trek.city_departure, '')

        city1 = CityFactory.create(geom=MultiPolygon(Polygon(((-1, -1), (3, -1), (3, 3),
                                                              (-1, 3), (-1, -1)))))
        city2 = CityFactory.create(geom=MultiPolygon(Polygon(((3, 3), (9, 3), (9, 9),
                                                              (3, 9), (3, 3)))))
        self.assertEqual(trek.cities, [city1, city2])
        self.assertEqual(trek.city_departure, unicode(city1))

Example 38

Project: splunk-webframework Source File: tests.py
Function: test_reverse_geom
    @no_mysql
    @no_spatialite
    def test_reverse_geom(self):
        "Testing GeoQuerySet.reverse_geom()."
        coords = [ (-95.363151, 29.763374), (-95.448601, 29.713803) ]
        Track.objects.create(name='Foo', line=LineString(coords))
        t = Track.objects.reverse_geom().get(name='Foo')
        coords.reverse()
        self.assertEqual(tuple(coords), t.reverse_geom.coords)
        if oracle:
            self.assertRaises(TypeError, State.objects.reverse_geom)

Example 39

Project: Geotrek-admin Source File: test_models.py
    def test_save_with_another_geom(self):
        geom = LineString(((-7, -7), (5, -7), (5, 5), (-7, 5), (-7, -7)), srid=2154)
        self.trek.geom = geom
        self.trek.save()
        retrieve_trek = Trek.objects.get(pk=self.trek.pk)
        self.assertFalse(retrieve_trek.geom.equals_exact(geom, tolerance=0.00001))

Example 40

Project: Geotrek-admin Source File: test_fields.py
    def test_geom_can_be_geojson(self):
        geojsonstr = self.geojson.replace('"', '\\"')
        geom = self.f.clean('{"geom": "%s", '
                            ' "snap": [null, null]}' % geojsonstr)
        self.assertTrue(geom.equals_exact(
            LineString((100000, 100000), (200000, 200000),
                       srid=settings.SRID), 0.1))

Example 41

Project: django-geotagging Source File: tag_tests.py
    def setUp(self):
        self.installTagLibrary('geotagging.templatetags.geotagging_tags')
        denver_user = User.objects.create(username='denver')
        dia_user = User.objects.create(username='dia')
        aa_user = User.objects.create(username='annarbor')
	self.line = LineString((-104.552299, 38.128626), (-103.211191, 40.715081))
        self.denver = Geotag.objects.create(tagged_obj=denver_user,
                            point=Point(-104.9847034, 39.739153600000002))
        dia = Geotag.objects.create(tagged_obj=dia_user,
                            point=Point(-104.673856, 39.849511999999997))
        aa = Geotag.objects.create(tagged_obj=aa_user,
                            point=Point(-83.726329399999997, 42.2708716))

Example 42

Project: linz2osm Source File: overpass.py
def geometry_for_osm_feature(osm_feature, nodes={}, ways={}):
    if osm_feature['type'] == 'way':
        node_list = filter(None, [
                node_point(node_id, nodes) for node_id in osm_feature['nodes']
                ])
        if node_list:
            return LineString(node_list)
        else:
            return None
    elif osm_feature['type'] == 'node':
        return Point(osm_feature['lon'], osm_feature['lat'])
    elif osm_feature['type'] == 'rel':
        # FIXME - implement
        return None
    else:
        return None

Example 43

Project: Geotrek-admin Source File: test_graph.py
    def test_json_graph_simple(self):
        path = PathFactory(geom=LineString((0, 0), (1, 1)))
        response = self.client.get(self.url)
        self.assertEqual(response.status_code, 200)
        graph = json.loads(response.content)
        self.assertDictEqual({'edges': {str(path.pk): {u'id': path.pk, u'length': 1.4142135623731, u'nodes_id': [1, 2]}},
                              'nodes': {u'1': {u'2': path.pk}, u'2': {u'1': path.pk}}}, graph)

Example 44

Project: splunk-webframework Source File: test_geos.py
Function: test_threed
    def test_threed(self):
        "Testing three-dimensional geometries."
        # Testing a 3D Point
        pnt = Point(2, 3, 8)
        self.assertEqual((2.,3.,8.), pnt.coords)
        self.assertRaises(TypeError, pnt.set_coords, (1.,2.))
        pnt.coords = (1.,2.,3.)
        self.assertEqual((1.,2.,3.), pnt.coords)

        # Testing a 3D LineString
        ls = LineString((2., 3., 8.), (50., 250., -117.))
        self.assertEqual(((2.,3.,8.), (50.,250.,-117.)), ls.tuple)
        self.assertRaises(TypeError, ls.__setitem__, 0, (1.,2.))
        ls[0] = (1.,2.,3.)
        self.assertEqual((1.,2.,3.), ls[0])

Example 45

Project: Geotrek-admin Source File: test_elevation.py
    def test_elevation_topology_outside_dem(self):
        outside_path = Path.objects.create(geom=LineString((200, 200), (300, 300)))
        topo = TopologyFactory.create(no_path=True)
        topo.add_path(outside_path, start=0.5, end=0.5)
        topo.save()
        self.assertEqual(topo.geom_3d.coords[2], 0)
        self.assertEqual(topo.ascent, 0)
        self.assertEqual(topo.descent, 0)
        self.assertEqual(topo.min_elevation, 0)
        self.assertEqual(topo.max_elevation, 0)

Example 46

Project: Geotrek-admin Source File: test_topology.py
    def test_opposite_paths(self):
        """
                A  C
        B +-------+-------+ D

        """
        ab = PathFactory.create(geom=LineString((5, 0), (0, 0)))
        cd = PathFactory.create(geom=LineString((5, 0), (10, 0)))
        topo = TopologyFactory.create(no_path=True)
        topo.add_path(ab, start=0.2, end=0)
        topo.add_path(cd, start=0, end=0.2)
        topo.save()
        expected = LineString((4, 0), (5, 0), (6, 0))
        self.assertEqual(topo.geom, expected)
        # Now let's have some fun, reverse BA :)
        ab.reverse()
        ab.save()
        topo.reload()
        self.assertEqual(topo.geom, expected)

Example 47

Project: PyClassLessons Source File: tests.py
Function: test_geometryfield
    @no_spatialite  # SpatiaLite does not support abstract geometry columns
    def test_geometryfield(self):
        "Testing the general GeometryField."
        Feature(name='Point', geom=Point(1, 1)).save()
        Feature(name='LineString', geom=LineString((0, 0), (1, 1), (5, 5))).save()
        Feature(name='Polygon', geom=Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0)))).save()
        Feature(name='GeometryCollection',
                geom=GeometryCollection(Point(2, 2), LineString((0, 0), (2, 2)),
                                        Polygon(LinearRing((0, 0), (0, 5), (5, 5), (5, 0), (0, 0))))).save()

        f_1 = Feature.objects.get(name='Point')
        self.assertEqual(True, isinstance(f_1.geom, Point))
        self.assertEqual((1.0, 1.0), f_1.geom.tuple)
        f_2 = Feature.objects.get(name='LineString')
        self.assertEqual(True, isinstance(f_2.geom, LineString))
        self.assertEqual(((0.0, 0.0), (1.0, 1.0), (5.0, 5.0)), f_2.geom.tuple)

        f_3 = Feature.objects.get(name='Polygon')
        self.assertEqual(True, isinstance(f_3.geom, Polygon))
        f_4 = Feature.objects.get(name='GeometryCollection')
        self.assertEqual(True, isinstance(f_4.geom, GeometryCollection))
        self.assertEqual(f_3.geom, f_4.geom[2])

Example 48

Project: PyClassLessons Source File: tests.py
    @no_spatialite
    def test_distance_geodetic(self):
        """
        Test the `distance` GeoQuerySet method on geodetic coordinate systems.
        """
        tol = 2 if oracle else 5

        # Testing geodetic distance calculation with a non-point geometry
        # (a LineString of Wollongong and Shellharbour coords).
        ls = LineString(((150.902, -34.4245), (150.87, -34.5789)))
        if oracle or connection.ops.geography:
            # Reference query:
            #  SELECT ST_distance_sphere(point, ST_GeomFromText('LINESTRING(150.9020 -34.4245,150.8700 -34.5789)', 4326)) FROM distapp_australiacity ORDER BY name;
            distances = [1120954.92533513, 140575.720018241, 640396.662906304,
                         60580.9693849269, 972807.955955075, 568451.8357838,
                         40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0]
            qs = AustraliaCity.objects.distance(ls).order_by('name')
            for city, distance in zip(qs, distances):
                # Testing equivalence to within a meter.
                self.assertAlmostEqual(distance, city.distance.m, 0)
        else:
            # PostGIS 1.4 and below is limited to disance queries only
            # to/from point geometries, check for raising of ValueError.
            self.assertRaises(ValueError, AustraliaCity.objects.distance, ls)
            self.assertRaises(ValueError, AustraliaCity.objects.distance, ls.wkt)

        # Got the reference distances using the raw SQL statements:
        #  SELECT ST_distance_spheroid(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326), 'SPHEROID["WGS 84",6378137.0,298.257223563]') FROM distapp_australiacity WHERE (NOT (id = 11));
        #  SELECT ST_distance_sphere(point, ST_GeomFromText('POINT(151.231341 -33.952685)', 4326)) FROM distapp_australiacity WHERE (NOT (id = 11));  st_distance_sphere
        if connection.ops.postgis and connection.ops.proj_version_tuple() >= (4, 7, 0):
            # PROJ.4 versions 4.7+ have updated datums, and thus different
            # distance values.
            spheroid_distances = [60504.0628957201, 77023.9489850262, 49154.8867574404,
                                  90847.4358768573, 217402.811919332, 709599.234564757,
                                  640011.483550888, 7772.00667991925, 1047861.78619339,
                                  1165126.55236034]
            sphere_distances = [60580.9693849267, 77144.0435286473, 49199.4415344719,
                                90804.7533823494, 217713.384600405, 709134.127242793,
                                639828.157159169, 7786.82949717788, 1049204.06569028,
                                1162623.7238134]

        else:
            spheroid_distances = [60504.0628825298, 77023.948962654, 49154.8867507115,
                                  90847.435881812, 217402.811862568, 709599.234619957,
                                  640011.483583758, 7772.00667666425, 1047861.7859506,
                                  1165126.55237647]
            sphere_distances = [60580.7612632291, 77143.7785056615, 49199.2725132184,
                                90804.4414289463, 217712.63666124, 709131.691061906,
                                639825.959074112, 7786.80274606706, 1049200.46122281,
                                1162619.7297006]

        # Testing with spheroid distances first.
        hillsdale = AustraliaCity.objects.get(name='Hillsdale')
        qs = AustraliaCity.objects.exclude(id=hillsdale.id).distance(hillsdale.point, spheroid=True)
        for i, c in enumerate(qs):
            self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol)
        if postgis:
            # PostGIS uses sphere-only distances by default, testing these as well.
            qs = AustraliaCity.objects.exclude(id=hillsdale.id).distance(hillsdale.point)
            for i, c in enumerate(qs):
                self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)

Example 49

Project: PyClassLessons Source File: tests.py
    def test_proxy(self):
        "Testing Lazy-Geometry support (using the GeometryProxy)."
        ## Testing on a Point
        pnt = Point(0, 0)
        nullcity = City(name='NullCity', point=pnt)
        nullcity.save()

        # Making sure TypeError is thrown when trying to set with an
        #  incompatible type.
        for bad in [5, 2.0, LineString((0, 0), (1, 1))]:
            try:
                nullcity.point = bad
            except TypeError:
                pass
            else:
                self.fail('Should throw a TypeError')

        # Now setting with a compatible GEOS Geometry, saving, and ensuring
        #  the save took, notice no SRID is explicitly set.
        new = Point(5, 23)
        nullcity.point = new

        # Ensuring that the SRID is automatically set to that of the
        #  field after assignment, but before saving.
        self.assertEqual(4326, nullcity.point.srid)
        nullcity.save()

        # Ensuring the point was saved correctly after saving
        self.assertEqual(new, City.objects.get(name='NullCity').point)

        # Setting the X and Y of the Point
        nullcity.point.x = 23
        nullcity.point.y = 5
        # Checking assignments pre & post-save.
        self.assertNotEqual(Point(23, 5), City.objects.get(name='NullCity').point)
        nullcity.save()
        self.assertEqual(Point(23, 5), City.objects.get(name='NullCity').point)
        nullcity.delete()

        ## Testing on a Polygon
        shell = LinearRing((0, 0), (0, 100), (100, 100), (100, 0), (0, 0))
        inner = LinearRing((40, 40), (40, 60), (60, 60), (60, 40), (40, 40))

        # Creating a State object using a built Polygon
        ply = Polygon(shell, inner)
        nullstate = State(name='NullState', poly=ply)
        self.assertEqual(4326, nullstate.poly.srid)  # SRID auto-set from None
        nullstate.save()

        ns = State.objects.get(name='NullState')
        self.assertEqual(ply, ns.poly)

        # Testing the `ogr` and `srs` lazy-geometry properties.
        if gdal.HAS_GDAL:
            self.assertEqual(True, isinstance(ns.poly.ogr, gdal.OGRGeometry))
            self.assertEqual(ns.poly.wkb, ns.poly.ogr.wkb)
            self.assertEqual(True, isinstance(ns.poly.srs, gdal.SpatialReference))
            self.assertEqual('WGS 84', ns.poly.srs.name)

        # Changing the interior ring on the poly attribute.
        new_inner = LinearRing((30, 30), (30, 70), (70, 70), (70, 30), (30, 30))
        ns.poly[1] = new_inner
        ply[1] = new_inner
        self.assertEqual(4326, ns.poly.srid)
        ns.save()
        self.assertEqual(ply, State.objects.get(name='NullState').poly)
        ns.delete()

Example 50

Project: splunk-webframework Source File: test_geos.py
    def test_linestring(self):
        "Testing LineString objects."
        prev = fromstr('POINT(0 0)')
        for l in self.geometries.linestrings:
            ls = fromstr(l.wkt)
            self.assertEqual(ls.geom_type, 'LineString')
            self.assertEqual(ls.geom_typeid, 1)
            self.assertEqual(ls.empty, False)
            self.assertEqual(ls.ring, False)
            if hasattr(l, 'centroid'):
                self.assertEqual(l.centroid, ls.centroid.tuple)
            if hasattr(l, 'tup'):
                self.assertEqual(l.tup, ls.tuple)

            self.assertEqual(True, ls == fromstr(l.wkt))
            self.assertEqual(False, ls == prev)
            self.assertRaises(GEOSIndexError, ls.__getitem__, len(ls))
            prev = ls

            # Creating a LineString from a tuple, list, and numpy array
            self.assertEqual(ls, LineString(ls.tuple))  # tuple
            self.assertEqual(ls, LineString(*ls.tuple)) # as individual arguments
            self.assertEqual(ls, LineString([list(tup) for tup in ls.tuple])) # as list
            self.assertEqual(ls.wkt, LineString(*tuple(Point(tup) for tup in ls.tuple)).wkt) # Point individual arguments
            if numpy: self.assertEqual(ls, LineString(numpy.array(ls.tuple))) # as numpy array
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3