public VehicleList(IEnumerable <VehicleModel> vehicles) { list = vehicles; //geo = new GeoVehicles(list); var model = new FeatureCollection(); int count = 1; foreach (var item in list) { item.index = count; var geom = new Point(new GeographicPosition(item.Latitude, item.Longitude)); var props = new Dictionary <string, object> { { "Make", item.Make }, { "Model", item.Model }, { "Year", item.Year }, { "Name", item.Name }, { "Address", item.Address }, { "City", item.City }, { "State", item.State }, { "Zip", item.Zip }, { "Phone", item.Phone }, { "Index", count }, { "Latitude", item.Latitude }, { "Longitude", item.Longitude } }; var feature = new GeoJSON.Net.Feature.Feature(geom, props, count.ToString()); model.Features.Add(feature); gs = new HtmlString(JsonConvert.SerializeObject(model)); count++; } }
public string GetCurrentValues() { var model = new FeatureCollection(); foreach (Claim c in claimHash.Values) { var geom = new Point(c.location); var props = new Dictionary <string, object> { { "cod", c.code }, { "dat", c.date }, { "qua", c.quality }, { "typ", c.type }, { "des", c.description }, { "sup", c.supply }, { "con", c.consumption }, { "cli", c.client } }; var feature = new GeoJSON.Net.Feature.Feature(geom, props); model.Features.Add(feature); } var claimjson = JsonConvert.SerializeObject(model); return(claimjson); }
/// <summary> /// Initializes a new instance of the <see cref="LcboStore"/> class. /// </summary> public LcboStore() { GeoJSON = new Feature(new Point(new Position())); Id = 0; Name = String.Empty; Volumes = new AlcoholVolumes(); }
public async Task <string> GetAllFarmersProfiles() { var geojsonndata = new FeatureCollection() { CRS = new GeoJSON.Net.CoordinateReferenceSystem.NamedCRS("urn:ogc:def:crs:OGC:1.3:CRS84") }; using (var _context = new NARIGPCoreContext()) { var farmers = _context.Transactions.ToList(); var farmActivities = _context.Txns.ToList(); var query = farmers.GroupJoin(farmActivities, fp => fp.Id, fa => fa.TransactionsId, (fp, results) => new TransactionViewModel( fp.Id, fp.Name, fp.Phone, fp.Gender, fp.AgeGroup, fp.SubCounty, fp.Ward, fp.Vcgroup, fp.C302, fp.C11501, fp.C11301, fp.Geometry, results)).ToList(); query.ForEach(sa => { var transModel = new TransModel() { Id = sa.Id, Name = sa.Name, AgeGroup = sa.AgeGroup, Phone = sa.Phone, Gender = sa.Gender, Vcgroup = sa.Vcgroup, Ward = sa.Ward, SubCounty = sa.SubCounty, C302 = sa.C302, C11501 = sa.C11501, C11301 = sa.C11301, Long = sa.Geometry.Coordinate.X, Lat = sa.Geometry.Coordinate.Y, Txns = sa.Results.ToList() }; double X = sa.Geometry.Coordinate.X; double Y = sa.Geometry.Coordinate.Y; var point = new Point(new Position(Y, X)); var feature = new GeoJSON.Net.Feature.Feature(point, transModel); geojsonndata.Features.Add(feature); }); } var actualJson = JsonConvert.SerializeObject(geojsonndata); return(actualJson); }
//GET /api/routing?from=31.8239,35.0375&to=31.8213,35.0965&type=f public async Task<IHttpActionResult> GetRouting(string from, string to, string type) { LineString lineString; var profile = ConvertProfile(type); if (profile == ProfileType.None) { var pointFrom = GetGeographicPosition(from); var pointTo = GetGeographicPosition(to); if (ModelState.IsValid == false) { return BadRequest(ModelState); } lineString = new LineString(new[] { pointFrom, pointTo }); } else { lineString = await _routingGateway.GetRouting(new RoutingGatewayRequest { From = from, To = to, Profile = profile, }); } var feature = new Feature(lineString, new FeatureProperties { Name = "Routing from " + from + " to " + to + " profile type: " + profile.ToString(), Creator = "IsraelHiking" }); return Ok(new FeatureCollection(new List<Feature>() { feature })); }
public override async Task Process(IPipeContext context) { var dataContext = context as GeoJsonContext; if (dataContext == null) { throw new NotSupportedException("The pipeline context must be of type DataPipelineContext"); } // Save time and space only read the first line to determine if this is a Feature or a // // Feature collection // string capture = ""; using (var reader = new StringReader(dataContext.OriginalData)) { bool finishedSearch = false; while (!finishedSearch) { var character = reader.ReadLine(); if (capture.IndexOf(',') < 0) { capture += character; } else { finishedSearch = true; } } if (capture.Contains("FeatureCollection")) { dataContext.Features = JsonConvert.DeserializeObject <GeoJSON.Net.Feature.FeatureCollection>(dataContext.OriginalData); } else if (capture.Contains("Feature")) { var feature = JsonConvert.DeserializeObject <GeoJSON.Net.Feature.Feature>(dataContext.OriginalData); dataContext.Features = new GeoJSON.Net.Feature.FeatureCollection(new List <GeoJSON.Net.Feature.Feature> { feature }); } else if (capture.Contains("MultiLineString")) { var multiline = JsonConvert.DeserializeObject <GeoJSON.Net.Geometry.MultiLineString>(dataContext.OriginalData); var feature = new GeoJSON.Net.Feature.Feature(multiline); dataContext.Features = new GeoJSON.Net.Feature.FeatureCollection(new List <GeoJSON.Net.Feature.Feature> { feature }); } else { throw new NotSupportedException("Type of GeoJson data could not be determined."); } } while (this.HasNextPipe) { await this.NextPipe.Process(context); } }
/// <summary> /// Prints GEOJson dump of Sites /// </summary> /// <param name="requiredProperties">list of properties to include (if not found in siteproperties an empty string will be inserted)</param> public void Execute(string[] requiredProperties, string siteType) { Console.Write("Content-Type: application/json\n\n"); var features = new List<Feature>(); FeatureCollection fc = new FeatureCollection(features); var filter = ""; if( siteType != "") filter = "type = '"+siteType+"'"; var sites = db.GetSiteCatalog(filter:filter); var siteProp = new TimeSeriesDatabaseDataSet.sitepropertiesDataTable(db); int id = 0; foreach (var s in sites) { try { var pos = new GeographicPosition(s.latitude, s.longitude); var pt = new GeoJSON.Net.Geometry.Point(pos); var props = siteProp.GetDictionary(s.siteid); for (int i = 0; i < requiredProperties.Length; i++) { if (requiredProperties[i].Trim() == "") continue; if (!props.ContainsKey(requiredProperties[i])) props.Add(requiredProperties[i], ""); } props.Add("siteid", s.siteid); props.Add("title", s.description); props.Add("state", s.state); props.Add("type", s.type); props.Add("region", s.responsibility.Trim()); props.Add("install", s.install); id++; var feature = new Feature(pt, props, id.ToString()); fc.Features.Add(feature); } catch (Exception error) { Console.WriteLine("Error at site:"+s); Console.WriteLine(error.Message); } } var settings = new JsonSerializerSettings(); settings.NullValueHandling = NullValueHandling.Ignore; var json = Newtonsoft.Json.JsonConvert.SerializeObject(fc, Newtonsoft.Json.Formatting.Indented,settings); Console.WriteLine(json); //File.WriteAllText(@"c:\temp\test.json", json); }
public FeatureCollection GetSalesData() { var model = new FeatureCollection() { CRS = new GeoJSON.Net.CoordinateReferenceSystem.NamedCRS("urn:ogc:def:crs:OGC::CRS84") }; var sales = _context.So011t .FromSql("EXECUTE sp_SalesData") .ToList(); sales.ForEach(x => { SO01TViewModel sale = new SO01TViewModel(); sale.Client = x.Client; sale.AcMgr = x.AcMgr; sale.AddlDesc = x.AddlDesc; sale.Comments = x.Comments; sale.Country = x.Country; sale.Createdby = x.Createdby; sale.Createddate = x.Createddate; sale.Currency = x.Currency; sale.Description = x.Description; sale.Dnote = x.Dnote; sale.Invoice = x.Invoice; sale.Invoiced = x.Invoiced; sale.Modby = x.Modby; sale.Moddate = x.Moddate; sale.Orderby = x.Orderby; sale.Ordercode = x.Ordercode; sale.Orderid = x.Orderid; sale.Orderdate = x.Orderdate; sale.OrderItem = x.OrderItem; sale.OrderType = x.OrderItem; sale.OrderType = x.OrderType; sale.Ordid = x.Ordid; sale.Ponum = x.Ponum; sale.Price = x.Price; sale.ProductCateg = x.ProductCateg; sale.ProductGroup = x.ProductGroup; sale.ProductId = x.ProductId; sale.ProductName = x.ProductName; sale.Quantity = x.Quantity; sale.Quotedate = x.Quotedate; sale.QuoteNo = x.QuoteNo; sale.SoldBy = x.SoldBy; sale.Supplierproductid = x.Supplierproductid; sale.Tax = x.Tax; sale.Type = x.Type; sale.Version = x.Version; sale.Xrate = x.Xrate; var actualPolygon = JsonConvert.DeserializeObject <Polygon>(x.Wkt); var feature = new GeoJSON.Net.Feature.Feature(actualPolygon, sale); model.Features.Add(feature); }); return(model); }
public void PointFeatureSerialization() { var point = new GeoJSON.Net.Geometry.Point(new GeoJSON.Net.Geometry.GeographicPosition(45.79012, 15.94107)); var featureProperties = new Dictionary<string, object> { {"Name", "Foo"} }; var model = new GeoJSON.Net.Feature.Feature(point, featureProperties); var serializedData = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore }); Assert.IsFalse(serializedData.Contains("longitude")); }
public LcboStore(DbDataReader reader) : this() { this.Id = Convert.ToInt32(reader["id"]); var columnNames = reader.GetSchemaTable().Rows.OfType<DataRow>().Select(r => (string)r["ColumnName"]); if (columnNames.Contains("name") && reader["name"] != DBNull.Value) { this.Name = reader["name"] as string; } if (columnNames.Contains("beer_volume") && reader["beer_volume"] != DBNull.Value) { this.Volumes.Beer = Convert.ToInt32(reader["beer_volume"]); } if (columnNames.Contains("wine_volume") && reader["wine_volume"] != DBNull.Value) { this.Volumes.Wine = Convert.ToInt32(reader["wine_volume"]); } if (columnNames.Contains("spirits_volume") && reader["spirits_volume"] != DBNull.Value) { this.Volumes.Spirits = Convert.ToInt32(reader["spirits_volume"]); } if (columnNames.Contains("city") && reader["city"] != DBNull.Value) { this.City = reader["city"] as string; } if (columnNames.Contains("subdivision_id") && reader["subdivision_id"] != DBNull.Value) { this.SubdivisionId = Convert.ToInt32(reader["subdivision_id"]); } if (columnNames.Contains("location") && reader["location"] != DBNull.Value) { var location = reader["location"] as string; var geojsonlocation = JsonConvert.DeserializeObject<Point>(location); var properties = new Dictionary<string, object> { { "name", this.Name }, { "city", this.City }, { "beerVolume", this.Volumes.Beer }, { "wineVolume", this.Volumes.Wine }, { "spiritsVolume", this.Volumes.Spirits }, { "totalVolume", this.Volumes.Total }, }; var feature = new Feature(geojsonlocation, properties); this.GeoJSON = feature; } }
public void PointFeatureSerialization() { var point = new GeoJSON.Net.Geometry.Point(new GeoJSON.Net.Geometry.GeographicPosition(45.79012, 15.94107)); var featureProperties = new Dictionary <string, object> { { "Name", "Foo" } }; var model = new GeoJSON.Net.Feature.Feature(point, featureProperties); var serializedData = GetSerialized(model); Assert.IsFalse(serializedData.Contains("longitude")); }
public void AddLine(string name, List<PointLatLng> points, ColorInfo colorInfo, Feature featureInfo) { _context.Send(_ => { _overlay.Routes.Add(new GMapRoute(points, name) { Stroke = new Pen(Color.FromArgb((int) colorInfo.StrokeColor), colorInfo.StrokeWidth +2), IsHitTestVisible = true, Tag = featureInfo }); }, null); }
public void PointFeatureSerialization() { var point = new GeoJSON.Net.Geometry.Point(new GeoJSON.Net.Geometry.GeographicPosition(45.79012, 15.94107)); var featureProperties = new Dictionary <string, object> { { "Name", "Foo" } }; var model = new GeoJSON.Net.Feature.Feature(point, featureProperties); var serializedData = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore }); Assert.IsFalse(serializedData.Contains("longitude")); }
public void AddPolygon(string name, List<PointLatLng> points, ColorInfo colorInfo, Feature featureInfo) { _context.Send(_ => { _overlay.Polygons.Add(new GMapPolygon(points, name) { Fill = new SolidBrush(Color.FromArgb((int) colorInfo.FillColor)), Stroke = new Pen(Color.FromArgb((int) colorInfo.StrokeColor), colorInfo.StrokeWidth), IsHitTestVisible = true, Tag = featureInfo }); }, null); }
internal Feature CreateFeature(GeoJSON.Net.Feature.Feature geoJsonFeature) { if (geoJsonFeature.Geometry == null) { throw new NotSupportedException("The Feature must contain Geometry data to be converted"); } var tileFeature = new TileFactory.Feature(convertToGeometryType(geoJsonFeature.Geometry.Type)) { Id = !string.IsNullOrEmpty(geoJsonFeature.Id) ? geoJsonFeature.Id : Guid.NewGuid().ToString(), Tags = geoJsonFeature.Properties }; return(tileFeature); }
private FeatureCollection CoordsToGeoJson(List <IPosition> coordinates) { if (!coordinates.Any()) { return(null); } var coords = coordinates.Select(r => new Position(r.Latitude, r.Longitude)).ToList(); var geo = new GeoJSON.Net.Geometry.LineString(coords); var feature = new GeoJSON.Net.Feature.Feature(geo); var featureCollection = new FeatureCollection(new List <Feature> { feature }); return(featureCollection); }
public void PolygonFeatureSerialization() { var coordinates = new List<GeographicPosition> { new GeographicPosition(52.370725881211314, 4.889259338378906), new GeographicPosition(52.3711451105601, 4.895267486572266), new GeographicPosition(52.36931095278263, 4.892091751098633), new GeographicPosition(52.370725881211314, 4.889259338378906) }.ToList<IPosition>(); var polygon = new Polygon(new List<LineString> { new LineString(coordinates) }); var featureProperties = new Dictionary<string, object> { { "Name", "Foo" } }; var model = new GeoJSON.Net.Feature.Feature(polygon, featureProperties); var serializedData = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore }); }
public void CreateLineFeature(string feeder, List <Position> geom, Breaker breaker) { if (geom.Count() < 2) { return; } var lineString = new LineString(geom); var props = new Dictionary <string, object> { //{ "type", "mv_line" }, { "feed", feeder }, { "name", breaker.name }, }; var feature = new GeoJSON.Net.Feature.Feature(lineString, props); lineFeatures.Features.Add(feature); }
/// <summary> /// Return a GeoJson from a datatable with column Geometry in Json format. /// </summary> /// <param name="dt">DataTable with columns properties and column geometry</param> /// <param name="GeometryColumn">Column Name of Geometry</param> /// <returns></returns> public static string fromDataset(DataTable dt, string GeometryColumn = "Geom") { var model = new FeatureCollection(); int numColumns = dt.Columns.Count; string[] keys = new string[numColumns]; for (int i = 0; i < numColumns; i++) { var columnName = dt.Columns[i].ColumnName; if (string.Compare(columnName, GeometryColumn, CultureInfo.InvariantCulture, CompareOptions.OrdinalIgnoreCase) != 0) { keys[i] = columnName; } } foreach (DataRow row in dt.Rows) { object geom = null; var geomDB = row[GeometryColumn].ToString(); var json = row[GeometryColumn].ToString(); JsonTextReader reader = new JsonTextReader(new StringReader(json)); while (reader.Read()) { geom = new GeometryConverter().ReadJson(reader, null, null, null); } Dictionary <string, object> props = new Dictionary <string, object>(); for (int j = 0; j < keys.Length; j++) { if (!string.IsNullOrEmpty(keys[j])) { props.Add(keys[j], row[j]); } } var feature = new GeoJSON.Net.Feature.Feature((IGeometryObject)geom, props); model.Features.Add(feature); } return(JsonConvert.SerializeObject(model)); }
public void LineString_Coordinate_Serialization() { string expected = "\"coordinates\":[[102.0,0.0],[103.0,1.0],[104.0,0.0],[105.0,1.0]]"; var feature = new GeoJSON.Net.Feature.Feature( new LineString(new List <IPosition> { new GeographicPosition(0.0, 102.0), new GeographicPosition(1.0, 103.0), new GeographicPosition(0.0, 104.0), new GeographicPosition(1.0, 105.0), }), new Dictionary <string, object> { { "name", "Dinagat Islands" } }); var serialized = GetSerialized(feature, false); Assert.AreNotEqual(-1, serialized.IndexOf(expected), expected + "\n" + serialized); }
public static Feature Parse(Tile.Feature feature, List<string> keys, List<Tile.Value> values, int x, int y, int z, uint extent, bool convertToGeographicPosition) { Feature result = null; var geom = GeometryParser.ParseGeometry(feature.Geometry, feature.Type); var id = feature.Id; var positions= convertToGeographicPosition? geom.Select(p => p.ToGeographicPosition(x,y,z,extent)).ToList(): geom.Select(p => new GeographicPosition(p.Latitude, p.Longitude)).ToList(); var coordinates = positions.ToList<IPosition>(); if (feature.Type == Tile.GeomType.Polygon) { if (coordinates.Count > 3) { var polygon = new Polygon(new List<LineString> {new LineString(coordinates)}); result = new Feature(polygon); } } else if (feature.Type == Tile.GeomType.LineString) { var ls = new LineString(coordinates); result = new Feature(ls); } else if (feature.Type == Tile.GeomType.Point) { var pt = new Point(coordinates[0]); result = new Feature(pt); } if (result != null) { result.Id = id.ToString(CultureInfo.InvariantCulture); var attributes = AttributesParser.Parse(keys, values, feature.Tags); foreach (var item in attributes) { result.Properties.Add(item.Key, item.Value); } } return result; }
public string GetCurrentVehicleValues() { var model = new FeatureCollection(); foreach (Vehicle v in vehicleHash.Values) { var geom = new Point(new Position(v.Latitude, v.Longitude)); var props = new Dictionary <string, object> { { "avl", v.Avl }, { "tim", v.Timestamp }, { "spe", v.Speed }, { "nam", vehicleNames[v.Avl] } }; var feature = new GeoJSON.Net.Feature.Feature(geom, props); model.Features.Add(feature); } var vehiclejson = JsonConvert.SerializeObject(model); return(vehiclejson); }
public void PolygonFeatureSerialization() { var coordinates = new List <GeographicPosition> { new GeographicPosition(52.370725881211314, 4.889259338378906), new GeographicPosition(52.3711451105601, 4.895267486572266), new GeographicPosition(52.36931095278263, 4.892091751098633), new GeographicPosition(52.370725881211314, 4.889259338378906) }.ToList <IPosition>(); var polygon = new Polygon(new List <LineString> { new LineString(coordinates) }); var featureProperties = new Dictionary <string, object> { { "Name", "Foo" } }; var model = new GeoJSON.Net.Feature.Feature(polygon, featureProperties); var serializedData = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore }); }
public TreeModel(Feature feature) { this.feature = feature; this.Ort = feature.Properties["ort"].ToString(); this.deuText = feature.Properties["deuText"].ToString(); this.wisText = feature.Properties["wisText"].ToString(); this.treeId = feature.Properties["treeId"].ToString(); this.baumNr = Convert.ToInt32(feature.Properties["baumNr"].ToString()); this.stadtteil = feature.Properties["stadtteil"].ToString(); this.strasse = feature.Properties["strasse"].ToString(); this.treeType = feature.Properties["treeType"].ToString(); this.stUmfang = Convert.ToDouble(feature.Properties["stUmfang"].ToString()); this.kroneDm = Convert.ToDouble(feature.Properties["kroneDm"].ToString()); this.typ = feature.Properties["typ"].ToString(); var point = (GeoJSON.Net.Geometry.Point)feature.Geometry; var coords = (GeoJSON.Net.Geometry.GeographicPosition)point.Coordinates; this.Location = new Geopoint(new BasicGeoposition() { Latitude = coords.Latitude, Longitude = coords.Longitude }); }
public static Feature ToGeoJSON(this VectorTileFeature vectortileFeature, int x, int y, int z) { IGeometryObject geom = null; switch (vectortileFeature.GeometryType) { case Tile.GeomType.Point: var projectedPoints = ProjectPoints(vectortileFeature.Geometry, x, y, z, vectortileFeature.Extent); geom = GetPointGeometry(projectedPoints); break; case Tile.GeomType.LineString: var projectedLines = ProjectLines(vectortileFeature.Geometry, x, y, z, vectortileFeature.Extent); geom = GetLineGeometry(projectedLines); break; case Tile.GeomType.Polygon: // todo: Call method ClassifyRings.Classify first... // and process the classified rings... var rings = ClassifyRings.Classify(vectortileFeature.Geometry); var projectedPolygons = ProjectPolygons(rings, x, y, z, vectortileFeature.Extent); // var projectedPolygons = ProjectLines(vectortileFeature.Geometry, x, y, z, vectortileFeature.Extent); geom = GetPolygonGeometry(projectedPolygons); break; } var result = new Feature(geom); // add attributes foreach (var item in vectortileFeature.Attributes) { result.Properties.Add(item.Key, item.Value); } result.Id = vectortileFeature.Id; return result; }
/* * GeoJSON Feature Representation of a beacon */ public Feature toGeoJSONFeature() { var properties = new Dictionary<String, object>(); properties.Add("Beacon Type", beaconType); properties.Add("Element Id", elementId); var feature = new Feature(BeaconCoordinates, properties); return feature; }
public async Task <ActionResult <FeatureCollection> > GetGeoJsonAsync(string id, ODataQueryOptions <RouteInstance> q, [FromQuery] string language) { var userClaim = User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier); var userIdClaim = int.Parse(userClaim != null ? userClaim.Value : "-1"); var guid = Guid.Parse(id); var map = await _context.Maps.SingleOrDefaultAsync(m => m.MapGuid == guid); if (map == null) { return(NotFound()); } if (string.IsNullOrWhiteSpace(map.SharingLinkName)) { if (!User.Claims.Any()) { return(Forbid()); } var adminClaim = (User.Claims.SingleOrDefault(c => c.Type == "admin").Value ?? "false"); if ((userIdClaim < 0 || map.UserId != userIdClaim) && !string.Equals(adminClaim, "true", StringComparison.OrdinalIgnoreCase)) { return(Forbid()); } } var routes = _context.RouteInstances .Include(ri => ri.Route) .ThenInclude(r => r.RouteType) .AsQueryable(); var types = await _context.RouteTypes.ToListAsync(); var colours = new Dictionary <int, LineStyle>(); types.ForEach(t => { colours.Add(t.TypeId, new LineStyle { Color = Color32.Parse(t.Colour) }); }); if (q.Filter != null) { var model = Startup.GetEdmModel(); IEdmType type = model.FindDeclaredType("OVDB_database.Models.RouteInstance"); IEdmNavigationSource source = model.FindDeclaredEntitySet("Products"); var parser = new ODataQueryOptionParser(model, type, source, new Dictionary <string, string> { { "$filter", q.Filter.RawValue } }); var context = new ODataQueryContext(model, typeof(RouteInstance), q.Context.Path); var filter = new FilterQueryOption(q.Filter.RawValue, context, parser); routes = q.Filter.ApplyTo(routes, new ODataQuerySettings()) as IQueryable <RouteInstance>; } routes = routes.Where(r => r.RouteInstanceMaps.Any(rim => rim.MapId == map.MapId) || r.Route.RouteMaps.Any(rm => rm.MapId == map.MapId)); var collection = new FeatureCollection(); var routesList = new List <Route>(); var routesToReturn = new Dictionary <int, int>(); await routes.ForEachAsync(r => { if (!routesToReturn.ContainsKey(r.RouteId)) { routesToReturn.Add(r.RouteId, 0); routesList.Add(r.Route); } routesToReturn[r.RouteId] += 1; }); routesList.ForEach(r => { try { var multi = r.Coordinates.Split("###").ToList(); var lines = new List <GeoJSON.Net.Geometry.LineString>(); multi.ForEach(block => { var coordinates = block.Split('\n').Where(a => !string.IsNullOrWhiteSpace(a)).ToList(); var coords = coordinates.Select(r => new Position(double.Parse(r.Split(',')[1], CultureInfo.InvariantCulture), double.Parse(r.Split(',')[0], CultureInfo.InvariantCulture))).ToList(); if (coords.Count >= 2) { var geo = new GeoJSON.Net.Geometry.LineString(coords); lines.Add(geo); } }); GeoJSON.Net.Feature.Feature feature; if (lines.Count == 1) { feature = new GeoJSON.Net.Feature.Feature(lines.Single()); } else { var multiLineString = new MultiLineString(lines); feature = new GeoJSON.Net.Feature.Feature(multiLineString); } feature.Properties.Add("id", r.RouteId); feature.Properties.Add("totalInstances", routesToReturn[r.RouteId]); if (map.ShowRouteOutline) { feature.Properties.Add("o", 1); } if (map.ShowRouteInfo) { if (language == "nl" && !string.IsNullOrWhiteSpace(r.NameNL)) { feature.Properties.Add("name", r.NameNL); } else { feature.Properties.Add("name", r.Name); } if (language == "nl" && !string.IsNullOrWhiteSpace(r.RouteType.NameNL)) { feature.Properties.Add("type", r.RouteType.NameNL); } else { feature.Properties.Add("type", r.RouteType.Name); } if (language == "nl" && !string.IsNullOrWhiteSpace(r.DescriptionNL)) { feature.Properties.Add("description", r.DescriptionNL); } else { feature.Properties.Add("description", r.Description); } feature.Properties.Add("lineNumber", r.LineNumber); feature.Properties.Add("operatingCompany", r.OperatingCompany); if (r.OverrideDistance.HasValue) { feature.Properties.Add("distance", r.OverrideDistance); } else { feature.Properties.Add("distance", r.CalculatedDistance); } } if (map.UserId == userIdClaim) { feature.Properties.Add("owner", true); } if (!string.IsNullOrWhiteSpace(r.OverrideColour)) { feature.Properties.Add("stroke", r.OverrideColour); } else { feature.Properties.Add("stroke", r.RouteType.Colour); } collection.Features.Add(feature); } catch (Exception ex) { Console.WriteLine(ex.Message); throw; } }); return(collection); }
public async Task <ActionResult <FeatureCollection> > GetSingleRouteGeoJsonAsync(int id, Guid guid, [FromQuery] string language) { var route = await _context.Routes.Include(r => r.RouteType).Include(r => r.RouteCountries).SingleOrDefaultAsync(r => r.RouteId == id && r.Share == guid); if (route == null) { return(NotFound()); } var collection = new FeatureCollection(); var multi = route.Coordinates.Split("###").ToList(); var lines = new List <GeoJSON.Net.Geometry.LineString>(); multi.ForEach(block => { var coordinates = block.Split('\n').Where(a => !string.IsNullOrWhiteSpace(a)).ToList(); var coords = coordinates.Select(r => new Position(double.Parse(r.Split(',')[1], CultureInfo.InvariantCulture), double.Parse(r.Split(',')[0], CultureInfo.InvariantCulture))).ToList(); if (coords.Count >= 2) { var geo = new GeoJSON.Net.Geometry.LineString(coords); lines.Add(geo); } }); GeoJSON.Net.Feature.Feature feature; if (lines.Count == 1) { feature = new GeoJSON.Net.Feature.Feature(lines.Single()); } else { var multiLineString = new MultiLineString(lines); feature = new GeoJSON.Net.Feature.Feature(multiLineString); } if (language == "nl" && !string.IsNullOrWhiteSpace(route.NameNL)) { feature.Properties.Add("name", route.NameNL); } else { feature.Properties.Add("name", route.Name); } if (language == "nl" && !string.IsNullOrWhiteSpace(route.RouteType.NameNL)) { feature.Properties.Add("type", route.RouteType?.NameNL); } else { feature.Properties.Add("type", route.RouteType?.Name); } if (language == "nl" && !string.IsNullOrWhiteSpace(route.DescriptionNL)) { feature.Properties.Add("description", route.DescriptionNL); } else { feature.Properties.Add("description", route.Description ?? "Unknown"); } feature.Properties.Add("lineNumber", route.LineNumber); feature.Properties.Add("operatingCompany", route.OperatingCompany);; if (!string.IsNullOrWhiteSpace(route.OverrideColour)) { feature.Properties.Add("stroke", route.OverrideColour); } else { feature.Properties.Add("stroke", route.RouteType?.Colour ?? "#000"); } collection.Features.Add(feature); return(collection); }
private static bool FeatureRepresentsCircle(Feature feature) { return feature.Geometry.Type == GeoJSONObjectType.Point && feature.Properties.ContainsKey("radius"); }
public string BuildingsToGeoJson() { var fc = new FeatureCollection(); var buildings = Buildings.Where(w => w.LocationDataWKT != ""); foreach (var building in buildings) { string wkt = building.LocationDataWKT; string geoType = wkt.Substring(0, wkt.IndexOf("(")).Trim(); string coord = wkt.Replace(geoType, "").Replace("(", "").Replace(")", "").Replace(", ", ",").Trim(); IGeometryObject geometry = null; if (geoType == "POLYGON") { geometry = new Polygon(new List <LineString> { new LineString( coord.Split(',') .Select(s => s.Split(' ')) .Select(a => new GeographicPosition(double.Parse(a[1]), double.Parse(a[0]))) ) }); } else if (geoType == "POINT") { geometry = new Point( coord.Split(',') .Select(s => s.Split(' ')) .Select(a => new GeographicPosition(double.Parse(a[1]), double.Parse(a[0]))).First() ); } else { throw new Exception("Invalid GeoJson geoType. Value: " + geoType); } var props = new Dictionary <string, object> { { "id", building.GroupRiskBuildingId }, // Building info { "groupRiskBuildingId", building.GroupRiskBuildingId }, { "buildingId", building.BuildingId }, { "policyId", building.PolicyId }, { "groupId", building.GroupId }, { "locationId", building.LocationId }, { "constructionType", building.ConstructionType }, { "pmlValue", building.PmlValue }, // Location info { "groupRiskLocationId", building.GroupRiskLocationId }, { "protectionClass", building.ProtectionClass }, { "grade", building.Grade }, { "area", building.Area }, { "stories", building.Stories }, { "address1", building.Address1 }, { "address2", building.Address2 }, { "address3", building.Address3 }, { "city", building.City }, { "state", building.State }, { "postalCode", building.PostalCode }, { "isDirty", building.IsDirty.ToString() } }; if (geometry != null) { var feature = new GeoJSON.Net.Feature.Feature(geometry, props); fc.Features.Add(feature); } } return(JsonConvert.SerializeObject(fc)); }
public string RiskGroupToGeoJson() { var fc = new FeatureCollection(); string wkt = LocationDataWKT; if (!String.IsNullOrEmpty(wkt)) { IGeometryObject geometry = null; string geoType = wkt.Substring(0, wkt.IndexOf("(")).Trim(); string wktPrepared = String.Empty; if (geoType == "POINT") { wktPrepared = wkt.Replace(geoType, "").Trim().Replace("((", "").Replace("))", "").Replace("(", "").Replace(")", ""); var input = wktPrepared; geometry = input.Split(',') .Select(s => s.Split(' ')) .Select(a => new GeographicPosition(double.Parse(a[1]), double.Parse(a[0]))) .Select(a => new Point(a)) .FirstOrDefault(); } else if (geoType == "POLYGON") { wktPrepared = wkt.Replace(geoType, "").Trim().Replace("((", "").Replace("))", "").Replace(", ", ","); string[] input = Regex.Split(wktPrepared, @","); List <GeographicPosition> geometryList = input .Select(s => s.Split(' ')) .Select(a => new GeographicPosition(double.Parse(a[1]), double.Parse(a[0]))) .ToList(); geometry = new Polygon(new List <LineString> { new LineString(geometryList) }); } else if (geoType == "MULTIPOINT") { wktPrepared = wkt.Replace(geoType, "").Trim().Replace("((", "").Replace("))", "").Replace("(", "").Replace(", ", ","); string[] points = Regex.Split(wktPrepared, @"\),"); List <Point> geometryList = points .Select(s => s.Split(' ')) .Select(a => new GeographicPosition(double.Parse(a[1]), double.Parse(a[0]))) .Select(a => new Point(a)) .ToList(); geometry = new MultiPoint(geometryList); } else if (geoType == "MULTIPOLYGON") { wktPrepared = wkt.Replace(geoType, "").Trim().Replace("(((", "").Replace(")))", "").Replace("(", ""); string[] polys = Regex.Split(wktPrepared, @"\)\),"); List <Polygon> polyList = new List <Polygon>(); foreach (var element in polys.Select(s => s.Split(','))) { List <GeographicPosition> posList = element .Select(s => s.Trim().Split(' ')) .Select(a => new GeographicPosition(double.Parse(a[1]), double.Parse(a[0]))) .ToList(); polyList.Add(new Polygon(new List <LineString> { new LineString(posList) })); } geometry = new MultiPolygon(polyList); } else { throw new Exception("Invalid GeoJson geoType. Value: " + geoType); } var props = new Dictionary <string, object> { { "id", this.GroupId }, // Building info { "policyInScope", this.PolicyInScope }, { "startDate", this.StartDate }, { "endDate", this.EndDate }, { "groupRiskPolicyId", this.GroupRiskPolicyId }, { "policyid", this.PolicyId } }; if (geometry != null) { var feature = new GeoJSON.Net.Feature.Feature(geometry, props); fc.Features.Add(feature); } } return(JsonConvert.SerializeObject(fc)); }
public static JFeature.Feature Feature2JG(Feature feature) { JGeometry.IGeometryObject igeometry = Geometry2JG(feature.geometry); JFeature.Feature jFeature = new JFeature.Feature(igeometry, feature.attributes, feature.featureID.ToString()); return(jFeature); }
public void Test() { var route = new Route(); var collection = new FeatureCollection(); var multi = route.Coordinates.Split("###").ToList(); var lines = new List <GeoJSON.Net.Geometry.LineString>(); multi.ForEach(block => { var coordinates = block.Split('\n').Where(a => !string.IsNullOrWhiteSpace(a)).ToList(); var coords = coordinates.Select(r => new Position(double.Parse(r.Split(',')[1], CultureInfo.InvariantCulture), double.Parse(r.Split(',')[0], CultureInfo.InvariantCulture))).ToList(); if (coords.Count >= 2) { var geo = new GeoJSON.Net.Geometry.LineString(coords); lines.Add(geo); } }); GeoJSON.Net.Feature.Feature feature; if (lines.Count == 1) { feature = new GeoJSON.Net.Feature.Feature(lines.Single()); } else { var multiLineString = new MultiLineString(lines); feature = new GeoJSON.Net.Feature.Feature(multiLineString); } if (!string.IsNullOrWhiteSpace(route.Name)) { feature.Properties.Add("name", route.Name); } if (!string.IsNullOrWhiteSpace(route.NameNL)) { feature.Properties.Add("nameNL", route.NameNL); } if (!string.IsNullOrWhiteSpace(route.Description)) { feature.Properties.Add("description", route.Description); } if (!string.IsNullOrWhiteSpace(route.DescriptionNL)) { feature.Properties.Add("descriptionNL", route.DescriptionNL); } if (route.FirstDateTime.HasValue) { feature.Properties.Add("firstDateTime", route.FirstDateTime.Value.ToString("o")); } if (!string.IsNullOrWhiteSpace(route.LineNumber)) { feature.Properties.Add("lineNumber", route.LineNumber); } if (!string.IsNullOrWhiteSpace(route.OperatingCompany)) { feature.Properties.Add("operatingCompany", route.OperatingCompany); } if (!string.IsNullOrWhiteSpace(route.OverrideColour)) { feature.Properties.Add("name", route.OverrideColour); } if (route.RouteCountries.Any()) { feature.Properties.Add("countries", string.Join(',', route.RouteCountries.Select(c => c.Country.Name))); } if (route.RouteMaps.Any()) { feature.Properties.Add("maps", string.Join(',', route.RouteMaps.Select(c => c.Map.Name))); } if (route.RouteTypeId.HasValue) { feature.Properties.Add("type", route.RouteType.Name); } collection.Features.Add(feature); }
private FeatureCollection ConvertGpxContentToGeoJson(byte[] content) { var collection = new FeatureCollection(); using (var stream = new MemoryStream(content)) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(gpxType)); var gpx = xmlSerializer.Deserialize(stream) as gpxType; foreach (var point in gpx.wpt ?? new wptType[0]) { var feature = new Feature(new Point(CreateGeoPosition(point)), CreateNameProperties(point.name)); collection.Features.Add(feature); } foreach (var track in gpx.trk ?? new trkType[0]) { if (track.trkseg.Length == 1) { var lineStringFeature = new Feature(new LineString(track.trkseg[0].trkpt.Select(point => CreateGeoPosition(point))), CreateNameProperties(track.name)); collection.Features.Add(lineStringFeature); continue; } var lineStringList = new List<LineString>(); foreach (var segment in track.trkseg) { lineStringList.Add(new LineString(segment.trkpt.Select(point => CreateGeoPosition(point)))); } var feature = new Feature(new MultiLineString(lineStringList), CreateNameProperties(track.name)); collection.Features.Add(feature); } foreach (var route in gpx.rte ?? new rteType[0]) { var lineStringFeature = new Feature(new LineString(route.rtept.Select(point => CreateGeoPosition(point))), CreateNameProperties(route.name)); collection.Features.Add(lineStringFeature); } } return collection; }
public void GenerateMapData() { // init road data var roads = RoadSegment.ParseRoadData(File.ReadAllText(Path.Combine(dataDir, "r0.txt"))); // serialize as geojson FeatureCollection trafficData = new FeatureCollection(); foreach (RoadSegment road in roads) { // find the sensor and determine color var sensor = sensorData.Where(s => s.ID == road.ID).FirstOrDefault(); List<IPosition> segments = new List<IPosition>(); for (int i = 0; i < road.Nodes.Count; i++) { segments.Add(new GeographicPosition(road.Nodes[i].Lat, road.Nodes[i].Lon)); } var featureProperties = new Dictionary<string, object> { { "id", road.ID }, { "l", road.Semt }, { "s", sensor == null ? -1 : sensor.Speed } }; var feat = new Feature(new LineString(segments), featureProperties); trafficData.Features.Add(feat); } var serializedData = JsonConvert.SerializeObject(trafficData); var dateTime = String.Format("{2:00}/{3:00}/{4} {0:00}:{1:00}", acqTimeLocal.Hour, acqTimeLocal.Minute,acqTimeLocal.Day,acqTimeLocal.Month,acqTimeLocal.Year); StringBuilder sb = new StringBuilder(); sb.Append("var mapData=" + serializedData + ";\r\n"); sb.Append("var acqTime='" + dateTime + "';\r\n"); sb.Append("var trafficIndex=" + trafficIndex + ";\r\n"); File.WriteAllText(Path.Combine(dataDir, "tkmData.js"), sb.ToString()); }
public async Task<Feature> BoundaryGeoJson(int subdivId) { var result = new Feature(new Point(new Position())); var query = @"select ST_AsGeoJSON(boundry, 15, 4) as boundary from subdivisions where id = @subdivId"; using (var conn = new Npgsql.NpgsqlConnection(connString)) { using (var cmd = conn.CreateCommand()) { cmd.CommandText = query; conn.Open(); cmd.Parameters.AddWithValue("@subdivId", subdivId); var boundary = await cmd.ExecuteScalarAsync() as string; if (boundary.Contains("\"type\":\"MultiPolygon\"")) { var multipolygon = JsonConvert.DeserializeObject<MultiPolygon>(boundary); result = new Feature(multipolygon); } else if (boundary.Contains("\"type\":\"Polygon\"")) { var polygon = JsonConvert.DeserializeObject<Polygon>(boundary); result = new Feature(polygon); } } } return result; }
public void InfoForQGIS() { FeatureCollection lv_line = new FeatureCollection(); FeatureCollection lv_service_line = new FeatureCollection(); FeatureCollection substation = new FeatureCollection(); FeatureCollection substation_text = new FeatureCollection(); FeatureCollection mv_pole = new FeatureCollection(); FeatureCollection mv_pole_text = new FeatureCollection(); FeatureCollection lv_pole = new FeatureCollection(); FeatureCollection lv_pole_text = new FeatureCollection(); FeatureCollection client = new FeatureCollection(); FeatureCollection client_text = new FeatureCollection(); FeatureCollection aux = new FeatureCollection(); FeatureCollection aux_text = new FeatureCollection(); //string feeder_ex = "('O-145','O-242','O-243')"; DataTable btlines = ExecuteSelectQuery("select codigo,circuito,alm,sed,ckto,utm from els_2018.linea where estado = 'Existente'and tipo = 'BT' and uso != 'Servicio' and sed !=''"); //DataTable btlines = ExecuteSelectQuery("select codigo,circuito,alm,sed,ckto,utm from els_2018.linea where estado = 'Existente'and tipo = 'BT' and sed !='' and uso != 'Servicio' and alm in "+ feeder_ex); for (int i = 0; i < btlines.Rows.Count; ++i) { List <Position> geom = new List <Position>(); string utm = btlines.Rows[i]["utm"].ToString(); string[] strArr = utm.Split(' '); for (int count = 0; count <= strArr.Length - 1; count++) { string[] pos = strArr[count].Split(','); Position p = ToLatLon(Convert.ToDouble(pos[0]), Convert.ToDouble(pos[1]), "19S"); geom.Add(p); } if (geom.Count() < 2) { continue; } var lineString = new LineString(geom); //here we need the information about the circuit var props = new Dictionary <string, object> { { "feed", btlines.Rows[i]["alm"].ToString() }, { "sub", btlines.Rows[i]["sed"].ToString() }, { "cir", btlines.Rows[i]["ckto"].ToString() } }; var feature = new GeoJSON.Net.Feature.Feature(lineString, props); lv_line.Features.Add(feature); } DataTable btsevicelines = ExecuteSelectQuery("select codigo,circuito,alm,sed,ckto,utm from els_2018.linea where estado = 'Existente'and tipo = 'BT' and uso = 'Servicio' and sed !=''"); //DataTable btsevicelines = ExecuteSelectQuery("select codigo,circuito,alm,sed,ckto,utm from els_2018.linea where estado = 'Existente'and tipo = 'BT' and sed !='' and uso = 'Servicio' and alm in " + feeder_ex); for (int i = 0; i < btsevicelines.Rows.Count; ++i) { List <Position> geom = new List <Position>(); string utm = btsevicelines.Rows[i]["utm"].ToString(); string[] strArr = utm.Split(' '); for (int count = 0; count <= strArr.Length - 1; count++) { string[] pos = strArr[count].Split(','); Position p = ToLatLon(Convert.ToDouble(pos[0]), Convert.ToDouble(pos[1]), "19S"); geom.Add(p); } if (geom.Count() < 2) { continue; } var lineString = new LineString(geom); var props = new Dictionary <string, object> { //{ "type", "lv_service_line" }, { "feed", btsevicelines.Rows[i]["alm"].ToString() }, { "sub", btsevicelines.Rows[i]["sed"].ToString() }, { "cir", btsevicelines.Rows[i]["ckto"].ToString() } }; var feature = new GeoJSON.Net.Feature.Feature(lineString, props); lv_service_line.Features.Add(feature); } DataTable substations = ExecuteSelectQuery("select codigo,id,etiqueta,alm,utm_x,utm_y,utm_s_x,utm_s_y from els_2018.subestacion where estado = 'Existente' and id != '' and etiqueta != '' and utm_s_x != 0"); //DataTable substations = ExecuteSelectQuery("select codigo,id,etiqueta,alm,utm_x,utm_y,utm_s_x,utm_s_y from els_2018.subestacion where estado = 'Existente' and id != '' and etiqueta != '' and utm_s_x != 0 and alm IN " + feeder_ex); for (int i = 0; i < substations.Rows.Count; ++i) { Position p = ToLatLon(Convert.ToDouble(substations.Rows[i]["utm_x"]), Convert.ToDouble(substations.Rows[i]["utm_y"]), "19S"); var geom = new Point(p); var props = new Dictionary <string, object> { //{ "type", "sub" }, { "feed", substations.Rows[i]["alm"].ToString() }, { "name", substations.Rows[i]["id"].ToString() }, }; var feature = new GeoJSON.Net.Feature.Feature(geom, props); substation.Features.Add(feature); //label feature Position p_lbl = ToLatLon(Convert.ToDouble(substations.Rows[i]["utm_s_x"]), Convert.ToDouble(substations.Rows[i]["utm_s_y"]), "19S"); var geom_lbl = new Point(p_lbl); var props_lbl = new Dictionary <string, object> { //{ "type", "sub_lbl" }, { "feed", substations.Rows[i]["alm"].ToString() }, { "name", substations.Rows[i]["id"].ToString() }, }; var feature_lbl = new GeoJSON.Net.Feature.Feature(geom_lbl, props_lbl); substation_text.Features.Add(feature_lbl); } DataTable poles = ExecuteSelectQuery("select tipo_uso, etiqueta, alm, sed, utm_x, utm_y, utm_s_x, utm_s_y from els_2018.poste where estado = 'Existente' and utm_x != 0 and (tipo_uso = 'Red Secundaria' or tipo_uso = 'Red Primaria' or tipo_uso = 'Alumbrado Publico')"); //DataTable poles = ExecuteSelectQuery("select tipo_uso, etiqueta, alm, sed, utm_x, utm_y, utm_s_x, utm_s_y from els_2018.poste where estado = 'Existente' and utm_x != 0 and (tipo_uso = 'Red Secundaria' or tipo_uso = 'Red Primaria' or tipo_uso = 'Alumbrado Publico') and alm IN " + feeder_ex); for (int i = 0; i < poles.Rows.Count; ++i) { string type, type_lbl; if (poles.Rows[i]["tipo_uso"].ToString() == "Red Primaria") { type = "mv_pole"; type_lbl = "mv_pole_lbl"; aux = mv_pole; aux_text = mv_pole_text; } else { type = "lv_pole"; type_lbl = "lv_pole_lbl"; aux = lv_pole; aux_text = lv_pole_text; } Position p = ToLatLon(Convert.ToDouble(poles.Rows[i]["utm_x"]), Convert.ToDouble(poles.Rows[i]["utm_y"]), "19S"); var geom = new Point(p); var props = new Dictionary <string, object> { //{ "type", type }, { "feed", poles.Rows[i]["alm"].ToString() }, { "name", poles.Rows[i]["etiqueta"].ToString() }, }; var feature = new GeoJSON.Net.Feature.Feature(geom, props); aux.Features.Add(feature); //for labels Position p_lbl = ToLatLon(Convert.ToDouble(poles.Rows[i]["utm_s_x"]), Convert.ToDouble(poles.Rows[i]["utm_s_y"]), "19S"); var geom_lbl = new Point(p_lbl); var props_lbl = new Dictionary <string, object> { //{ "type", type_lbl }, { "feed", poles.Rows[i]["alm"].ToString() }, { "name", poles.Rows[i]["etiqueta"].ToString() }, }; var feature_lbl = new GeoJSON.Net.Feature.Feature(geom_lbl, props_lbl); aux_text.Features.Add(feature_lbl); } DataTable clients = ExecuteSelectQuery("select circuito,alm,sed,ckto,suministro,utm_x,utm_y,utm_s_x,utm_s_y from els_2018.punto_servicio where estado = 'Existente' and suministro != ' '"); //DataTable clients = ExecuteSelectQuery("select circuito,alm,sed,ckto,suministro,utm_x,utm_y,utm_s_x,utm_s_y from els_2018.punto_servicio where estado = 'Existente' and suministro != ' ' and alm IN " + feeder_ex); for (int i = 0; i < clients.Rows.Count; ++i) { Position p = ToLatLon(Convert.ToDouble(clients.Rows[i]["utm_x"]), Convert.ToDouble(clients.Rows[i]["utm_y"]), "19S"); var geom = new Point(p); var props = new Dictionary <string, object> { //{ "type", "client" }, { "feed", clients.Rows[i]["alm"].ToString() }, { "name", clients.Rows[i]["ckto"].ToString() }, }; var feature = new GeoJSON.Net.Feature.Feature(geom, props); client.Features.Add(feature); //labels Position p_lbl = ToLatLon(Convert.ToDouble(clients.Rows[i]["utm_s_x"]), Convert.ToDouble(clients.Rows[i]["utm_s_y"]), "19S"); var geom_lbl = new Point(p_lbl); string sum = clients.Rows[i]["suministro"].ToString(); sum = sum.Replace(" ", "\n"); var props_lbl = new Dictionary <string, object> { //{ "type", "client_lbl" }, { "feed", clients.Rows[i]["alm"].ToString() }, { "name", sum }, }; var feature_lbl = new GeoJSON.Net.Feature.Feature(geom_lbl, props_lbl); client_text.Features.Add(feature_lbl); } File.WriteAllText(@"C:\cygwin64\home\tony\giscada\lv_line.geojson", JsonConvert.SerializeObject(lv_line)); File.WriteAllText(@"C:\cygwin64\home\tony\giscada\lv_service_line.geojson", JsonConvert.SerializeObject(lv_service_line)); File.WriteAllText(@"C:\cygwin64\home\tony\giscada\substation.geojson", JsonConvert.SerializeObject(substation)); File.WriteAllText(@"C:\cygwin64\home\tony\giscada\substation_text.geojson", JsonConvert.SerializeObject(substation_text)); File.WriteAllText(@"C:\cygwin64\home\tony\giscada\mv_pole.geojson", JsonConvert.SerializeObject(mv_pole)); File.WriteAllText(@"C:\cygwin64\home\tony\giscada\mv_pole_text.geojson", JsonConvert.SerializeObject(mv_pole_text)); File.WriteAllText(@"C:\cygwin64\home\tony\giscada\lv_pole.geojson", JsonConvert.SerializeObject(lv_pole)); File.WriteAllText(@"C:\cygwin64\home\tony\giscada\lv_pole_text.geojson", JsonConvert.SerializeObject(lv_pole_text)); File.WriteAllText(@"C:\cygwin64\home\tony\giscada\client.geojson", JsonConvert.SerializeObject(client)); File.WriteAllText(@"C:\cygwin64\home\tony\giscada\client_text.geojson", JsonConvert.SerializeObject(client_text)); }
/// <summary> /// Creates the geojson export. /// </summary> /// <param name="results">The results.</param> /// <param name="exportProperties">The export properties.</param> public void CreateExport(IRecordSet results, string geometryFieldName) { if (results != null) { ICursor cursor; cursor = results.get_Cursor(false); IRow row = cursor.NextRow(); int rowCount = 0; //create an empty list of geojson features var geoJsonFeatures = new List<GeoJSON.Net.Feature.Feature>(); //get the index of the geometry field int fieldIndex = row.Fields.FindField(geometryFieldName); if (fieldIndex == -1) throw new Exception("Could not locate geometry field:shape"); if (row != null) { while (row != null) { //use the factory to convert the esri geometry to the geojson geometry IGeometryObject geoJsonGeom = null; if (row.get_Value(fieldIndex) != null) { GeoJsonGeometryFactory geomFactory = new GeoJsonGeometryFactory(); geoJsonGeom = geomFactory.GetGeometry(row.get_Value(fieldIndex) as IGeometry); } //use the factory to convert esri row to geojson attributes var atts = new GeoJsonAttributeFactory().GetAttributes(row); //create the feature and add it to the collection - use the unique key from the row or create one GeoJSON.Net.Feature.Feature f = null; if (row.Table.HasOID) { f = new GeoJSON.Net.Feature.Feature(geoJsonGeom, atts) { Id = row.get_Value(row.Fields.FindField(row.Table.OIDFieldName)).ToString() }; } else { f = new GeoJSON.Net.Feature.Feature(geoJsonGeom, atts) { Id = Guid.NewGuid().ToString() }; } geoJsonFeatures.Add(f); row = cursor.NextRow(); rowCount++; } } //initialise the geoJsonFeatureCollection var fc = new FeatureCollection(geoJsonFeatures); //to keep the export small, use formatting = none and exclude null values //todo - allow the null value handling and indentation to be exposed _geoJson = JsonConvert.SerializeObject(fc, Formatting.None, new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore }); } }
/// <summary> /// Calculates the route. /// </summary> /// <param name="transportMode">The transport mode.</param> /// <param name="start">The start point.</param> /// <param name="end">The end point.</param> /// <returns> /// A new <see cref="RouteModel" /> with the route details. /// </returns> public RouteModel CalculatePointToPoint(VehicleEnum transportMode, GeoCoordinate start, GeoCoordinate end) { // calculate route. var startPoint = router.Resolve(transportMode, start); var endPoint = router.Resolve(transportMode, end); var route = router.Calculate(transportMode, startPoint, endPoint); if (route == null) { throw new RoutingException("No matching route found."); } var coordinates = route.Entries .Select(x => new GeographicPosition(x.Latitude, x.Longitude)) .ToList(); var lineString = new LineString(coordinates); var feature = new Feature( lineString, new Dictionary<string, object> { { "name", "Test route result." }, { "distance", route.TotalDistance }, { "journeytime", route.TotalTime }, }); var generator = new InstructionGenerator(); var instructions = generator.Generate(route, interpreter, new SimpleEnglishLanguageGenerator()); return new RouteModel { Results = new ResultSet(feature) }; }