public static Feature ToFeature(this RouterDb routerDb, uint edgeId)
        {
            var enumerator = routerDb.Network.GetEnumerator();

            if (!enumerator.MoveToEdge(edgeId))
            {
                return(null);
            }

            var vertex1 = routerDb.Network.GetVertex(enumerator.From);
            var vertex2 = routerDb.Network.GetVertex(enumerator.To);

            // compose geometry.
            var coordinates = new List <Coordinate>();

            coordinates.Add(new Coordinate(vertex1.Longitude, vertex1.Latitude));
            var shape = enumerator.GetShape();

            if (shape != null)
            {
                foreach (var shapePoint in shape)
                {
                    coordinates.Add(new Coordinate(shapePoint.Longitude, shapePoint.Latitude));
                }
            }
            coordinates.Add(new Coordinate(vertex2.Longitude, vertex2.Latitude));

            var attributes = new AttributesTable();
            var tags       = routerDb.GetAttributes(edgeId);

            foreach (var tag in tags)
            {
                attributes.Add(tag.Key, tag.Value);
            }

            return(new Feature(new LineString(coordinates.ToArray()), attributes));
        }
Beispiel #2
0
        public void SaveNodesToShape(string shapeFileName, Dictionary <long, GeoNode> allNodesCache, List <GeoNode> nodesToSave)
        {
            string firstNameAttribute = "a";
            string lastNameAttribute  = "b";

            //create geometry factory
            IGeometryFactory geomFactory = NtsGeometryServices.Instance.CreateGeometryFactory();


            IList <Feature> features = new List <Feature>();

            for (int i = 0; i < nodesToSave.Count - 1; i++)
            {
                GeoNode node1 = nodesToSave[i];
                GeoNode node2 = nodesToSave[i + 1];
                //var ngbGeoNode = allNodesCache[ngb.NodeId];
                var             line = geomFactory.CreateLineString(new[] { new Coordinate(node1.Longitude, node1.Latitude), new Coordinate(node2.Longitude, node2.Latitude) });
                AttributesTable t1   = new AttributesTable();
                t1.AddAttribute(firstNameAttribute, node1.OSMId);
                t1.AddAttribute(lastNameAttribute, node2.OSMId);

                Feature feat = new Feature(line, t1);
                features.Add(feat);
            }
            var dirName = Path.GetDirectoryName(shapeFileName);

            if (!Directory.Exists(dirName))
            {
                Directory.CreateDirectory(dirName);
            }
            var writer = new ShapefileDataWriter(shapeFileName)
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Count)
            };

            writer.Write(features);
        }
        public void ToGpx_WithAllTypesOffeatures_ShouldBeConverted()
        {
            var converter = new GpxGeoJsonConverter();
            var geojson   = new FeatureCollection();
            var table     = new AttributesTable();

            geojson.Features.Add(new Feature(new Point(new Coordinate(1, 1)), table));
            geojson.Features.Add(new Feature(new MultiPoint(new[] { new Point(new Coordinate(2, 2)) as IPoint }), table));
            geojson.Features.Add(new Feature(new Polygon(new LinearRing(new [] { new Coordinate(3, 3), new Coordinate(4, 4), new Coordinate(5, 5), new Coordinate(3, 3) })), table));
            geojson.Features.Add(new Feature(new LineString(new[] { new Coordinate(6, 6), new Coordinate(7, 7) }), table));
            geojson.Features.Add(new Feature(new MultiPolygon(new IPolygon[] { new Polygon(new LinearRing(new [] { new Coordinate(8, 8), new Coordinate(9, 9), new Coordinate(10, 10), new Coordinate(8, 8) })) }), table));
            geojson.Features.Add(new Feature(new MultiLineString(new ILineString[]
            {
                new LineString(new[] { new Coordinate(11, 11), new Coordinate(12, 12) }),
                new LineString(new[] { new Coordinate(12, 12), new Coordinate(13, 13) }),
                new LineString(new[] { new Coordinate(14, 14), new Coordinate(15, 15) }),
            }), table));

            var gpx = converter.ToGpx(geojson);

            Assert.AreEqual(2, gpx.wpt.Length);
            Assert.AreEqual(3, gpx.rte.Length);
            Assert.AreEqual(2, gpx.trk.Length);
        }
        public static string ToGeoJson(IEnumerable <System.Data.Entity.Spatial.DbGeometry> dbGeometrys,
                                       ProjectionInfo pStart, DataTable dataTable)
        {
            var pEnd              = Definitions.WorldProjection;
            var dbGeometrys1      = dbGeometrys as IList <System.Data.Entity.Spatial.DbGeometry> ?? dbGeometrys.ToList();
            var reader            = new WKTReader();
            var featureCollection = new FeatureCollection();
            var columns           = (from DataColumn column in dataTable.Columns select column.ColumnName).ToList();

            for (var i = 0; i < dbGeometrys1.Count(); i++)
            {
                var geometry = GeometryHelper.Project(dbGeometrys1[i].MakeValid(), pStart, pEnd);
                var read     = reader.Read(geometry.WellKnownValue.WellKnownText);
                var table    = new AttributesTable();
                foreach (var column in columns)
                {
                    table.AddAttribute(column, dataTable.Rows[i][column]);
                }
                featureCollection.Add(new Feature(read, table));
            }
            var geoJsonWriter = new GeoJsonWriter();

            return(geoJsonWriter.Write(featureCollection));
        }
Beispiel #5
0
        public void TestWriteFeatureCollectionWithFirstFeatureGeometryNull()
        {
            // Setup
            var geoJsonWriter = new GeoJsonWriter();

            var featureJson            = "{\"type\": \"Feature\",\"geometry\": {\"type\": \"LineString\",\"coordinates\": [[0,0],[2,2],[3,2]]},\"properties\": {\"key\": \"value\"}}";
            var notNullGeometryFeature = new GeoJsonReader().Read <Feature>(featureJson);

            var attributesTable = new AttributesTable {
                { "key", "value" }
            };
            IGeometry geometry            = null;
            var       nullGeometryFeature = new Feature(geometry, attributesTable);

            var features_notNullFirst = new Collection <IFeature>
            {
                notNullGeometryFeature,
                nullGeometryFeature
            };

            var features_nullFirst = new Collection <IFeature>
            {
                nullGeometryFeature,
                notNullGeometryFeature
            };

            var featureCollection_notNullFirst = new FeatureCollection(features_notNullFirst);
            var featureCollection_nullFirst    = new FeatureCollection(features_nullFirst);

            // Act
            TestDelegate write_notNullFirst = () => geoJsonWriter.Write(featureCollection_notNullFirst);
            TestDelegate write_nullFirst    = () => geoJsonWriter.Write(featureCollection_nullFirst);

            Assert.That(write_notNullFirst, Throws.Nothing);
            Assert.That(write_nullFirst, Throws.Nothing);
        }
Beispiel #6
0
        private AttributesTable GetAttributes(JsonOffroadTrack offroadTrack)
        {
            var geoLocation = new AttributesTable
            {
                { FeatureAttributes.LAT, offroadTrack.start.latitude },
                { FeatureAttributes.LON, offroadTrack.start.longitude }
            };
            var category   = GetCategory(offroadTrack.activityType);
            var attributes = new AttributesTable
            {
                { FeatureAttributes.ID, offroadTrack.id },
                { FeatureAttributes.NAME, offroadTrack.title },
                { FeatureAttributes.POI_SOURCE, Sources.OFFROAD },
                { FeatureAttributes.POI_CATEGORY, category },
                { FeatureAttributes.POI_LANGUAGE, Languages.ALL },
                { FeatureAttributes.OSM_TYPE, string.Empty },
                { FeatureAttributes.ICON, GetIconByCategory(category) },
                { FeatureAttributes.ICON_COLOR, "black" },
                { FeatureAttributes.SEARCH_FACTOR, 1 },
                { FeatureAttributes.GEOLOCATION, geoLocation }
            };

            return(attributes);
        }
