public ActionResult Get(string loc1, string loc2, string profile = "", bool instructions = false,
                                string lang = "en")
        {
            try
            {
                var from  = Utility.ParseCoordinate(loc1);
                var to    = Utility.ParseCoordinate(loc2);
                var route = RouterInstance.Calculate(profile, from, to);

                route.PruneColours();

                GeoJsonFeatureCollection instr = null;
                if (instructions)
                {
                    instr = RouterInstance.GenerateInstructions(route, lang);
                }

                RequestLogger.LogRequest(from, to);
                return(Json(new RouteResponse(route, instr)));
            }
            catch (ResolveException e)
            {
                Log.Error(e, "Getting a route failed (not found)");
                return(NotFound(e.Message));
            }
            catch (Exception e)
            {
                Log.Error(e, "Getting a route failed (other error)");
                return(BadRequest(e.Message));
            }
        }
        /// <summary>
        /// Returns an instance of <see cref="IRectangle"/> representing the bounding box of the specified GeoJSON <paramref name="collection"/>.
        /// </summary>
        /// <param name="collection">The feature collection.</param>
        /// <returns>An instance of <see cref="IRectangle"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="collection"/> is <c>null</c>.</exception>
        /// <exception cref="InvalidOperationException"><paramref name="collection"/> is empty.</exception>
        public static IRectangle GetBoundingBox(GeoJsonFeatureCollection collection)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }
            if (collection.Features.Count == 0)
            {
                throw new InvalidOperationException(nameof(collection));
            }

            List <IPoint> points = new List <IPoint>();

            foreach (GeoJsonFeature feature in collection.Features)
            {
                IRectangle bbox = GetBoundingBox(feature);

                if (bbox != null)
                {
                    points.Add(bbox.SouthWest);
                    points.Add(bbox.NorthEast);
                }
            }

            return(points.Count == 0 ? null : MapsUtils.GetBoundingBox(points));
        }
Example #3
0
        private void TestRoundTrip <TCoordinates>(string expected, GeoJsonFeatureCollection <TCoordinates> featureCollection) where TCoordinates : GeoJsonCoordinates
        {
            var json = featureCollection.ToJson();

            Assert.AreEqual(expected, json);

            var rehydrated = BsonSerializer.Deserialize <GeoJsonFeatureCollection <TCoordinates> >(json);

            Assert.AreEqual(expected, rehydrated.ToJson());
        }
        /// <summary>
        /// Parses the specified <paramref name="json"/> object into an instance deriving from <see cref="GeoJsonObject"/>.
        ///
        /// As the GeoJSON format specified the type of a
        /// </summary>
        /// <param name="json">The JSON object.</param>
        /// <returns>An instance that derives from <see cref="GeoJsonObject"/>.</returns>
        private static GeoJsonObject Parse(JObject json)
        {
            if (json == null)
            {
                return(null);
            }

            // Get the value of the "type" property
            string type = json.GetString("type");

            if (string.IsNullOrWhiteSpace(type))
            {
                throw new GeoJsonParseException("The JSON object doesn't specify a type", json);
            }

            // Parse the type into an enum
            if (EnumUtils.TryParseEnum(type, out GeoJsonType result) == false)
            {
                throw new GeoJsonParseException($"Unknown type {type}", json);
            }

            switch (result)
            {
            case GeoJsonType.Feature:
                return(GeoJsonFeature.Parse(json));

            case GeoJsonType.FeatureCollection:
                return(GeoJsonFeatureCollection.Parse(json));

            case GeoJsonType.Point:
                return(GeoJsonPoint.Parse(json));

            case GeoJsonType.LineString:
                return(GeoJsonLineString.Parse(json));

            case GeoJsonType.Polygon:
                return(GeoJsonPolygon.Parse(json));

            case GeoJsonType.MultiPoint:
                return(GeoJsonMultiPoint.Parse(json));

            //case GeoJsonType.MultiLineString:
            //    return GeoJsonMultiLineString.Parse(obj);

            case GeoJsonType.MultiPolygon:
                return(GeoJsonMultiPolygon.Parse(json));

            case GeoJsonType.GeometryCollection:
                return(GeoJsonGeometryCollection.Parse(json));

            default:
                throw new GeoJsonParseException($"Unknown type {type}", json);
            }
        }
        public virtual GeoJsonFeatureCollection ConvertFolder(KmlFolder folder, IStyleProvider provider)
        {
            GeoJsonFeatureCollection collection = new GeoJsonFeatureCollection();

            foreach (KmlFeature feature in folder.Features)
            {
                ConvertFolder(folder, collection, feature, provider);
            }

            return(collection);
        }
