Esempio n. 1
0
        public async Task <ActionResult <Route> > ImportRouteToDatabaseAsync([FromBody] OSMLineDTO line)
        {
            var userIdClaim = int.Parse(User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value ?? "-1");

            if (userIdClaim < 0)
            {
                return(Forbid());
            }

            var geojson     = line.GeoJson;
            var coordinates =
                ((LineString)geojson.Features.Single().Geometry).Coordinates
                .Select(c => c.Longitude.ToString(CultureInfo.InvariantCulture) + ", " + c.Latitude.ToString(CultureInfo.InvariantCulture))
                .ToList();


            var route = new Route
            {
                Coordinates = string.Join('\n', coordinates),
                Name        = line.Name,
                Share       = Guid.NewGuid(),
                RouteMaps   = new List <RouteMap>()
            };

            if (route.Name == null)
            {
                route.Name = "Name";
            }

            if (!string.IsNullOrWhiteSpace(line.Description))
            {
                route.Description = line.Description;
            }
            if (!string.IsNullOrWhiteSpace(line.Colour))
            {
                route.OverrideColour = line.Colour;
            }
            if (!string.IsNullOrWhiteSpace(line.Operator))
            {
                route.OperatingCompany = line.Operator;
            }
            if (!string.IsNullOrWhiteSpace(line.Ref))
            {
                route.LineNumber = line.Ref;
            }
            if (!string.IsNullOrWhiteSpace(line.From))
            {
                route.From = line.From;
            }
            if (!string.IsNullOrWhiteSpace(line.To))
            {
                route.To = line.To;
            }
            var maps = await _context.Maps.Where(m => m.UserId == userIdClaim).ToListAsync();

            var defaultMap = maps.Where(m => m.Default == true).FirstOrDefault();

            if (defaultMap == null)
            {
                defaultMap = maps.First();
            }

            route.RouteMaps.Add(new RouteMap {
                MapId = defaultMap.MapId
            });
            DistanceCalculationHelper.ComputeDistance(route);

            _context.Routes.Add(route);
            await _context.SaveChangesAsync();

            return(Ok(route));
        }
Esempio n. 2
0
        private async Task <List <OSMLineDTO> > CreateNetworkRoutesListAsync(string network, DateTime?dateTime)
        {
            var query = $"<osm-script output=\"json\"><query type=\"relation\">";

            if (dateTime.HasValue)
            {
                query = $"<osm-script output=\"json\" date=\"{dateTime:o}\"><query type=\"relation\">";
            }
            query += $"<has-kv k=\"network\" modv=\"\" regv=\"" + network + "\"/>";
            query += $"<has-kv k=\"route\"/>";
            query += $"</query><print mode=\"tags\" order=\"quadtile\"/></osm-script>";
            string text = null;

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("User-Agent", "OVDB");
                var response = await httpClient.PostAsync("https://overpass-api.de/api/interpreter", new StringContent(query));

                if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
                {
                    return(null);
                }
                text = await response.Content.ReadAsStringAsync();
            }

            var lines        = JsonConvert.DeserializeObject <OsmLinesList>(text);
            var responseList = new List <OSMLineDTO>();

            lines.Elements = lines.Elements.OrderBy(e => { if (e.Tags.ContainsKey("name"))
                                                           {
                                                               return(e.Tags["name"]);
                                                           }
                                                           return(""); }).ToList();


            lines.Elements.ForEach(l =>
            {
                var element = new OSMLineDTO();
                if (l.Tags.ContainsKey("name"))
                {
                    element.Name = l.Tags["name"];
                }
                if (l.Tags.ContainsKey("description"))
                {
                    element.Description = l.Tags["description"];
                }
                if (l.Tags.ContainsKey("from"))
                {
                    element.From = l.Tags["from"];
                }
                element.Id = l.Id;
                if (l.Tags.ContainsKey("network"))
                {
                    element.Network = l.Tags["network"];
                }
                if (l.Tags.ContainsKey("operator"))
                {
                    element.Operator = l.Tags["operator"];
                }
                if (l.Tags.ContainsKey("to"))
                {
                    element.To = l.Tags["to"];
                }
                if (l.Tags.ContainsKey("fixme"))
                {
                    element.PotentialErrors = l.Tags["fixme"];
                }
                if (l.Tags.ContainsKey("colour"))
                {
                    element.Colour = l.Tags["colour"];
                }
                responseList.Add(element);
            });
            return(responseList);;
        }
