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, GeoJsonPolygonCoordinates <TCoordinates> value)
        {
            var bsonWriter = context.Writer;

            bsonWriter.WriteStartArray();
            context.SerializeWithChildContext(_linearRingCoordinatesSerializer, value.Exterior);
            foreach (var hole in value.Holes)
            {
                context.SerializeWithChildContext(_linearRingCoordinatesSerializer, hole);
            }
            bsonWriter.WriteEndArray();
        }
Beispiel #2
0
        // protected methods
        /// <summary>
        /// Deserializes a value.
        /// </summary>
        /// <param name="context">The deserialization context.</param>
        /// <param name="args">The deserialization args.</param>
        /// <returns>The value.</returns>
        protected override GeoJsonPolygon <TCoordinates> DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var geoJsonObjectArgs = new GeoJsonObjectArgs <TCoordinates>();
            GeoJsonPolygonCoordinates <TCoordinates> coordinates = null;

            _helper.DeserializeMembers(context, (elementName, flag) =>
            {
                switch (flag)
                {
                case Flags.Coordinates: coordinates = DeserializeCoordinates(context); break;

                default: _helper.DeserializeBaseMember(context, elementName, flag, geoJsonObjectArgs); break;
                }
            });

            return(new GeoJsonPolygon <TCoordinates>(geoJsonObjectArgs, coordinates));
        }
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();
        }
Beispiel #5
0
 private void SerializeCoordinates(BsonSerializationContext context, GeoJsonPolygonCoordinates <TCoordinates> coordinates)
 {
     context.Writer.WriteName("coordinates");
     _coordinatesSerializer.Serialize(context, coordinates);
 }
 private void SerializeCoordinates(BsonWriter bsonWriter, GeoJsonPolygonCoordinates <TCoordinates> coordinates)
 {
     bsonWriter.WriteName("coordinates");
     _coordinatesSerializer.Serialize(bsonWriter, typeof(GeoJsonPolygonCoordinates <TCoordinates>), coordinates, null);
 }
        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 #8
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;

        }
        public static GeoJsonPoint <GeoJson2DGeographicCoordinates> GetPolygonCentroid(GeoJsonPolygonCoordinates <GeoJson2DGeographicCoordinates> poly)
        {
            double accumulatedArea = 0.0d;
            double centerX         = 0.0d;
            double centerY         = 0.0d;

            if (poly == null)
            {
                return(null);
            }

            var coords = poly.Exterior.Positions.ToList();

            for (int i = 0, j = coords.Count - 1; i < coords.Count; j = i++)
            {
                double temp = coords[i].Longitude * coords[j].Latitude - coords[j].Longitude * coords[i].Latitude;
                accumulatedArea += temp;
                centerX         += (coords[i].Longitude + coords[j].Longitude) * temp;
                centerY         += (coords[i].Latitude + coords[j].Latitude) * temp;
            }

            if (Math.Abs(accumulatedArea) < 1E-7f)
            {
                return(null);
            }

            accumulatedArea *= 3f;

            return(GeoJson.Point(GeoJson.Geographic(centerX / accumulatedArea, centerY / accumulatedArea)));
        }