Example #6
0
        public ActionResult GetAtmSupermarketInRadius(int radius)
        {
            var atmList = new List <GeoJsonModel>();

            using (var conn = new NpgsqlConnection())
            {
                conn.ConnectionString = "PORT=5432;TIMEOUT=15;POOLING=True;MINPOOLSIZE=1;MAXPOOLSIZE=20;COMMANDTIMEOUT=20;DATABASE=pdtgis;HOST=localhost;USER ID=postgres;PASSWORD=mato777bleskino";
                conn.Open();

                using (var cmd = new NpgsqlCommand())
                {
                    cmd.Connection  = conn;
                    cmd.CommandText = string.Format("SELECT x.operator,y.name,ST_AsGeoJson(x.way), ST_AsGeoJson(y.way), ST_Distance(Geography(x.way),Geography(y.way)) from planet_osm_point x, planet_osm_point y where(x.amenity = \'atm\' AND x.operator IS NOT NULL) AND(y.shop = \'supermarket\') AND ST_DWithin(Geography(x.way), Geography(y.way), {0})", radius);
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var atm  = new GeoJsonModel();
                            var shop = new GeoJsonModel();
                            atm.type                    = "Feature";
                            atm.properties              = new GeoJsonProperties();
                            atm.properties.name         = !reader.IsDBNull(0) ? reader.GetString(0) : String.Empty;
                            atm.properties.title        = !reader.IsDBNull(0) ? reader.GetString(0) : String.Empty;
                            atm.properties.description  = !reader.IsDBNull(4) ? reader.GetDouble(4).ToString() : String.Empty;
                            atm.properties.MarkerSymbol = "bank";
                            atm.properties.MarkerColor  = "#FF0000";
                            atm.geometry                = JsonConvert.DeserializeObject <GeoJsonGeometry>(reader.GetString(2));
                            atmList.Add(atm);

                            shop.type                    = "Feature";
                            shop.properties              = new GeoJsonProperties();
                            shop.properties.name         = !reader.IsDBNull(1) ? reader.GetString(1) : String.Empty;
                            shop.properties.title        = !reader.IsDBNull(1) ? reader.GetString(1) : String.Empty;
                            shop.properties.description  = !reader.IsDBNull(4) ? reader.GetDouble(4).ToString() : String.Empty;
                            shop.properties.MarkerSymbol = "shop";
                            shop.properties.MarkerColor  = "#00FF00";
                            shop.geometry                = JsonConvert.DeserializeObject <GeoJsonGeometry>(reader.GetString(3));
                            atmList.Add(shop);
                        }
                    }
                }
            }

            var geoJsonFeatures = new GeoJsonFeatureCollection();

            geoJsonFeatures.type     = "FeatureCollection";
            geoJsonFeatures.features = atmList;

            return(new JsonDotNetResult(geoJsonFeatures));
        }