Beispiel #7
0
        public void TestConstructor2()
        {
            IAttributesTable at = null;

            /*
             * Assert.DoesNotThrow(
             *  () => at = new AttributesTable(new[] {new[] {"key1", new object()}, new[] {"key2", new object()}}));
             * Assert.That(at, Is.Not.Null);
             * Assert.That(at.Count, Is.EqualTo(2));
             * Assert.That(at.Exists("key1"), Is.True);
             * Assert.That(at.Exists("key2"), Is.True);
             * Assert.Throws<ArgumentException>(
             *  () => at = new AttributesTable(new[] {new[] {"key1", new object()}, new[] {(object) "key2",}}));
             * Assert.Throws<ArgumentException>(
             *  () => at = new AttributesTable(new[] {new[] {"key1", new object()}, new[] {new object(), "item2",}}));
             */
            Assert.DoesNotThrow(() => at = new AttributesTable {
                { "key1", new object() }, { "key2", new object() }
            });
            Assert.That(at, Is.Not.Null);
            Assert.That(at.Count, Is.EqualTo(2));
            Assert.That(at.Exists("key1"), Is.True);
            Assert.That(at.Exists("key2"), Is.True);
        }
Beispiel #8
0
        // see https://code.google.com/p/nettopologysuite/issues/detail?id=146
        public void Issue146_ShapeCreationWithInvalidAttributeName()
        {
            Coordinate[] points = new Coordinate[3];
            points[0] = new Coordinate(0, 0);
            points[1] = new Coordinate(1, 0);
            points[2] = new Coordinate(1, 1);
            LineString       ls  = new LineString(points);
            IMultiLineString mls = GeometryFactory.Default.CreateMultiLineString(new ILineString[] { ls });

            AttributesTable attrs = new AttributesTable();

            attrs.Add("Simulation name", "FOO");

            Feature[]           features   = new[] { new Feature(mls, attrs) };
            ShapefileDataWriter shp_writer = null;

            Assert.Throws <ArgumentException>(() => shp_writer =
                                                  new ShapefileDataWriter("invalid_line_string")
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Length)
            });

            //Assert.Throws<ArgumentException>(() => shp_writer.Write(features));
        }
Beispiel #9
0
        public static Dictionary <string, AttributesTable> ReadClassAttributes(string filename)
        {
            if (!File.Exists(filename))
            {
                Console.WriteLine("The file " + filename + " does not exist.");
                return(new Dictionary <string, AttributesTable>());
            }
            var             result = new Dictionary <string, AttributesTable>();
            DbaseFileReader reader = TryDbaseFileReader(filename);

            if (reader == null)
            {
                return(new Dictionary <string, AttributesTable>());
            }

            var header         = reader.GetHeader();
            int classNameIndex = 0;

            for (int i = 0; i < header.NumFields; ++i)
            {
                if (header.Fields[i].Name == "CNAM")
                {
                    classNameIndex = i;
                }
            }
            foreach (ArrayList entry in reader)
            {
                string className = (string)entry[classNameIndex];
                result[className] = new AttributesTable();
                for (int i = 0; i < header.NumFields; ++i)
                {
                    result[className].Add(header.Fields[i].Name, entry[i]);
                }
            }
            return(result);
        }
Beispiel #10
0
        private AttributesTable GetAttributes(JsonNakebItem nakebItem)
        {
            var geoLocation = new AttributesTable
            {
                { FeatureAttributes.LAT, nakebItem.start.Lat },
                { FeatureAttributes.LON, nakebItem.start.Lng }
            };
            var attributes = new AttributesTable
            {
                { FeatureAttributes.ID, nakebItem.id },
                { FeatureAttributes.NAME, nakebItem.title },
                { FeatureAttributes.POI_SOURCE, Sources.NAKEB },
                { FeatureAttributes.POI_CATEGORY, Categories.ROUTE_HIKE },
                { FeatureAttributes.POI_LANGUAGE, Languages.ALL },
                { FeatureAttributes.OSM_TYPE, string.Empty },
                { FeatureAttributes.ICON, "icon-hike" },
                { FeatureAttributes.ICON_COLOR, "black" },
                { FeatureAttributes.SEARCH_FACTOR, 1 },
                { FeatureAttributes.GEOLOCATION, geoLocation },
            };


            return(attributes);
        }
Beispiel #11
0
        /// <summary>
        /// Builds from the given provider.
        /// </summary>
        /// <param name="provider">
        /// The base <see cref="SharpMap.Data.Providers.IProvider"/>
        /// from witch initialize the <see cref="NtsProvider"/> instance.
        /// </param>
        private void BuildFromProvider(IProvider provider)
        {
            // Features list initialization
            _features = new List <Feature>(provider.GetFeatureCount());

            try
            {
                // Load all features from the given provider
                provider.Open();
                var ids = provider.GetOidsInView(provider.GetExtents());
                foreach (var id in ids)
                {
                    var             dataRow    = provider.GetFeatureByOid(id);
                    var             geometry   = dataRow.Geometry;
                    AttributesTable attributes = new AttributesTable();
                    var             att        = dataRow.Attributes;
                    foreach (var column in dataRow.Factory.AttributesDefinition)
                    {
                        var attName = column.AttributeName;
                        if (att[attName] == null || att[attName] is DBNull)
                        {
                            throw new ApplicationException("Null values not supported");
                        }
                        attributes.AddAttribute(attName, att[column.AttributeName]);
                    }
                    _features.Add(new Feature(geometry, attributes));
                }
            }
            finally
            {
                if (provider.IsOpen)
                {
                    provider.Close();
                }
            }
        }
Beispiel #12
0
        private AttributesTable GetAttributes(Coordinate location, string title, string id, string language)
        {
            var geoLocation = new AttributesTable
            {
                { FeatureAttributes.LAT, location.Y },
                { FeatureAttributes.LON, location.X }
            };
            var attributes = new AttributesTable
            {
                { FeatureAttributes.ID, id },
                { FeatureAttributes.NAME, title },
                { FeatureAttributes.POI_SOURCE, Sources.WIKIPEDIA },
                { FeatureAttributes.POI_CATEGORY, Categories.WIKIPEDIA },
                { FeatureAttributes.POI_LANGUAGE, language },
                { FeatureAttributes.OSM_TYPE, string.Empty },
                { FeatureAttributes.ICON, "icon-wikipedia-w" },
                { FeatureAttributes.ICON_COLOR, "black" },
                { FeatureAttributes.SEARCH_FACTOR, 1 },
                { FeatureAttributes.GEOLOCATION, geoLocation },
                { FeatureAttributes.SOURCE_IMAGE_URL, "https://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/128px-Wikipedia-logo-v2.svg.png" }
            };

            return(attributes);
        }
Beispiel #13
0
        public void ReadJsonWithInnerObjectTest()
        {
            const string             json   = "{\"test1\":\"value1\",\"test2\": { \"innertest1\":\"innervalue1\" }}}";
            AttributesTableConverter target = new AttributesTableConverter();

            using (JsonTextReader reader = new JsonTextReader(new StringReader(json)))
            {
                JsonSerializer serializer = new JsonSerializer();

                // read start object token and prepare the next token
                reader.Read();
                AttributesTable result =
                    (AttributesTable)
                    target.ReadJson(reader, typeof(AttributesTable), new AttributesTable(), serializer);
                Assert.IsNotNull(result);
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual("value1", result["test1"]);
                Assert.IsNotNull(result["test2"]);
                Assert.IsInstanceOf <IAttributesTable>(result["test2"]);
                IAttributesTable inner = (IAttributesTable)result["test2"];
                Assert.AreEqual(1, inner.Count);
                Assert.AreEqual("innervalue1", inner["innertest1"]);
            }
        }
