Beispiel #1
0
        /// <summary>
        /// Serializes a value.
        /// </summary>
        /// <param name="context">The serialization context.</param>
        /// <param name="value">The value.</param>
        protected override void SerializeValue(BsonSerializationContext context, GeoJsonLinearRingCoordinates <TCoordinates> value)
        {
            var bsonWriter = context.Writer;

            bsonWriter.WriteStartArray();
            foreach (var position in value.Positions)
            {
                context.SerializeWithChildContext(_coordinatesSerializer, position);
            }
            bsonWriter.WriteEndArray();
        }
Beispiel #2
0
        static public IRing ToRing <T>(this GeoJsonLinearRingCoordinates <T> linearRing) where T : GeoJsonCoordinates
        {
            var ring = new Ring();

            foreach (var position in linearRing.Positions)
            {
                var values = position.Values;
                ring.AddPoint(new Point(values[0], values[1]));
            }

            return(ring);
        }
Beispiel #3
0
        internal static PartnerMongoDb ToPartnerMongoDb(this Partner partner)
        {
            var polygonsCoodinates = new List <GeoJsonPolygonCoordinates <GeoJson2DGeographicCoordinates> >();

            foreach (var multipolygon in partner.CoverageArea.Coordinates)
            {
                foreach (var polygon in multipolygon)
                {
                    var points = new List <GeoJson2DGeographicCoordinates>();
                    foreach (var coordinates in polygon)
                    {
                        var coordinatesArray = coordinates.ToArray();
                        var longitude        = coordinatesArray[0];
                        var latitude         = coordinatesArray[1];

                        var point = new GeoJson2DGeographicCoordinates(longitude, latitude);
                        points.Add(point);
                    }

                    var linearRings        = new GeoJsonLinearRingCoordinates <GeoJson2DGeographicCoordinates>(points);
                    var polygonCoordinates = new GeoJsonPolygonCoordinates <GeoJson2DGeographicCoordinates>(linearRings);
                    polygonsCoodinates.Add(polygonCoordinates);
                }
            }

            var coverageArea       = GeoJson.MultiPolygon(polygonsCoodinates.ToArray());
            var addressCoordinates = partner.Address.Coordinates.ToArray();
            var address            = GeoJson.Point(new GeoJson2DGeographicCoordinates(addressCoordinates[0], addressCoordinates[1]));

            var partnerDb = new PartnerMongoDb()
            {
                Document     = partner.Document,
                OwnerName    = partner.OwnerName,
                TradingName  = partner.TradingName,
                CoverageArea = coverageArea,
                Address      = address
            };

            return(partnerDb);
        }
        public MongoDbFeatureCursor(MongoDbFeatureClass fc, IQueryFilter filter)
            : base(fc.SpatialReference, filter.FeatureSpatialReference)
        {
            IFindFluent <Json.GeometryDocument, Json.GeometryDocument> findFluent = null;

            int bestLevel = -1;

            if (fc.GeneralizationLevel >= 0 && fc.GeometryType != Framework.Geometry.geometryType.Point && filter.MapScale > 0)
            {
                var resolution = filter.MapScale / _dpm;
                bestLevel = resolution.BestResolutionLevel();
            }

            if (bestLevel >= 0)
            {
                bestLevel          = Math.Max(fc.GeneralizationLevel, bestLevel);
                _shapeFieldname    = $"_shapeGen{bestLevel}";
                _shapePropertyInfo = typeof(Json.GeometryDocument).GetProperty($"ShapeGeneralized{bestLevel}");
                _isWkbShape        = true;
            }

            if (filter is ISpatialFilter)
            {
                ISpatialFilter sFilter = (ISpatialFilter)filter;
                var            env     = sFilter.Geometry.Envelope;

                env.minx = Math.Max(-180, env.minx);
                env.miny = Math.Max(-90, env.miny);
                env.maxx = Math.Min(180, env.maxx);
                env.maxy = Math.Min(90, env.maxy);

                GeoJson2DGeographicCoordinates   bottomleft  = new GeoJson2DGeographicCoordinates(env.minx, env.miny);
                GeoJson2DGeographicCoordinates   topleft     = new GeoJson2DGeographicCoordinates(env.minx, env.maxy);
                GeoJson2DGeographicCoordinates   topright    = new GeoJson2DGeographicCoordinates(env.maxx, env.maxy);
                GeoJson2DGeographicCoordinates   bottomright = new GeoJson2DGeographicCoordinates(env.maxx, env.miny);
                GeoJson2DGeographicCoordinates[] coord_array = new GeoJson2DGeographicCoordinates[] { bottomleft, topleft, topright, bottomright, bottomleft };
                GeoJsonLinearRingCoordinates <GeoJson2DGeographicCoordinates> ringcoord = new GeoJsonLinearRingCoordinates <GeoJson2DGeographicCoordinates>(coord_array);
                GeoJsonPolygonCoordinates <GeoJson2DGeographicCoordinates>    boxcoord  = new GeoJsonPolygonCoordinates <GeoJson2DGeographicCoordinates>(ringcoord);
                GeoJsonPolygon <GeoJson2DGeographicCoordinates> box = new GeoJsonPolygon <GeoJson2DGeographicCoordinates>(boxcoord);

                var bsonFilter =
                    fc.GeometryType == Framework.Geometry.geometryType.Point ?
                    Builders <Json.GeometryDocument> .Filter
                    .GeoIntersects(x => x.Shape, box) :
                    Builders <Json.GeometryDocument> .Filter
                    .GeoIntersects(x => x.Bounds, box);

                //.GeoWithinBox(x => x.Shape, env.minx, env.miny, env.maxx, env.maxy);

                var findOptions = new FindOptions()
                {
                    BatchSize = 10000
                };

                findFluent = fc.MongoCollection.Find(bsonFilter, options: findOptions);
            }
            else
            {
                findFluent = fc.MongoCollection.Find(_ => true);
                //filter.Limit = 1000;
            }

            if (filter.Limit > 0)
            {
                findFluent = findFluent.Limit(filter.Limit);
            }
            if (filter.BeginRecord > 1)
            {
                findFluent = findFluent.Skip(filter.BeginRecord - 1);
            }
            if (filter.SubFields != "*")
            {
                StringBuilder project = new StringBuilder();
                project.Append("{");
                foreach (var field in filter.SubFields.Split(' '))
                {
                    if (project.Length > 1)
                    {
                        project.Append(",");
                    }
                    if (field == "_id")
                    {
                        project.Append($"{field}:1");
                    }
                    else if (field == "_shape")
                    {
                        project.Append($"{_shapeFieldname}:1");
                    }
                    else
                    {
                        project.Append($"\"properties.{field}\":1");
                    }
                }
                project.Append("}");
                findFluent = findFluent.Project <Json.GeometryDocument>(project.ToString());
            }
            else
            {
                string project = String.Join(",", Enumerable.Range(0, 15).Select(i => $"{{_shapeGen{i}:0}}"));
                findFluent = findFluent.Project <Json.GeometryDocument>(project);
            }

            _cursor = findFluent.ToCursor();
        }
        public async Task<HttpResponseMessage> feature_mobile(string area, string subj, double SWlong, double SWlat, double NElong, double NElat)
        {



            // set connection string in web.config 
            _mongoClient = new MongoClient(ConfigurationManager.ConnectionStrings["MongoDBContext"].ConnectionString);
            _mongoDatabase = _mongoClient.GetDatabase(ConfigurationManager.AppSettings["civilgisDBname"]);
            var _max_row_count = Convert.ToInt16(ConfigurationManager.AppSettings["max_row_count_mobile"]);

            var table_name = area + "_" + subj;



            var _mongoCollection = _mongoDatabase.GetCollection<FeatureDoc>(table_name);


            if ((SWlong == 0) || (SWlat == 0) || (NElong == 0) || (NElat == 0))
            {
                SWlong = -117.963690;
                SWlat = 33.634180;
                NElong = -117.854780;
                NElat = 33.702970;
            }



            GeoJson2DGeographicCoordinates bottomleft = new GeoJson2DGeographicCoordinates(SWlong, SWlat);
            GeoJson2DGeographicCoordinates topleft = new GeoJson2DGeographicCoordinates(SWlong, NElat);
            GeoJson2DGeographicCoordinates topright = new GeoJson2DGeographicCoordinates(NElong, NElat);
            GeoJson2DGeographicCoordinates bottomright = new GeoJson2DGeographicCoordinates(NElong, SWlat);
            GeoJson2DGeographicCoordinates[] coord_array = new GeoJson2DGeographicCoordinates[] { bottomleft, topleft, topright, bottomright, bottomleft };
            GeoJsonLinearRingCoordinates<GeoJson2DGeographicCoordinates> ringcoord = new GeoJsonLinearRingCoordinates<GeoJson2DGeographicCoordinates>(coord_array);
            GeoJsonPolygonCoordinates<GeoJson2DGeographicCoordinates> boxcoord = new GeoJsonPolygonCoordinates<GeoJson2DGeographicCoordinates>(ringcoord);
            GeoJsonPolygon<GeoJson2DGeographicCoordinates> box = new GeoJsonPolygon<GeoJson2DGeographicCoordinates>(boxcoord);


            var filter = Builders<FeatureDoc>.Filter.GeoIntersects(x => x.geometry, box);



            long count = 0;
            string result = "";




            // count only, not select
            var temp = _mongoCollection.CountAsync(filter);
            temp.Wait();
            count = temp.Result;



            if ((count > 0) && (count < _max_row_count))
            {

                //var result = "{ \"type\": \"FeatureCollection\",\"features\": [";
                // result = @"{ ""type"": ""FeatureCollection"",""features"": [";
                result = @"{ ""type"": ""FeatureCollection"",""features"": ";



                // ------------------- use Find ----------------------------------------
                var _listBsonDoc = await _mongoCollection.Find(filter).ToListAsync();


                //--------------------- 1 ---------------------------------------------------
                var batch_json = _listBsonDoc.ToJson();

                //ObjectId("55c532cf21167708171b02a2") must change to  "55c532cf21167708171b02a2"
                // below use 1.1    1.2 is alternative


                //----------------- 1.1 ok ---------------------------
                batch_json = batch_json.Replace("ObjectId(\"", "\"");
                batch_json = batch_json.Replace("\")", "\"");
                //----------------------------------------------------

                /*
                        //--------------------1.2 ---------------------------------
                         batch_json = Regex.Replace(batch_json, "ObjectId", "");
                         batch_json = Regex.Replace(batch_json, @"(", "");
                         batch_json = Regex.Replace(batch_json, @")", "");
                        //----------------------------------------------------------
                 */

                result = result + batch_json;

                //----------------------------------- end 1 --------------------------------------







                // batch.toString() has bug, 
                // -------- temp fix the bug, there are one ][ occur between {1}][{2}, it should be {1},{2}, so ][ need to replace with , -------------
                result = result.Replace("][", ",");
                //================================================== bug fix {}][{} ====================================================================


                result = result + "}";

            }

            else if (count == 0)
            {
                // no record
                result = count.ToString();

            }
            else
            {
                // more than limit
                result = count.ToString();
            }



            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result, "text/plain");



            return response;

        }