Example #7
0
        /// <inheritdoc />
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.Null)
            {
                return(null);
            }
            if (reader.TokenType != JsonToken.StartObject)
            {
                return(null);
            }

            JObject obj = JObject.Load(reader);

            string type = obj.Value <string>("type");

            switch (type?.ToLower())
            {
            case "feature":
                return(GeoJsonFeature.Parse(obj));

            case "featurecollection":
                return(GeoJsonFeatureCollection.Parse(obj));

            case "point":
                return(GeoJsonPoint.Parse(obj));

            case "multipoint":
                return(GeoJsonMultiPoint.Parse(obj));

            case "linestring":
                return(GeoJsonLineString.Parse(obj));

            case "multilinestring":
                return(GeoJsonMultiLineString.Parse(obj));

            case "polygon":
                return(GeoJsonPolygon.Parse(obj));

            case "multipolygon":
                return(GeoJsonMultiPolygon.Parse(obj));

            default:
                if (objectType == typeof(GeoJsonProperties))
                {
                    return(ReadJsonProperties(reader));
                }
                throw new GeoJsonParseException($"Unknown shape: {type}", obj);
            }
        }
        protected virtual void ConvertFolder(KmlFolder folder, GeoJsonFeatureCollection collection, KmlFeature feature, IStyleProvider provider)
        {
            switch (feature)
            {
            case KmlPlacemark placemark:

                collection.Add(ConvertPlacemark(placemark, provider));

                break;

            case KmlDocument document:
            // Why would you have a document in a folder? (although it seems legal according to the specification)

            case KmlFolder childFolder:
            // Why would you have folder in another folder? (although it seems legal according to the specification)

            default:
                throw new KmlException("Unsupported feature " + feature.GetType());
            }
        }
Example #9
0
        public ActionResult GetShopsAll()
        {
            var shopList = new List <GeoJsonModel>();

            using (var conn = new NpgsqlConnection())
            {
                conn.ConnectionString = "PORT=5432;TIMEOUT=15;POOLING=True;MINPOOLSIZE=1;MAXPOOLSIZE=20;COMMANDTIMEOUT=20;DATABASE=pdtgis;HOST=localhost;USER ID=postgres;PASSWORD=mato777bleskino";
                conn.Open();

                using (var cmd = new NpgsqlCommand())
                {
                    cmd.Connection  = conn;
                    cmd.CommandText =
                        "SELECT name, ST_AsGeoJson(way) FROM planet_osm_point WHERE shop = \'supermarket\' AND name IS NOT NULL";
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var shop = new GeoJsonModel();
                            shop.type                    = "Feature";
                            shop.properties              = new GeoJsonProperties();
                            shop.properties.name         = !reader.IsDBNull(0) ? reader.GetString(0) : String.Empty;
                            shop.properties.title        = !reader.IsDBNull(0) ? reader.GetString(0) : String.Empty;;
                            shop.properties.MarkerSymbol = "shop";
                            shop.properties.MarkerColor  = "#EB42DF";
                            shop.properties.MarkerSize   = "small";
                            shop.geometry                = JsonConvert.DeserializeObject <GeoJsonGeometry>(reader.GetString(1));
                            shopList.Add(shop);
                        }
                    }
                }
            }

            var geoJsonFeatures = new GeoJsonFeatureCollection();

            geoJsonFeatures.type     = "FeatureCollection";
            geoJsonFeatures.features = shopList;

            return(new JsonDotNetResult(geoJsonFeatures));
        }