Esempio n. 3
0
        private static async Task <List <OSMLineDTO> > CreateRoutesListAsync(string reference, OSMRouteType?routeType, string network, DateTime?dateTime)
        {
            var query = $"<osm-script output=\"json\"><query type=\"relation\">";

            if (dateTime.HasValue)
            {
                query = $"<osm-script output=\"json\" date=\"{dateTime.Value.ToUniversalTime():o}\"><query type=\"relation\">";
            }
            query += $"<has-kv k=\"ref\" v=\"" + reference + "\"/>";
            if (routeType != null && routeType != OSMRouteType.not_specified)
            {
                query += $"<has-kv k=\"route\" v=\"" + routeType.ToString() + "\"/>";
            }
            if (!string.IsNullOrWhiteSpace(network))
            {
                query += $"<has-kv k=\"network\" modv=\"\" regv=\"" + network + "\"/>";
            }
            query += $"</query><print mode=\"tags\" geometry=\"center\" order=\"quadtile\"/></osm-script>";
            string text = null;

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("User-Agent", "OVDB/1.0 (contact-me [email protected])");
                try
                {
                    var response = await httpClient.PostAsync("https://overpass-api.de/api/interpreter", new StringContent(query));

                    if (response.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
                    {
                        return(null);
                    }
                    text = await response.Content.ReadAsStringAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    throw;
                }
            }

            var lines        = JsonConvert.DeserializeObject <OsmLinesList>(text);
            var responseList = new List <OSMLineDTO>();

            lines.Elements = lines.Elements.OrderBy(e =>
            {
                if (e.Center == null)
                {
                    return(double.MaxValue / 10);
                }
                return(GeometryHelper.distance(e.Center.Lat, e.Center.Lon, 52.228936, 5.321492, 'k'));
            }).ToList();


            lines.Elements.ForEach(l =>
            {
                var element = new OSMLineDTO();
                if (l.Tags.ContainsKey("name"))
                {
                    element.Name = l.Tags["name"];
                }
                if (l.Tags.ContainsKey("description"))
                {
                    element.Description = l.Tags["description"];
                }
                if (l.Tags.ContainsKey("from"))
                {
                    element.From = l.Tags["from"];
                }
                element.Id = l.Id;
                if (l.Tags.ContainsKey("network"))
                {
                    element.Network = l.Tags["network"];
                }
                if (l.Tags.ContainsKey("operator"))
                {
                    element.Operator = l.Tags["operator"];
                }
                if (l.Tags.ContainsKey("to"))
                {
                    element.To = l.Tags["to"];
                }
                if (l.Tags.ContainsKey("fixme"))
                {
                    element.PotentialErrors = l.Tags["fixme"];
                }
                if (l.Tags.ContainsKey("colour"))
                {
                    element.Colour = l.Tags["colour"];
                }
                responseList.Add(element);
            });
            return(responseList);
        }