Beispiel #6
0
        static public GeoJsonGeometry <T> ToGeoJsonGeometry <T>(this IGeometry geometry) where T : GeoJsonCoordinates
        {
            if (geometry is IPoint)
            {
                var point = (IPoint)geometry;

                return(new GeoJsonPoint <T>(
                           (T)Activator.CreateInstance(typeof(T), new object[] { point.X, point.Y })));
            }
            if (geometry is IPolyline)
            {
                var polyline = (IPolyline)geometry;

                if (polyline.PathCount == 1)
                {
                    var lineStringCoordinates = new GeoJsonLineStringCoordinates <T>(polyline[0].ToGeoJsonCoordinates <T>());
                    return(new GeoJsonLineString <T>(lineStringCoordinates));
                }
                if (polyline.PathCount > 1)
                {
                    var lineStrings = new List <GeoJsonLineStringCoordinates <T> >();
                    for (int p = 0, p_to = polyline.PathCount; p < p_to; p++)
                    {
                        lineStrings.Add(new GeoJsonLineStringCoordinates <T>(polyline[p].ToGeoJsonCoordinates <T>()));
                    }

                    var multiLineStrings = new GeoJsonMultiLineStringCoordinates <T>(lineStrings);
                    return(new GeoJsonMultiLineString <T>(multiLineStrings));
                }
            }
            if (geometry is IPolygon)
            {
                var polygon = (IPolygon)geometry;
                polygon.MakeValid();
                polygon.CloseAllRings();

                if (polygon.OuterRingCount == 1)
                {
                    var outerRing  = new GeoJsonLinearRingCoordinates <T>(polygon.OuterRings().First().ToGeoJsonCoordinates <T>());
                    var innerRings = new List <GeoJsonLinearRingCoordinates <T> >();
                    if (polygon.InnerRingCount > 0)
                    {
                        foreach (var hole in polygon.InnerRings(polygon.OuterRings().First()))
                        {
                            innerRings.Add(new GeoJsonLinearRingCoordinates <T>(hole.ToGeoJsonCoordinates <T>()));
                        }
                    }
                    var polygonCoordinates = innerRings.Count > 0 ? new GeoJsonPolygonCoordinates <T>(outerRing, innerRings) : new GeoJsonPolygonCoordinates <T>(outerRing);
                    return(new GeoJsonPolygon <T>(polygonCoordinates));
                }
                else if (polygon.OuterRingCount > 1)
                {
                    List <GeoJsonPolygonCoordinates <T> > polygonCoordinatesArray = new List <GeoJsonPolygonCoordinates <T> >();
                    foreach (var ring in polygon.OuterRings())
                    {
                        var outerRing  = new GeoJsonLinearRingCoordinates <T>(ring.ToGeoJsonCoordinates <T>());
                        var innerRings = new List <GeoJsonLinearRingCoordinates <T> >();
                        foreach (var hole in polygon.InnerRings(ring))
                        {
                            innerRings.Add(new GeoJsonLinearRingCoordinates <T>(hole.ToGeoJsonCoordinates <T>()));
                        }
                        polygonCoordinatesArray.Add(innerRings.Count > 0 ? new GeoJsonPolygonCoordinates <T>(outerRing, innerRings) : new GeoJsonPolygonCoordinates <T>(outerRing));
                    }

                    var multiPolygonCoordinates = new GeoJsonMultiPolygonCoordinates <T>(polygonCoordinatesArray);
                    return(new GeoJsonMultiPolygon <T>(multiPolygonCoordinates));
                }
            }

            return(null);
        }