Beispiel #14
0
 /// <summary>
 /// xy列表直接输出到shape文件
 /// </summary>
 /// <param name="polygonXYList">x1 y1,x2 y2,x3 y3,x4 y4</param>
 /// <param name="bw"></param>
 public static void ExportShapeFile(string path, List <string> polygonXYList)
 {
     try
     {
         ShapefileDataWriter shapeWrite  = new ShapefileDataWriter(path);
         IGeometryFactory    pGFactory   = new GeometryFactory();
         IList <Feature>     featureList = new List <Feature>();
         foreach (string str in polygonXYList)
         {
             List <Coordinate> coordList = new List <Coordinate>();
             string[]          xys       = str.Split(',');
             string            name      = xys[0];
             AttributesTable   at        = new AttributesTable();
             at.AddAttribute("TFH", name);
             for (int i = 1; i < xys.Length; i++)
             {
                 string[] xandy = xys[i].Split(' ');
                 double   x = 0, y = 0;
                 double.TryParse(xandy[0], out x);
                 double.TryParse(xandy[1], out y);
                 Coordinate coord = new Coordinate(x, y);
                 coordList.Add(coord);
             }
             IPolygon pPolygon = pGFactory.CreatePolygon(coordList.ToArray());
             Feature  f        = new Feature(pPolygon, at);
             featureList.Add(f);
         }
         System.Collections.IList features = (System.Collections.IList)featureList;
         shapeWrite.Header = ShapefileDataWriter.GetHeader(featureList[0], featureList.Count);
         shapeWrite.Write(features);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Beispiel #15
0
        /// <summary>
        /// This is a static function to update the geolocation of a feature for search capabilities
        /// </summary>
        /// <param name="feature"></param>
        public static void UpdateLocation(Feature feature)
        {
            if ((feature.Geometry is LineString || feature.Geometry is MultiLineString) && feature.Geometry.Coordinate != null)
            {
                var geoLocationTable = new AttributesTable
                {
                    { FeatureAttributes.LAT, feature.Geometry.Coordinate.Y },
                    { FeatureAttributes.LON, feature.Geometry.Coordinate.X }
                };
                feature.Attributes.AddAttribute(FeatureAttributes.GEOLOCATION, geoLocationTable);
                return;
            }
            if (feature.Geometry.Centroid == null || feature.Geometry.Centroid.IsEmpty)
            {
                return;
            }
            var table = new AttributesTable
            {
                { FeatureAttributes.LAT, feature.Geometry.Centroid.Y },
                { FeatureAttributes.LON, feature.Geometry.Centroid.X }
            };

            feature.Attributes.AddAttribute(FeatureAttributes.GEOLOCATION, table);
        }
        /// <summary>
        /// Creates an <see cref="IMultiLineString"/> <see cref="Feature"/> that contains the same data
        /// stored in a given <see cref="GpxTrack"/>.
        /// </summary>
        /// <param name="track">
        /// The <see cref="GpxTrack"/> source.
        /// </param>
        /// <param name="geometryFactory">
        /// The <see cref="IGeometryFactory"/> to use to create the <see cref="IMultiLineString"/>,
        /// or <see langword="null"/> to create a new one to use on-the-fly using the current
        /// <see cref="GeometryServiceProvider"/>.
        /// </param>
        /// <returns>
        /// A <see cref="Feature"/> that contains the same data as <paramref name="track"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// Thrown when <paramref name="track"/> is <see langword="null"/>
        /// </exception>
        /// <remarks>
        /// The values of <see cref="Feature.Attributes"/> will be populated with the values of the
        /// <see cref="GpxTrack"/> properties, even when <see langword="null"/>.
        /// </remarks>
        public static Feature ToFeature(GpxTrack track, IGeometryFactory geometryFactory)
        {
            if (track is null)
            {
                throw new ArgumentNullException(nameof(track));
            }

            if (geometryFactory is null)
            {
                geometryFactory = GeometryServiceProvider.Instance.CreateGeometryFactory();
            }

            // a track is an IMultiLineString feature.
            var lineStrings = new ILineString[track.Segments.Length];

            for (int i = 0; i < lineStrings.Length; i++)
            {
                lineStrings[i] = BuildLineString(track.Segments[i].Waypoints, geometryFactory);
            }

            var multiLineString = geometryFactory.CreateMultiLineString(lineStrings);
            var attributes      = new AttributesTable
            {
                { nameof(track.Name), track.Name },
                { nameof(track.Comment), track.Comment },
                { nameof(track.Description), track.Description },
                { nameof(track.Source), track.Source },
                { nameof(track.Links), track.Links },
                { nameof(track.Number), track.Number },
                { nameof(track.Classification), track.Classification },
                { nameof(track.Segments), track.Segments },
                { nameof(track.Extensions), track.Extensions },
            };

            return(new Feature(multiLineString, attributes));
        }
        public void Test()
        {
            var features = new List <IFeature>();
            var seq      = DotSpatialAffineCoordinateSequenceFactory.Instance.Create(1, Ordinates.XY);

            seq.SetOrdinate(0, Ordinate.X, -91.0454);
            seq.SetOrdinate(0, Ordinate.Y, 32.5907);
            var pt   = new GeometryFactory(DotSpatialAffineCoordinateSequenceFactory.Instance).CreatePoint(seq);
            var attr = new AttributesTable();

            attr.Add("FirstName", "John");
            attr.Add("LastName", "Doe");
            features.Add(new Feature(pt, attr));

            string fileName = Path.GetTempFileName();

            fileName = fileName.Substring(0, fileName.Length - 4);
            var shpWriter = new ShapefileDataWriter(fileName, features[0].Geometry.Factory)
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Count)
            };

            shpWriter.Write(features);

            bool isTrue;

            using (var reader = new ShapefileDataReader(fileName, pt.Factory))
                @isTrue = reader.ShapeHeader.ShapeType.ToString() == "Point";

            foreach (string file in Directory.GetFiles(Path.GetTempPath(), Path.GetFileName(fileName) + ".*"))
            {
                File.Delete(file);
            }

            Assert.IsTrue(@isTrue);
        }
Beispiel #18
0
        public void WriteJsonTest()
        {
            var sb  = new StringBuilder();
            var atS = new AttributesTable();
            IAttributesTable atD = null;

            atS.Add("test1", "value1");
            atS.Add("test2", "value2");
            var options = DefaultOptions;

            using (var ms = new MemoryStream())
            {
                Serialize(ms, atS, options);
                Assert.AreEqual("{\"test1\":\"value1\",\"test2\":\"value2\"}", Encoding.UTF8.GetString(ms.ToArray()));
                atD = Deserialize(ms, options);
            }

            Assert.That(atD, Is.Not.Null);
            Assert.That(atD.Count, Is.EqualTo(atS.Count));
            Assert.That(atD.GetNames()[0], Is.EqualTo(atS.GetNames()[0]));
            Assert.That(atD.GetNames()[1], Is.EqualTo(atS.GetNames()[1]));
            Assert.That(atD[atD.GetNames()[0]], Is.EqualTo(atS[atS.GetNames()[0]]));
            Assert.That(atD[atD.GetNames()[1]], Is.EqualTo(atS[atS.GetNames()[1]]));
        }
Beispiel #19
0
        /// <summary>
        /// Convert the given OSM node to a GeoJSON point feature.
        /// </summary>
        /// <param name="Node">An OSM node.</param>
        public static Feature ToGeoJSON(this Node Node)
        {
            // {
            //     "type":  "Feature",
            //     "id":    "node/35304749",
            //     "properties": {
            //         "@id":         "node/35304749",
            //         "highway":     "bus_stop",
            //         "name":        "Lobeda",
            //         "operator":    "JES",
            //         "wheelchair":  "yes"
            //     },
            //     "geometry": {
            //         "type":        "Point",
            //         "coordinates": [ 11.6023278, 50.8926376 ]
            //     }
            // }

            try
            {
                var             id    = string.Concat("node/", Node.Id);
                AttributesTable props = new AttributesTable();
                props.Add("osmid", id);
                foreach (var tag in Node.Tags)
                {
                    props.Add(tag.Key, tag.Value);
                }
                var feature = new Feature(new Point(new Coordinate(Node.Longitude, Node.Latitude)), props);
                return(feature);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("OSM to GeoJSON error for node");
                return(null);
            }
        }