Esempio n. 4
0
        public async Task <ActionResult> Read(int id, [FromQuery] long from, [FromQuery] long to, [FromQuery] DateTime?dateTime)
        {
            var idCache = id + "|" + (dateTime.HasValue ? dateTime.Value.ToString("o") : "");

            var osm = await _cache.GetOrCreateAsync(idCache, async i => await CreateCache(id, i, dateTime));

            if (osm == null)
            {
                _cache.Remove(id);
                await Task.Delay(1000);

                osm = await _cache.GetOrCreateAsync(idCache, async i => await CreateCache(id, i, dateTime));
            }
            var relation = osm.Elements.SingleOrDefault(e => e.Type == TypeEnum.Relation);
            var stops    = new List <Element>();
            var lists    = new List <List <IPosition> >();

            relation.Members.ForEach(way =>
            {
                if (way.Role.Contains("Platform", StringComparison.OrdinalIgnoreCase) || way.Role.Contains("Stop", StringComparison.OrdinalIgnoreCase))
                {
                    HandleNewStop(way, osm, stops);
                }
                else
                {
                    var wayOsm  = osm.Elements.Where(e => e.Id == way.Ref).ToList();
                    var nodes   = wayOsm.FirstOrDefault().Nodes;
                    var subList = new List <IPosition>();
                    if (nodes != null)
                    {
                        nodes.ForEach(n =>
                        {
                            var node = osm.Elements.FirstOrDefault(e => e.Id == n);
                            subList.Add(new Position(node.Lat.GetValueOrDefault(), node.Lon.GetValueOrDefault()));
                        });
                        if (nodes.Any())
                        {
                            lists.Add(subList);
                        }
                    }
                }
            });
            var element = new OSMLineDTO();

            if (relation.Tags.ContainsKey("name"))
            {
                element.Name = relation.Tags["name"];
            }
            if (relation.Tags.ContainsKey("description"))
            {
                element.Description = relation.Tags["description"];
            }
            if (relation.Tags.ContainsKey("from"))
            {
                element.From = relation.Tags["from"];
            }
            element.Id = relation.Id;
            if (relation.Tags.ContainsKey("network"))
            {
                element.Network = relation.Tags["network"];
            }
            if (relation.Tags.ContainsKey("operator"))
            {
                element.Operator = relation.Tags["operator"];
            }
            if (relation.Tags.ContainsKey("to"))
            {
                element.To = relation.Tags["to"];
            }
            if (relation.Tags.ContainsKey("ref"))
            {
                element.Ref = relation.Tags["ref"];
            }
            if (relation.Tags.ContainsKey("fixme"))
            {
                element.PotentialErrors = relation.Tags["fixme"];
            }
            if (relation.Tags.ContainsKey("colour"))
            {
                element.Colour = relation.Tags["colour"];
            }
            if (relation.Tags.ContainsKey("ref") && relation.Tags.ContainsKey("to") && relation.Tags.ContainsKey("to"))
            {
                element.Name = relation.Tags["ref"] + ": " + relation.Tags["from"] + " => " + relation.Tags["to"];
            }
            lists = SortListOfList(lists);
            var oneList        = lists.SelectMany(i => i).ToList();
            var pointts2       = oneList.Select(l => l.Longitude.ToString(CultureInfo.InvariantCulture) + ", " + l.Latitude.ToString(CultureInfo.InvariantCulture)).ToList();
            var pointts2String = string.Join("\n", pointts2);

            var fromStop = stops.FirstOrDefault(s => s.Id == from);
            var toStop   = stops.LastOrDefault(s => s.Id == to);

            if (fromStop == null || toStop == null)
            {
                element.GeoJson = CoordsToGeoJson(oneList);
                return(Ok(element));
            }
            if (relation.Tags.ContainsKey("ref") && relation.Tags.ContainsKey("to") && relation.Tags.ContainsKey("to"))
            {
                element.Name = relation.Tags["ref"] + ": " + fromStop.Tags["friendlyName"] + " => " + toStop.Tags["friendlyName"];
            }
            var       min         = double.MaxValue;
            IPosition minPosition = null;

            oneList.ToList().ForEach(s =>
            {
                var distance = GeometryHelper.distance(s.Latitude, s.Longitude, fromStop.Lat.Value, fromStop.Lon.Value, 'k');
                if (distance < min)
                {
                    min         = distance;
                    minPosition = s;
                }
            });
            var       toMin         = double.MaxValue;
            IPosition toMinPosition = null;

            oneList.ToList().ForEach(s =>
            {
                var distance = GeometryHelper.distance(s.Latitude, s.Longitude, toStop.Lat.Value, toStop.Lon.Value, 'k');
                if (distance < toMin)
                {
                    toMin         = distance;
                    toMinPosition = s;
                }
            });


            var startIndex = oneList.ToList().IndexOf(minPosition);
            var toIndex    = oneList.ToList().IndexOf(toMinPosition);

            if (fromStop.Id == stops.First().Id&& startIndex < 20)
            {
                startIndex = 0;
            }

            if (toStop.Id == stops.Last().Id&& toIndex > oneList.Count - 20)
            {
                toIndex = oneList.Count - 1;
            }

            if (toIndex == startIndex)
            {
                return(Ok(element));
            }
            var reverseFromToOrder = false;

            if (startIndex > toIndex)
            {
                var temp = startIndex;
                startIndex         = toIndex;
                toIndex            = temp;
                reverseFromToOrder = true;

                if (relation.Tags.ContainsKey("ref") && relation.Tags.ContainsKey("to") && relation.Tags.ContainsKey("to"))
                {
                    element.Name = relation.Tags["ref"] + ": " + toStop.Tags["friendlyName"] + " => " + fromStop.Tags["friendlyName"];
                }
            }


            var filteredList       = oneList.Take(toIndex + 1).Skip(startIndex).ToList();
            var filteredPoints     = filteredList.Select(l => l.Longitude.ToString(CultureInfo.InvariantCulture) + ", " + l.Latitude.ToString(CultureInfo.InvariantCulture)).ToList();
            var filteredPointsList = string.Join("\n", filteredPoints);

            element.GeoJson = CoordsToGeoJson(filteredList);
            if (reverseFromToOrder)
            {
                element.From = toStop.Tags["friendlyName"];
                element.To   = fromStop.Tags["friendlyName"];
            }
            else
            {
                element.From = fromStop.Tags["friendlyName"];
                element.To   = toStop.Tags["friendlyName"];
            }
            return(Ok(element));
        }