Example #10
0
        public ActionResult GetSporAll()
        {
            var sporList = new List <GeoJsonModel>();

            using (var conn = new NpgsqlConnection())
            {
                conn.ConnectionString = "PORT=5432;TIMEOUT=15;POOLING=True;MINPOOLSIZE=1;MAXPOOLSIZE=20;COMMANDTIMEOUT=20;DATABASE=pdtgis;HOST=localhost;USER ID=postgres;PASSWORD=mato777bleskino";
                conn.Open();

                using (var cmd = new NpgsqlCommand())
                {
                    cmd.Connection  = conn;
                    cmd.CommandText =
                        "SELECT operator, ST_AsGeoJson(way) FROM planet_osm_point WHERE amenity='atm' AND lower(operator)LIKE '%sporite%'";
                    using (var reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            var spor = new GeoJsonModel();
                            spor.type                    = "Feature";
                            spor.properties              = new GeoJsonProperties();
                            spor.properties.name         = !reader.IsDBNull(0) ? reader.GetString(0) : String.Empty;
                            spor.properties.title        = !reader.IsDBNull(0) ? reader.GetString(0) : String.Empty;;
                            spor.properties.MarkerSymbol = "bank";
                            spor.properties.MarkerColor  = "#47ED87";
                            spor.properties.MarkerSize   = "small";
                            spor.geometry                = JsonConvert.DeserializeObject <GeoJsonGeometry>(reader.GetString(1));
                            sporList.Add(spor);
                        }
                    }
                }
            }

            var geoJsonFeatures = new GeoJsonFeatureCollection();

            geoJsonFeatures.type     = "FeatureCollection";
            geoJsonFeatures.features = sporList;

            return(new JsonDotNetResult(geoJsonFeatures));
        }
        public ActionResult Get(string loc1, string loc2, string profile = "", bool genInstructions = true, string lang = "en")
        {
            try {
                Coordinate from  = Utility.ParseCoordinate(loc1);
                Coordinate to    = Utility.ParseCoordinate(loc2);
                Route      route = RouterInstance.Calculate(profile, from, to);
                GeoJsonFeatureCollection instructions = null;
                if (genInstructions)
                {
                    try {
                        instructions = RouterInstance.GenerateInstructions(route, lang);
                    } catch {}
                }

                RequestLogger.LogRequest(from, to);
                return(Json(new RouteResponse(route, instructions)));
            } catch (ResolveException re) {
                return(NotFound(re.Message));
            } catch (Exception e) {
                return(BadRequest(e.Message));
            }
        }
        protected virtual GeoJsonFeatureCollection[] ConvertDocument(KmlDocument document, IStyleProvider provider)
        {
            // Use the style provider of the document if not explicitly specified
            provider = provider ?? document.StyleSelectors;

            // Initialize a new list of collections
            List <GeoJsonFeatureCollection> collections = new List <GeoJsonFeatureCollection>();

            if (document.Features.Any(x => x is KmlFolder))
            {
                GeoJsonFeatureCollection defaultCollection = null;

                foreach (KmlFeature feature in document.Features)
                {
                    switch (feature)
                    {
                    case KmlDocument _:
                        throw new KmlException("Weird place for a <Document>, huh?");

                    case KmlFolder folder:
                        collections.Add(ConvertFolder(folder, provider));
                        break;

                    case KmlPlacemark placemark:

                        // Make sure the default feature collection is initialized
                        if (defaultCollection == null)
                        {
                            collections.Add(defaultCollection = new GeoJsonFeatureCollection());
                        }

                        // As the placemark isn't located inside a folder, we should append it to a "default" feature collection"
                        defaultCollection.Add(ConvertPlacemark(placemark, provider));

                        break;

                    default:
                        throw new KmlException("Unsupported feature " + feature.GetType());
                    }
                }
            }
            else
            {
                GeoJsonFeatureCollection features = new GeoJsonFeatureCollection();

                foreach (KmlFeature feature in document.Features)
                {
                    switch (feature)
                    {
                    case KmlDocument _:
                        throw new KmlException("Weird place for a <Document>, huh?");

                    case KmlPlacemark placemark:
                        features.Add(ConvertPlacemark(placemark, provider));
                        break;

                    default:
                        throw new KmlException("Unsupported feature " + feature.GetType());
                    }
                }

                collections.Add(features);
            }

            return(collections.ToArray());
        }
 /// <summary>
 /// Serializes a value.
 /// </summary>
 /// <param name="context">The serialization context.</param>
 /// <param name="value">The value.</param>
 protected override void SerializeValue(BsonSerializationContext context, GeoJsonFeatureCollection <TCoordinates> value)
 {
     _helper.SerializeMembers(context, value, SerializeDerivedMembers);
 }
 private void SerializeDerivedMembers(BsonSerializationContext context, GeoJsonFeatureCollection <TCoordinates> value)
 {
     SerializeFeatures(context, value.Features);
 }