Beispiel #20
0
        public static IFeature FromByteBuffer(ByteBuffer bb, Header header)
        {
            // TODO: introspect which layer
            var            columnsLayer = header.Layers(0).Value;
            IList <Column> columns      = null;

            if (columnsLayer.ColumnsLength > 0)
            {
                columns = new List <Column>();
                for (int i = 0; i < columnsLayer.ColumnsLength; i++)
                {
                    var column = columnsLayer.Columns(i).Value;
                    columns.Add(column);
                }
            }

            var feature = Feature.GetRootAsFeature(bb);
            IAttributesTable attributesTable = null;

            if (feature.ValuesLength > 0)
            {
                attributesTable = new AttributesTable();
            }

            var layer = header.Layers((int)feature.Layer).Value;

            for (int i = 0; i < feature.ValuesLength; i++)
            {
                var value  = feature.Values(i).Value;
                var column = columns[value.ColumnIndex];
                switch (column.Type)
                {
                case ColumnType.Bool:
                    attributesTable.AddAttribute(column.Name, value.BoolValue);
                    break;

                case ColumnType.Int:
                    attributesTable.AddAttribute(column.Name, value.IntValue);
                    break;

                case ColumnType.Long:
                    attributesTable.AddAttribute(column.Name, value.LongValue);
                    break;

                case ColumnType.Double:
                    attributesTable.AddAttribute(column.Name, value.DoubleValue);
                    break;

                case ColumnType.String:
                    attributesTable.AddAttribute(column.Name, value.StringValue);
                    break;

                default: throw new ApplicationException("Unknown type");
                }
            }

            var geometry = GeometryConversions.FromFlatbuf(feature.Geometry.Value, layer.GeometryType, layer.Dimensions);
            var f        = new NetTopologySuite.Features.Feature(geometry, attributesTable);

            return(f);
        }
Beispiel #21
0
        private IFeature BuildFeature(int index)
        {
            if (((index - 1) % 10000) == 0)
            {
                Itinero.Logging.Logger.Log("FeatureList", TraceEventType.Information,
                                           "Building feature {0}/{1}.", index - 1, this.Count);
            }

            var edge = _routerDb.Network.GetEdge((uint)index);

            var vertexLocation1 = _routerDb.Network.GeometricGraph.GetVertex(edge.From);
            var coordinates     = new List <Coordinate>();

            coordinates.Add(new Coordinate(vertexLocation1.Longitude, vertexLocation1.Latitude));
            var shape = edge.Shape;

            if (shape != null)
            {
                var shapeEnumerable = shape.GetEnumerator();
                shapeEnumerable.Reset();
                while (shapeEnumerable.MoveNext())
                {
                    coordinates.Add(new Coordinate(shapeEnumerable.Current.Longitude,
                                                   shapeEnumerable.Current.Latitude));
                }
            }
            var vertexLocation2 = _routerDb.Network.GeometricGraph.GetVertex(edge.To);

            coordinates.Add(new Coordinate(vertexLocation2.Longitude, vertexLocation2.Latitude));
            var geometry = new LineString(coordinates.ToArray());

            var length = 0.0f;

            for (var i = 0; i < coordinates.Count - 1; i++)
            {
                length += Itinero.LocalGeo.Coordinate.DistanceEstimateInMeter((float)coordinates[i + 0].Y, (float)coordinates[i + 0].X,
                                                                              (float)coordinates[i + 1].Y, (float)coordinates[i + 1].X);
            }

            var tags = new Itinero.Attributes.AttributeCollection(_routerDb.EdgeProfiles.Get(edge.Data.Profile));

            foreach (var tag in _routerDb.EdgeMeta.Get(edge.Data.MetaId))
            {
                tags.AddOrReplace(tag.Key, tag.Value);
            }

            var attributes = new AttributesTable();

            attributes.AddFrom("highway", tags);
            attributes.AddFrom("route", tags);

            foreach (var p in _profiles)
            {
                var vehicleShortName = p.Parent.Name;
                if (vehicleShortName.Length > 4)
                {
                    vehicleShortName = vehicleShortName.Substring(0, 4);
                }

                var profileShortName = p.Name;
                if (profileShortName == null)
                {
                    profileShortName = string.Empty;
                }
                if (profileShortName.Length > 2)
                {
                    profileShortName = profileShortName.Substring(0, 3);
                }

                var profileName = $"{vehicleShortName}_{profileShortName}";

                var factor = p.FactorAndSpeed(tags);
                attributes.Add(profileName.ToLower(), factor.Value != 0);
                attributes.Add(profileName + "_dir", factor.Direction);
                var speed = 1 / factor.SpeedFactor * 3.6;
                if (factor.SpeedFactor <= 0)
                {
                    speed = 65536;
                }
                attributes.Add(profileName + "_sp", System.Math.Round(speed, 2));
                speed = 1 / factor.Value * 3.6;
                if (factor.Value <= 0)
                {
                    speed = 65536;
                }
                attributes.Add(profileName + "_spc", System.Math.Round(speed, 2));
            }

            attributes.Add("length", System.Math.Round(length, 3));

            string lanesString;
            var    lanes         = 1;
            var    lanesVerified = false;

            if (tags.TryGetValue("lanes", out lanesString))
            {
                lanesVerified = true;
                if (!int.TryParse(lanesString, out lanes))
                {
                    lanes         = 1;
                    lanesVerified = false;
                }
            }
            attributes.Add("lanes", lanes);
            attributes.Add("lanes_ve", lanesVerified);

            var name = tags.ExtractName();

            attributes.Add("name", name);

            attributes.AddFrom("way_id", tags);
            attributes.AddFrom("tunnel", tags);
            attributes.AddFrom("bridge", tags);

            attributes.Add("from", edge.From);
            attributes.Add("to", edge.To);

            return(new Feature(geometry, attributes));
        }