Beispiel #7
0
        public async Task <HttpResponseMessage> feature2(string area, string subj, double SWlong, double SWlat, double NElong, double NElat)
        {
            // embeded connection string in code
            //_mongoClient = new MongoClient("mongodb://*****:*****@"{ ""type"": ""FeatureCollection"",""features"": [";
                result = @"{ ""type"": ""FeatureCollection"",""features"": ";

                //here use FindAsync() with cursor to iterate through each record.
                using (var cursor = await _mongoCollection.FindAsync(filter))
                {
                    while (await cursor.MoveNextAsync())
                    {
                        var batch = cursor.Current;



                        //--------------------- 1 ---------------------------------------------------
                        var batch_json = batch.ToJson();

                        //ObjectId("55c532cf21167708171b02a2") must change to  "55c532cf21167708171b02a2"
                        // below use 1.1    1.2 is alternative


                        //----------------- 1.1 ok ---------------------------
                        batch_json = batch_json.Replace("ObjectId(\"", "\"");
                        batch_json = batch_json.Replace("\")", "\"");
                        //----------------------------------------------------

                        /*
                         *      //--------------------1.2 ---------------------------------
                         *       batch_json = Regex.Replace(batch_json, "ObjectId", "");
                         *       batch_json = Regex.Replace(batch_json, @"(", "");
                         *       batch_json = Regex.Replace(batch_json, @")", "");
                         *      //----------------------------------------------------------
                         */

                        result = result + batch_json;

                        //----------------------------------- end 1 --------------------------------------
                    } // while await
                }     // using


                // batch.toString() has bug,
                // -------- temp fix the bug, there are one ][ occur between {1}][{2}, it should be {1},{2}, so ][ need to replace with , -------------
                result = result.Replace("][", ",");
                //================================================== bug fix {}][{} ====================================================================


                result = result + "}";
            }

            else if (count == 0)
            {
                // no record
                result = count.ToString();
            }
            else
            {
                // more than limit
                result = count.ToString();
            }



            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result, "text/plain");



            return(response);
        }
        public async Task<HttpResponseMessage> feature0(string area, string subj, double SWlong, double SWlat, double NElong, double NElat)
        {


            // embeded connection string in code
            //_mongoClient = new MongoClient("mongodb://*****:*****@"{ ""type"": ""FeatureCollection"",""features"": [";

                //here use FindAsync() with cursor to iterate through each record.
                using (var cursor = await _mongoCollection.FindAsync(filter))
                {
                    while (await cursor.MoveNextAsync())
                    {
                        var batch = cursor.Current;
                        foreach (var bsonDocument in batch)
                        {

                            //bsonDocument objectID field convert to non-string style, like ObjectId(""000000000000000000000000"")", must remove it or change it to "0"

                            ObjectId nullID = new ObjectId();
                            bsonDocument.id = nullID;

                            string rd = bsonDocument.ToJson();
                            string nullstr = @"ObjectId(""000000000000000000000000"")";
                            string rd1 = rd.Replace(nullstr, "0");


                            result = result + rd1 + ",";
                            count++;
                        }
                    }
                }// using

                // remove last ","
                result = result.Remove(result.Length - 1);

                result = result + "]}";

            }

            else if (count == 0)
            {
                // no record
                result = count.ToString();

            }
            else
            {
                // more than limit
                result = count.ToString();
            }



            HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, result, "text/plain");



            return response;

        }