Beispiel #22
0
        private FeatureWithID getFeatureWithId(IDTOGeometryHolder entity)
        {
            //create geojson
            List <FeatureWithID> featuresListChilds = new List <FeatureWithID>();

            FeatureWithID    feature   = new FeatureWithID();
            IAttributesTable attribute = new AttributesTable();

            feature.Id = entity.Id.ToString();

            IGeometry shape2d = (IGeometry)entity.Shape.Clone();

            foreach (Coordinate coord in shape2d.Coordinates)
            {
                coord.Z = Double.NaN;
            }

            feature.Geometry = shape2d;



            //GEOJSON PROPERTIES: Childs (= Achsenreferenzen)
            if (entity is IReferenzGruppeDTOHolder)
            {
                IReferenzGruppeDTOHolder holder = entity as IReferenzGruppeDTOHolder;
                List <AchsenReferenzDTO> achsenreferenzListe = holder.ReferenzGruppeDTO.AchsenReferenzenDTO;
                foreach (AchsenReferenzDTO ar in achsenreferenzListe)
                {
                    FeatureWithID    feat       = new FeatureWithID();
                    IAttributesTable attributes = new AttributesTable();

                    feat.Id       = ar.Id.ToString();
                    feat.Geometry = ar.Shape;
                    attributes.AddAttribute(geoJSONAttribute_AchsenSegmentId, ar.AchsenSegment);
                    AchsenSegmentDTO achs = null;
                    if (ar.AchsenSegmentDTO == null)
                    {
                        achs = (AchsenSegmentDTO)dtoService.GetDTOByID(ar.AchsenSegment);
                    }
                    else
                    {
                        achs = ar.AchsenSegmentDTO;
                    }
                    attributes.AddAttribute(geoJSONAttribute_IsInverted, achs.IsInverted.ToString());
                    feat.Attributes = attributes;
                    featuresListChilds.Add(feat);
                }

                attribute.AddAttribute(geoJSONAttribute_childs, featuresListChilds);
                if (entity is AchsenSegmentDTO)
                {
                    AchsenSegmentDTO achs = entity as AchsenSegmentDTO;
                    attribute.AddAttribute(geoJSONAttribute_IsInverted, achs.IsInverted.ToString());
                }

                //GEOJSON PROPERTIES: ZUSTANDSABSCHNITTE
                if (entity is StrassenabschnittGISDTO)
                {
                    StrassenabschnittGISDTO sa = entity as StrassenabschnittGISDTO;
                    List <FeatureWithID>    featuresListZustandsabschnitte = new List <FeatureWithID>();

                    IEnumerable <ZustandsabschnittGISDTO> zustandsabschnitte = this.dtoService.Get <ZustandsabschnittGISDTO>().Where(z => sa.ZustandsabschnittenId.Any(id => id.Equals(z.Id)));
                    foreach (ZustandsabschnittGISDTO zustandsabschnitt in zustandsabschnitte)
                    {
                        FeatureWithID    feat = new FeatureWithID();
                        IAttributesTable att  = new AttributesTable();

                        feat.Id         = zustandsabschnitt.Id.ToString();
                        feat.Geometry   = zustandsabschnitt.Shape;
                        feat.Attributes = att;

                        featuresListZustandsabschnitte.Add(feat);
                    }

                    attribute.AddAttribute(geoJSONAttribute_Zustandsabschnitte, featuresListZustandsabschnitte);

                    attribute.AddAttribute(geoJSONAttribute_InspektionsrouteID, sa.InspektionsRouteId);
                }
                else
                {
                    if (entity is ZustandsabschnittGISDTO)
                    {
                        var za = entity as ZustandsabschnittGISDTO;
                        attribute.AddAttribute(geoJSONAttribute_StrassenabschnittsID, za.StrassenabschnittGIS);
                        attribute.AddAttribute(geoJSONAttribute_Zustandsindex, za.Zustandsindex.ToString(CultureInfo.InvariantCulture));
                        StrassenabschnittGISDTO strab     = this.dtoService.GetDTOByID <StrassenabschnittGISDTO>(za.StrassenabschnittGIS);
                        IList <FeatureWithID>   trottoirs = new List <FeatureWithID>();

                        if (strab.Trottoir == Common.Enums.TrottoirTyp.BeideSeiten || strab.Trottoir == Common.Enums.TrottoirTyp.Links)
                        {
                            FeatureWithID      trottfeature = new FeatureWithID();
                            List <ILineString> lines        = new List <ILineString>();
                            IAttributesTable   attributes   = new AttributesTable();
                            trottfeature.Id = Guid.NewGuid().ToString();
                            foreach (AchsenReferenzDTO referenz in strab.ReferenzGruppeDTO.AchsenReferenzenDTO)
                            {
                                AchsenSegmentDTO segment = this.dtoService.GetDTOByID <AchsenSegmentDTO>(referenz.AchsenSegment);
                                decimal          offset  = (decimal)(strab.BreiteFahrbahn + strab.BreiteTrottoirLinks) / 2;
                                if (segment.IsInverted)
                                {
                                    offset *= -1;
                                }
                                lines.Add(GeometryUtils.createOffsetLineNew(referenz.Shape.Factory, (ILineString)referenz.Shape, (double)offset));
                            }
                            IGeometry shape = za.Shape.Factory.CreateMultiLineString(lines.Where(l => l != null).ToArray());

                            trottfeature.Geometry = shape;
                            attributes.AddAttribute(geoJSONAttribute_ZustandsabschnittId, za.Id.ToString());
                            attributes.AddAttribute(geoJSONAttribute_Zustandsindex, (int)za.ZustandsindexTrottoirLinks);
                            trottfeature.Attributes = attributes;
                            trottoirs.Add(trottfeature);
                        }
                        if (strab.Trottoir == Common.Enums.TrottoirTyp.BeideSeiten || strab.Trottoir == Common.Enums.TrottoirTyp.Rechts)
                        {
                            FeatureWithID      trottfeature = new FeatureWithID();
                            IAttributesTable   attributes   = new AttributesTable();
                            List <ILineString> lines        = new List <ILineString>();
                            trottfeature.Id = Guid.NewGuid().ToString();
                            foreach (AchsenReferenzDTO referenz in za.ReferenzGruppeDTO.AchsenReferenzenDTO)
                            {
                                AchsenSegmentDTO segment = this.dtoService.GetDTOByID <AchsenSegmentDTO>(referenz.AchsenSegment);
                                decimal          offset  = (decimal)(strab.BreiteFahrbahn + strab.BreiteTrottoirRechts) / 2;
                                if (!segment.IsInverted)
                                {
                                    offset *= -1;
                                }
                                lines.Add(GeometryUtils.createOffsetLineNew(referenz.Shape.Factory, (ILineString)referenz.Shape, (double)offset));
                            }
                            IGeometry shape = za.Shape.Factory.CreateMultiLineString(lines.Where(l => l != null).ToArray());

                            trottfeature.Geometry = shape;
                            attributes.AddAttribute(geoJSONAttribute_ZustandsabschnittId, za.Id.ToString());
                            attributes.AddAttribute(geoJSONAttribute_Zustandsindex, (int)za.ZustandsindexTrottoirRechts);
                            trottfeature.Attributes = attributes;
                            trottoirs.Add(trottfeature);
                        }
                        if (trottoirs.IsEmpty())
                        {
                            attribute.AddAttribute(geoJSONAttribute_Trottoir, geoJSON_EmptyFeatureCollection);
                        }
                        else
                        {
                            attribute.AddAttribute(geoJSONAttribute_Trottoir, trottoirs);
                        }
                    }
                }
            }
            feature.Attributes = attribute;
            return(feature);
        }
        private static object InternalReadJson(JsonReader reader, JsonSerializer serializer)
        {
            //// TODO: refactor to remove check when reading TopoJSON
            //if (reader.TokenType == JsonToken.StartArray)
            //{
            //    reader.Read(); // move to first item
            //    IList<object> array = new List<object>();
            //    do
            //    {
            //        if (reader.TokenType == JsonToken.EndArray) break;
            //        object inner = InternalReadJson(reader, serializer);
            //        array.Add(inner);
            //        reader.Read(); // move to next item
            //    } while (true);
            //    return array;
            //}

            if (reader.TokenType != JsonToken.StartObject)
            {
                throw new ArgumentException("Expected token '{' not found.");
            }

            // Advance reader
            reader.Read();

            AttributesTable attributesTable = null;

            if (reader.TokenType != JsonToken.Null)
            {
                attributesTable = new AttributesTable();
                while (reader.TokenType == JsonToken.PropertyName)
                {
                    string attributeName = (string)reader.Value;
                    reader.Read();
                    object attributeValue;
                    if (reader.TokenType == JsonToken.StartObject)
                    {
                        // inner object
                        attributeValue = InternalReadJson(reader, serializer);
                        if (reader.TokenType != JsonToken.EndObject)
                        {
                            throw new ArgumentException("Expected token '}' not found.");
                        }
                        // read EndObject token
                        reader.Read();
                    }
                    else if (reader.TokenType == JsonToken.StartArray)
                    {
                        attributeValue = InternalReadJsonArray(reader, serializer);
                        //reader.Read(); // move to first item
                        //IList<object> array = new List<object>();
                        //do
                        //{
                        //    object inner = InternalReadJson(reader, serializer);
                        //    array.Add(inner);
                        //    reader.Read(); // move to next item
                        //} while (reader.TokenType != JsonToken.EndArray);
                        //attributeValue = array;
                    }
                    else
                    {
                        attributeValue = reader.Value;
                        reader.Read();
                    }
                    attributesTable.Add(attributeName, attributeValue);
                }
            }
            // TODO: refactor to remove check when reading TopoJSON
            if (reader.TokenType != JsonToken.EndObject)
            {
                throw new ArgumentException("Expected token '}' not found.");
            }

            return(attributesTable);
        }
Beispiel #24
0
        /// <summary>
        /// Builds from the given provider.
        /// </summary>
        /// <param name="provider">
        /// The base <see cref="SharpMap.Data.Providers.IProvider"/> 
        /// from witch initialize the <see cref="NtsProvider"/> instance.
        /// </param>
        private void BuildFromProvider(IProvider provider)
        {
            // Features list initialization
            _features = new List<Feature>(provider.GetFeatureCount());

            try
            {
                // Load all features from the given provider
                provider.Open();
                var ids = provider.GetOidsInView(provider.GetExtents());
                foreach (var id in ids)
                {
                    var dataRow = provider.GetFeatureByOid(id);
                    var geometry = dataRow.Geometry;
                    AttributesTable attributes = new AttributesTable();
                    var att = dataRow.Attributes;
                    foreach (var column in dataRow.Factory.AttributesDefinition)
                    {
                        var attName = column.AttributeName;
                        if (att[attName] == null || att[attName] is DBNull)
                            throw new ApplicationException("Null values not supported");
                        attributes.AddAttribute(attName, att[column.AttributeName]);
                    }
                    _features.Add(new Feature(geometry, attributes));
                }
            }
            finally
            {
                if (provider.IsOpen)
                    provider.Close();
            }
        }
        public async Task <IActionResult> GetMvt(int z, uint x, uint y)
        {
            if (z < 13)
            {
                return(NotFound());
            }

            try
            {
                var polygons = TiledPolygonGraphBuilder.GetPolygonsForTile((x, y, z), Startup.CachePath, Startup.TileSource.GetTile,
                                                                           IsBarrier);

                var layer = new Layer {
                    Name = "urban-polygons"
                };
                await foreach (var loc in polygons)
                {
                    var max     = double.MinValue;
                    var maxType = string.Empty;

                    var names      = loc.Attributes.GetNames();
                    var values     = loc.Attributes.GetValues();
                    var attributes = new AttributesTable();
                    for (var a = 0; a < names.Length; a++)
                    {
                        attributes.Add(names[a], values[a]);

                        var name = names[a];
                        if (name.StartsWith("face"))
                        {
                            continue;
                        }

                        var o = values[a];
                        var d = o is IConvertible convertible?convertible.ToDouble(null) : 0d;

                        if (d > max)
                        {
                            max     = d;
                            maxType = name;
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(maxType))
                    {
                        attributes.Add("type", maxType);
                    }

                    layer.Features.Add(new Feature(loc.Geometry, attributes));
                }

                var vectorTile = new VectorTile
                {
                    TileId = new NetTopologySuite.IO.VectorTiles.Tiles.Tile((int)x, (int)y, z).Id
                };
                vectorTile.Layers.Add(layer);

                var memoryStream = new MemoryStream();
                vectorTile.Write(memoryStream);
                memoryStream.Seek(0, SeekOrigin.Begin);

                return(new FileStreamResult(memoryStream, "application/x-protobuf"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Beispiel #26
0
        /// <summary>
        /// Builds from the given provider.
        /// </summary>
        /// <param name="provider">
        /// The base <see cref="SharpMap.Data.Providers.IProvider"/> 
        /// from witch initialize the <see cref="NtsProvider"/> instance.
        /// </param>
        private void BuildFromProvider(IProvider provider)
        {
            // Features list initialization
            _features = new List<Feature>(provider.GetFeatureCount());

            try
            {
                // Load all features from the given provider
                provider.Open();
                Collection<uint> ids = provider.GetObjectIDsInView(provider.GetExtents());
                foreach (uint id in ids)
                {
                    var dataRow = provider.GetFeature(id);
                    var geometry = dataRow.Geometry;
                    AttributesTable attributes = new AttributesTable();
                    foreach (DataColumn column in dataRow.Table.Columns)
                    {
                        if (dataRow[column] == null || dataRow[column] is DBNull)
                            throw new ApplicationException("Null values not supported");
                        attributes.AddAttribute(column.ColumnName, dataRow[column]);
                    }
                    _features.Add(new Feature(geometry, attributes));
                }
            }
            finally
            {
                if (provider.IsOpen)
                    provider.Close();
            }
        }
Beispiel #27
0
        private FeatureWithID getFeatureWithId(IAbschnittGISBase entity)
        {
            List <AchsenReferenz> achsenreferenzListe = achsenReferenzService.GetAchsenReferenzGruppe(entity.ReferenzGruppe.Id);

            //create geojson
            List <FeatureWithID> featuresListChilds = new List <FeatureWithID>();

            FeatureWithID    feature   = new FeatureWithID();
            IAttributesTable attribute = new AttributesTable();

            feature.Id       = entity.Id.ToString();
            feature.Geometry = entity.Shape;

            //GEOJSON PROPERTIES: Childs (= Achsenreferenzen)

            foreach (AchsenReferenz ar in achsenreferenzListe)
            {
                FeatureWithID    feat       = new FeatureWithID();
                IAttributesTable attributes = new AttributesTable();

                feat.Id       = ar.Id.ToString();
                feat.Geometry = ar.Shape;
                attributes.AddAttribute(geoJSONAttribute_AchsenSegmentId, ar.AchsenSegment.Id);
                attributes.AddAttribute(geoJSONAttribute_IsInverted, ar.AchsenSegment.IsInverted);
                feat.Attributes = attributes;
                featuresListChilds.Add(feat);
            }

            attribute.AddAttribute(geoJSONAttribute_childs, featuresListChilds);

            if (entity is KoordinierteMassnahmeGIS)
            {
                attribute.AddAttribute("Name", ((KoordinierteMassnahmeGIS)entity).Projektname);
            }
            if (entity is MassnahmenvorschlagTeilsystemeGIS)
            {
                attribute.AddAttribute("Name", ((MassnahmenvorschlagTeilsystemeGIS)entity).Projektname);
                attribute.AddAttribute("System", localizationService.GetLocalizedEnum <TeilsystemTyp>(((MassnahmenvorschlagTeilsystemeGIS)entity).Teilsystem));
            }
            //GEOJSON PROPERTIES: ZUSTANDSABSCHNITTE
            if (entity is StrassenabschnittGIS)
            {
                List <FeatureWithID> featuresListZustandsabschnitte = new List <FeatureWithID>();

                List <ZustandsabschnittGIS> zustandsabschnitte = transactionScopeProvider.Queryable <ZustandsabschnittGIS>().Where(za => za.StrassenabschnittGIS.Id == entity.Id).ToList();
                foreach (ZustandsabschnittGIS zustandsabschnitt in zustandsabschnitte)
                {
                    FeatureWithID    feat = new FeatureWithID();
                    IAttributesTable att  = new AttributesTable();

                    feat.Id         = zustandsabschnitt.Id.ToString();
                    feat.Geometry   = zustandsabschnitt.Shape;
                    feat.Attributes = att;

                    featuresListZustandsabschnitte.Add(feat);
                }
                var sa = entity as StrassenabschnittGIS;

                attribute.AddAttribute(geoJSONAttribute_Zustandsabschnitte, featuresListZustandsabschnitte);
                attribute.AddAttribute(geoJSONAttribute_IsLocked, sa.IsLocked);
                if (sa.InspektionsRtStrAbschnitte.Count > 0)
                {
                    attribute.AddAttribute(geoJSONAttribute_InspektionsrouteID, sa.InspektionsRtStrAbschnitte.SingleOrDefault().InspektionsRouteGIS.Id);
                }
                else
                {
                    attribute.AddAttribute(geoJSONAttribute_InspektionsrouteID, "");
                }
            }
            else
            {
                if (entity is ZustandsabschnittGIS)
                {
                    attribute.AddAttribute(geoJSONAttribute_StrassenabschnittsID, ((ZustandsabschnittGIS)entity).StrassenabschnittGIS.Id);
                    var za = entity as ZustandsabschnittGIS;
                    attribute.AddAttribute(geoJSONAttribute_IsLocked, za.IsLocked);
                }
            }
            feature.Attributes = attribute;
            return(feature);
        }
        private static object InternalReadJson(JsonReader reader, JsonSerializer serializer,
                                               bool innerObject)
        {
            //// TODO: refactor to remove check when reading TopoJSON
            //if (reader.TokenType == JsonToken.StartArray)
            //{
            //    reader.Read(); // move to first item
            //    IList<object> array = new List<object>();
            //    do
            //    {
            //        if (reader.TokenType == JsonToken.EndArray) break;
            //        object inner = InternalReadJson(reader, serializer);
            //        array.Add(inner);
            //        reader.Read(); // move to next item
            //    } while (true);
            //    return array;
            //}

            if (reader.TokenType != JsonToken.StartObject)
            {
                throw new ArgumentException("Expected token '{' not found.");
            }

            // Advance reader
            reader.Read();
            reader.SkipComments();

            IAttributesTable attributesTable = null;

            if (!innerObject && serializer.Context.Context is IFeature feature)
            {
                attributesTable = feature.Attributes;
            }

            if (reader.TokenType != JsonToken.Null)
            {
                if (attributesTable is null)
                {
                    attributesTable = new AttributesTable();
                }

                while (reader.TokenType == JsonToken.PropertyName)
                {
                    string attributeName = (string)reader.Value;
                    reader.Read();
                    object attributeValue;
                    if (reader.TokenType == JsonToken.StartObject)
                    {
                        if (serializer.TypeNameHandling != TypeNameHandling.Objects)
                        {
                            // inner object to AttributeTable
                            attributeValue = InternalReadJson(reader, serializer, true);
                            if (reader.TokenType != JsonToken.EndObject)
                            {
                                throw new ArgumentException("Expected token '}' not found.");
                            }

                            // read EndObject token
                            reader.Read();
                        }
                        else
                        {
                            // deserialize the inner object
                            attributeValue = serializer.Deserialize(reader);
                        }
                    }
                    else if (reader.TokenType == JsonToken.StartArray)
                    {
                        attributeValue = InternalReadJsonArray(reader, serializer);
                        //reader.Read(); // move to first item
                        //IList<object> array = new List<object>();
                        //do
                        //{
                        //    object inner = InternalReadJson(reader, serializer);
                        //    array.Add(inner);
                        //    reader.Read(); // move to next item
                        //} while (reader.TokenType != JsonToken.EndArray);
                        //attributeValue = array;
                    }
                    else
                    {
                        attributeValue = reader.Value;
                        reader.Read();
                    }

                    if (!attributesTable.Exists(attributeName))
                    {
                        attributesTable.Add(attributeName, attributeValue);
                    }
                }

                reader.SkipComments();
            }

            // TODO: refactor to remove check when reading TopoJSON
            if (reader.TokenType != JsonToken.EndObject)
            {
                throw new ArgumentException("Expected token '}' not found.");
            }

            return(attributesTable);
        }
Beispiel #29
0
        private void TestWriteZMValuesShapeFile(bool testM)
        {
            var points = new Coordinate[3];

            points[0] = new Coordinate(0, 0);
            points[1] = new Coordinate(1, 0);
            points[2] = new Coordinate(1, 1);

            var csFactory = DotSpatialAffineCoordinateSequenceFactory.Instance;
            var sequence  = csFactory.Create(3, Ordinates.XYZM);

            for (int i = 0; i < 3; i++)
            {
                sequence.SetOrdinate(i, Ordinate.X, points[i].X);
                sequence.SetOrdinate(i, Ordinate.Y, points[i].Y);
                sequence.SetOrdinate(i, Ordinate.Z, 1 + i);
                if (testM)
                {
                    sequence.SetOrdinate(i, Ordinate.M, 11 + i);
                }
            }
            var lineString = Factory.CreateLineString(sequence);

            var attributes = new AttributesTable();

            attributes.Add("FOO", "Trond");

            var feature  = new Feature(Factory.CreateMultiLineString(new[] { lineString }), attributes);
            var features = new Feature[1];

            features[0] = feature;

            var shpWriter = new ShapefileDataWriter("ZMtest", Factory)
            {
                Header = ShapefileDataWriter.GetHeader(features[0], features.Length)
            };

            shpWriter.Write(features);

            // Now let's read the file and verify that we got Z and M back
            var factory = new GeometryFactory(DotSpatialAffineCoordinateSequenceFactory.Instance);

            using (var reader = new ShapefileDataReader("ZMtest", factory))
            {
                reader.Read();
                var geom = reader.Geometry;

                for (int i = 0; i < 3; i++)
                {
                    var c = geom.Coordinates[i];
                    Assert.AreEqual(i + 1, c.Z);
                }

                if (testM)
                {
                    sequence = ((ILineString)geom).CoordinateSequence;
                    for (int i = 0; i < 3; i++)
                    {
                        Assert.AreEqual(sequence.GetOrdinate(i, Ordinate.M), 11 + i);
                    }
                }

                // Run a simple attribute test too
                string v = reader.GetString(1);
                Assert.AreEqual(v, "Trond");
            }
        }
Beispiel #30
0
        /// <summary>
        /// Convert the given OSM relation to a GeoJSON line feature.
        /// </summary>
        /// <param name="Relation">An OSM relation.</param>
        public static Feature ToGeoJSON(this Relation Relation)
        {
            // {
            //     "type":  "Feature",
            //     "id":    "way/305352912",
            //     "properties": {
            //         "@id":         "way/305352912",
            //     },
            //     "geometry": {
            //         "type":        "LineString",
            //         "coordinates": [ [ 11.6023278, 50.8926376 ], [ 11.5054540, 50.7980146 ], [ 11.6023278, 50.8926376 ] ]
            //     }
            // }

            // https://wiki.openstreetmap.org/wiki/Overpass_turbo/Polygon_Features

            // 1) Combine all ways into a single big list of geo coordinate (it's a puzzle! Some ways must be reversed in order to find matches!)
            // 2) Check if first geo coordinate is the same as the last
            // 3) If yes => polygon (exceptions see wiki link)


            // Relation.Ways.Select(Way => new JArray(Way.Nodes.Select(Node => new JArray(Node.Longitude, Node.Latitude))))

            try
            {
                var RemainingGeoFeatures = Relation.Members.Where(m => m.Way != null).Select(m => new GeoFeature(m.Way.Nodes.Select(Node => new Coordinate(Node.Longitude, Node.Latitude)))).ToList();
                var ResultList           = new List <GeoFeature>();

                bool       Found             = false;
                GeoFeature CurrentGeoFeature = new GeoFeature();

                //if (Relation.Tags["type"].ToString() != "multipolygon")
                //{
                //    Console.WriteLine("Broken OSM multipolygon relation found!");
                //}

                while (RemainingGeoFeatures.Count > 0)
                {
                    CurrentGeoFeature = RemainingGeoFeatures.RemoveAndReturnFirst();


                    // The current geo feature is closed -> a polygon!
                    if ((!Relation.Tags.ContainsKey("type") || Relation.Tags["type"].ToString() != "route") &&
                        CurrentGeoFeature.GeoCoordinates.First() == CurrentGeoFeature.GeoCoordinates.Last())
                    {
                        CurrentGeoFeature.Type = OgcGeometryType.Polygon;
                        ResultList.Add(CurrentGeoFeature);
                    }

                    // The current geo feature is not closed
                    // Try to extend the geo feature by finding fitting other geo features
                    else
                    {
                        do
                        {
                            Found = false;

                            foreach (var AdditionalPath in RemainingGeoFeatures)
                            {
                                if (AdditionalPath.GeoCoordinates.First() == CurrentGeoFeature.GeoCoordinates.Last())
                                {
                                    RemainingGeoFeatures.Remove(AdditionalPath);
                                    // Skip first GeoCoordinate as it is redundant!
                                    CurrentGeoFeature.GeoCoordinates.AddRange(AdditionalPath.GeoCoordinates);//.Skip(1));
                                    Found = true;
                                    break;
                                }

                                else if (AdditionalPath.GeoCoordinates.Last() == CurrentGeoFeature.GeoCoordinates.Last())
                                {
                                    RemainingGeoFeatures.Remove(AdditionalPath);
                                    // Skip first GeoCoordinate as it is redundant!
                                    CurrentGeoFeature.GeoCoordinates.AddRange(AdditionalPath.GeoCoordinates.ReverseAndReturn());//.Skip(1));
                                    Found = true;
                                    break;
                                }

                                else if (AdditionalPath.GeoCoordinates.First() == CurrentGeoFeature.GeoCoordinates.First())
                                {
                                    RemainingGeoFeatures.Remove(AdditionalPath);
                                    CurrentGeoFeature.GeoCoordinates.Reverse();
                                    // Skip first GeoCoordinate as it is redundant!
                                    CurrentGeoFeature.GeoCoordinates.AddRange(AdditionalPath.GeoCoordinates);//.Skip(1));
                                    Found = true;
                                    break;
                                }

                                else if (AdditionalPath.GeoCoordinates.Last() == CurrentGeoFeature.GeoCoordinates.First())
                                {
                                    RemainingGeoFeatures.Remove(AdditionalPath);
                                    CurrentGeoFeature.GeoCoordinates.Reverse();
                                    // Skip first GeoCoordinate as it is redundant!
                                    CurrentGeoFeature.GeoCoordinates.AddRange(AdditionalPath.GeoCoordinates.ReverseAndReturn());//.Skip(1));
                                    Found = true;
                                    break;
                                }
                            }
                        } while (RemainingGeoFeatures.Count > 0 && Found);

                        // Is route
                        bool isRoute = Relation.Tags.Any() && Relation.Tags["type"].ToString() == "route";
                        CurrentGeoFeature.Type = (!isRoute &&
                                                  CurrentGeoFeature.GeoCoordinates.First() == CurrentGeoFeature.GeoCoordinates.Last())
                                                      ? OgcGeometryType.Polygon
                                                      : OgcGeometryType.LineString;

                        ResultList.Add(CurrentGeoFeature);
                    }
                }


                Geometry geometry = null;
                if (ResultList.Count == 0)
                {
                    return(null);
                }

                if (ResultList.Count == 1)
                {
                    var ring = new LineString(CurrentGeoFeature.GeoCoordinates.ToArray());
                    if (ResultList.First().Type == OgcGeometryType.Polygon)
                    {
                        geometry = new Polygon(new LinearRing(ring.Coordinates));
                    }
                    else
                    {
                        geometry = ring;
                    }
                }
                else
                {
                    var multiRing = ResultList.Select(g => new LineString(g.GeoCoordinates.ToArray()));

                    if (ResultList.First().Type == OgcGeometryType.Polygon)
                    {
                        multiRing = multiRing.Where(r => r.NumPoints >= 4).ToList();
                        geometry  = new Polygon(new LinearRing(multiRing.First().Coordinates), multiRing.Skip(1).Select(r => new LinearRing(r.Coordinates)).ToArray());
                    }
                    else
                    {
                        geometry = new MultiLineString(multiRing.ToArray());
                    }
                }

                var             id    = string.Concat("relation/", Relation.Id);
                AttributesTable props = new AttributesTable();
                props.Add("osmid", id);
                foreach (var tag in Relation.Tags)
                {
                    props.Add(tag.Key, tag.Value);
                }
                var feature = new Feature(geometry, props);

                return(feature);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("OSM to GeoJSON error for relation");
                return(null);
            }
        }
        /// <summary>
        /// Convert shape-file to geojson-file stream
        /// </summary>
        /// <param name="shapeFilePath"></param>
        public static Stream ConvertToGeoJsonStream(string shapeFilePath)
        {
            var factory = new GeometryFactory();
            //Create a feature collection
            var featureCollection = new FeatureCollection();

            //Try to get crs from .prj file
            var crs = TryToGetCrs(shapeFilePath);

            //Set crs if we found it
            if (crs != CoordinateSystemId.None)
            {
                featureCollection.CRS = new NamedCRS(new CoordinateSystem(crs).Id.EpsgCode());
            }

            using (var shapeFileDataReader = new ShapefileDataReader(shapeFilePath, factory))
            {
                //Get shape file dbase header
                var header = shapeFileDataReader.DbaseHeader;

                //Loop throw all geometries
                while (shapeFileDataReader.Read())
                {
                    var attributesTable = new AttributesTable();
                    var geometry        = (Geometry)shapeFileDataReader.Geometry;

                    //Get header fields
                    for (var i = 0; i < header.NumFields; i++)
                    {
                        var fldDescriptor = header.Fields[i];
                        attributesTable.AddAttribute(fldDescriptor.Name, shapeFileDataReader.GetValue(i));
                    }

                    //Create feature using geometry and attributes
                    var feature = new Feature()
                    {
                        Geometry   = geometry,
                        Attributes = attributesTable
                    };

                    //Add feature to collection
                    featureCollection.Features.Add(feature);
                }

                //Close and free up any resources
                shapeFileDataReader.Close();
            }

            // Create a stream to write to.
            var outputStream   = new MemoryStream();
            var sw             = new StreamWriter(outputStream);
            var jsonSerializer = new GeoJsonSerializer(factory);

            //Serialize feature collection to json
            jsonSerializer.Serialize(sw, featureCollection);

            //Flush stream writer and reset stream position
            sw.Flush();
            outputStream.Position = 0;
            return(outputStream);
        }
Beispiel #32
0
        public static void Compress(string shapeFilePath, int gridFieldIndex, string encoding = null, string outputShapeFileName = "")
        {
            var factory = new GeometryFactory();

            if (!File.Exists(shapeFilePath))
            {
                Console.WriteLine("文件不存在。");
                return;
            }
            string filePath            = Path.GetDirectoryName(shapeFilePath);
            string outputShapeFilePath = "";
            var    outputFilePath      = Path.ChangeExtension(shapeFilePath, ".text");

            if (!string.IsNullOrEmpty(outputShapeFileName))
            {
                outputShapeFilePath = Path.Combine(filePath, outputShapeFileName);
                outputFilePath      = Path.ChangeExtension(outputShapeFileName, ".txt");
            }

            var      nFile        = new FileStream(outputFilePath, FileMode.Create);
            Encoding fileEncoding = Encoding.UTF8;

            nFile.Position = nFile.Length;

            var fts = new List <IFeature>();
            ShapefileDataReader reader;

            if (string.IsNullOrEmpty(encoding))
            {
                reader = new ShapefileDataReader(shapeFilePath, factory);
            }
            else
            {
                Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                reader = new ShapefileDataReader(shapeFilePath, factory, Encoding.GetEncoding(encoding));
            }

            using (reader)
            {
                var  dict        = new Dictionary <string, IGeometry>();
                int  count       = 0;
                long recordCount = 0;
                try {
                    while (reader.Read())
                    {
                        recordCount++;
                        var gridId = reader.GetString(gridFieldIndex);
                        if (dict.ContainsKey(gridId))
                        {
                            continue;
                        }

                        count++;
                        if (count % 1000 == 0)
                        {
                            Console.WriteLine($"{count}");
                            nFile.Flush();
                        }


                        dict.Add(gridId, reader.Geometry);
                        string text  = $"{gridId},{reader.Geometry.ToString()}\n";
                        var    bytes = fileEncoding.GetBytes(text);

                        nFile.Write(bytes, 0, bytes.Length);

                        var attrs = new AttributesTable();
                        attrs.Add("GRIDID", gridId);
                        var feature = new Feature(reader.Geometry, attrs);
                        fts.Add(feature);
                    }
                }
                catch (Exception)
                {
                    Console.WriteLine($"第{recordCount}条记录读取错误!");
                    throw;
                }
                Console.WriteLine($"共处理{reader.RecordCount}条数据,压缩生成{count}条数据");


                nFile.Close();
            };


            if (!string.IsNullOrEmpty(outputShapeFilePath))
            {
                var writer = new ShapefileDataWriter(outputShapeFilePath, factory);
                writer.Header = ShapefileDataWriter.GetHeader(fts[0], fts.Count);
                writer.Write(fts);
            }

            Console.WriteLine("成功结束!");
        }