Ejemplo n.º 1
0
        internal void GeneratePoi(GeoCoordinateBox box, 
            List<PointPoi> list,
            RelativeDirection direction)
        {
            // create a new instruction first.
            Instruction instruction = new Instruction(box, list);
            Instruction direction_instruction = null;

            // pass the instruction to the languate generator.
            if (direction == null)
            {
                instruction = _generator.GeneratePoi(instruction, list, null);
            }
            else
            {
                // create a direction instruction.
                if (direction.Direction == RelativeDirectionEnum.TurnBack)
                {
                    direction_instruction = new Instruction(box, list);
                    direction_instruction = _generator.GenerateSimpleTurn(direction_instruction, direction.Direction);
                }

                // generates the instructions.
                instruction = _generator.GeneratePoi(instruction, list, null);
            }

            // add the instruction to the instructions list.
            _instructions.Add(instruction);

            // add the direction instruction.
            if (direction_instruction != null)
            {
                _instructions.Add(direction_instruction);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Returns the data from the given data source that is inside the given box.
        /// </summary>
        /// <param name="dataSourceName">The name of the datasource.</param>
        /// <param name="box">The bounding box.</param>
        /// <returns></returns>
        public string RequestData(string dataSourceName, GeoCoordinateBox box)
        {
            string dataPath = ConfigurationManager.AppSettings["datapath"];

            // check of the file exists.
            var pbfFile = new FileInfo(dataPath + dataSourceName + ".pbf");
            var xmlFile = new FileInfo(dataPath + dataSourceName);

            DataProcessorSource source = null;
            FileStream sourceStream = null;
            NamedSource namedSource;
            if (pbfFile.Exists)
            { // first try PBF: more efficient.
                // create PBF source.
                sourceStream = pbfFile.OpenRead();
                source = new PBFDataProcessorSource(sourceStream);

                // create filter.
                DataProcessorFilter filter = new DataProcessorFilterBoundingBox(box);
                filter.RegisterSource(source);
                source = filter;
            }
            else if (xmlFile.Exists)
            { // then try XML.
                // create XML source.
                sourceStream = xmlFile.OpenRead();
                source = new XmlDataProcessorSource(sourceStream);

                // create filter.
                DataProcessorFilter filter = new DataProcessorFilterBoundingBox(box);
                filter.RegisterSource(source);
                source = filter;
            }
            else if (NamedSourceCollection.Instance.TryGetSource(dataSourceName, out namedSource))
            { // then try a named source.
                source = namedSource.Get(box);
            }
            else
            { // oeps! file or named source not found!
                throw new FileNotFoundException("File or name source {0} not found!", dataSourceName);
            }

            // create the target.
            var result = new StringBuilder();
            var writer = new StringWriter(result);
            var target = new XmlDataProcessorTarget(writer);

            // execute the processing.
            target.RegisterSource(source);
            target.Pull();

            // close the source stream if needed.
            if (sourceStream != null)
            {
                sourceStream.Close();
                sourceStream.Dispose();
            }

            return result.ToString();
        }
Ejemplo n.º 3
0
        internal void GenerateImmidiateTurn(GeoCoordinateBox box,
            List<KeyValuePair<string, string>> before_name, RelativeDirection first_direction, int first_street_count_to,
            RelativeDirection second_direction, List<KeyValuePair<string, string>> first_street_to, List<KeyValuePair<string, string>> second_street_to, List<PointPoi> list)
        {
            // create a new instruction first.
            Instruction instruction = new Instruction(box);

            // pass the instruction to the language generator.
            instruction = _generator.GenerateImmidiateTurn(
                instruction, first_street_count_to, first_street_to, first_direction, second_street_to, second_direction);

            // add the instruction to the instructions list.
            _instructions.Add(instruction);
        }
Ejemplo n.º 4
0
        public override void Succes()
        {
            List<Routing.ArcAggregation.Output.PointPoi> pois =
                (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point.Points;

            // construct the box indicating the location of the resulting find by this machine.
            GeoCoordinate point1 = pois[0].Location;
            GeoCoordinateBox box = new GeoCoordinateBox(
                new GeoCoordinate(point1.Latitude - 0.001f, point1.Longitude - 0.001f),
                new GeoCoordinate(point1.Latitude + 0.001f, point1.Longitude + 0.001f));

            // let the scentence planner generate the correct information.
            this.Planner.SentencePlanner.GeneratePoi(box, pois, null);
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Creates an image that scales.
 /// </summary>
 /// <param name="top"></param>
 /// <param name="bottom"></param>
 /// <param name="left"></param>
 /// <param name="right"></param>
 /// <param name="image"></param>
 public ElementImage(
     double top,
     double bottom,
     double left,
     double right,
     Image image,
     double? min_zoom,
     double? max_zoom)
     : base(min_zoom, max_zoom)
 {
     _image = image;
     GeoCoordinate top_left = new GeoCoordinate(top, left);
     GeoCoordinate bottom_right = new GeoCoordinate(bottom, right);
     _box = new GeoCoordinateBox(top_left, bottom_right);
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Generates a turn instruction.
        /// </summary>
        /// <param name="entryIdx"></param>
        /// <param name="box"></param>
        /// <param name="direction"></param>
        /// <param name="streetCountTurn"></param>
        /// <param name="streetCountBeforeTurn"></param>
        /// <param name="streetFrom"></param>
        /// <param name="streetTo"></param>
        /// <param name="list"></param>
        internal void GenerateTurn(int entryIdx, GeoCoordinateBox box,
                                   RelativeDirection direction, int streetCountTurn, int streetCountBeforeTurn,
                                   TagsCollectionBase streetFrom, TagsCollectionBase streetTo, List <PointPoi> list)
        {
            // create a new instruction first.
            Instruction instruction = new Instruction(entryIdx, box, list);

            // pass the instruction to the languate generator.
            // test if the street is the same but a turn needs to be taken anyway.
            if (streetFrom == streetTo)
            {
                if (streetCountTurn == 0)
                {// there are no other streets between the one being turned into and the street coming from in the same
                    // direction as the turn.
                    instruction = _generator.GenerateDirectFollowTurn(
                        instruction, streetCountBeforeTurn, streetTo, direction.Direction, list);
                }
                else
                { // there is another street; this is tricky to explain.
                    instruction = _generator.GenerateIndirectFollowTurn(
                        instruction, streetCountTurn, streetCountBeforeTurn, streetTo, direction.Direction, list);
                }
            }
            else
            {
                if (streetCountTurn == 0)
                { // there are no other streets between the one being turned into and the street coming from in the same
                    // direction as the turn.
                    instruction = _generator.GenerateDirectTurn(
                        instruction, streetCountBeforeTurn, streetTo, direction.Direction, list);
                }
                else
                { // there is another street; this is tricky to explain.
                    instruction = _generator.GenerateIndirectTurn(
                        instruction, streetCountTurn, streetCountBeforeTurn, streetTo, direction.Direction, list);
                }
            }

            // add the instruction to the instructions list.
            _instructions.Add(instruction);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Called when this machine is succesfull.
        /// </summary>
        public override void Succes()
        {
            // get first point.
            AggregatedPoint firstPoint = null;

            if (this.FinalMessages[0] is MicroPlannerMessagePoint)
            { // machine started on a point.
                firstPoint = (this.FinalMessages[0] as MicroPlannerMessagePoint).Point;
            }
            else
            { // get the previous point.
                firstPoint = (this.FinalMessages[0] as MicroPlannerMessageArc).Arc.Previous;
            }

            var poisPoint   = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point;
            var previousArc = (this.FinalMessages[this.FinalMessages.Count - 2] as MicroPlannerMessageArc).Arc;

            // get the pois list.
            var pois = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point.Points;

            // get the angle from the pois point.
            var direction = poisPoint.Angle;

            // calculate the box.
            var coordinates = new List <GeoCoordinate>();

            foreach (Routing.ArcAggregation.Output.PointPoi poi in pois)
            {
                coordinates.Add(poi.Location);
            }
            coordinates.Add(poisPoint.Location);
            var box = new GeoCoordinateBox(coordinates.ToArray());

            // let the scentence planner generate the correct information.
            var metaData = new Dictionary <string, object>();

            metaData["direction"] = direction;
            metaData["pois"]      = pois;
            metaData["type"]      = "poi";
            this.Planner.SentencePlanner.GenerateInstruction(metaData, firstPoint.SegmentIdx, poisPoint.SegmentIdx, box, pois);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Returns all objects within the given bounding box.
        /// </summary>
        /// <param name="box"></param>
        /// <returns></returns>
        public List <OsmGeo> BoundingBoxGet(GeoCoordinateBox box)
        {
            string response = this.DoApiCall(false, string.Format(
                                                 "/api/0.6/map?bbox={0},{1},{2},{3}",
                                                 box.MinLon.ToString(System.Globalization.CultureInfo.InvariantCulture),
                                                 box.MinLat.ToString(System.Globalization.CultureInfo.InvariantCulture),
                                                 box.MaxLon.ToString(System.Globalization.CultureInfo.InvariantCulture),
                                                 box.MaxLat.ToString(System.Globalization.CultureInfo.InvariantCulture)), Method.GET, null);

            if (response != null && response.Trim().Length > 0)
            {
                XmlReaderSource xml_source = new XmlReaderSource(XmlReader.Create(new StringReader(response)));
                OsmDocument     osm        = new OsmDocument(xml_source);

                List <OsmGeo>             box_objects = new List <OsmGeo>();
                OsmSharp.Osm.Xml.v0_6.osm xml_osm     = (osm.Osm as OsmSharp.Osm.Xml.v0_6.osm);
                if (xml_osm.node != null)
                {
                    foreach (Osm.Xml.v0_6.node xml_node in xml_osm.node)
                    {
                        box_objects.Add(this.Convertv6XmlNode(xml_node));
                    }
                }
                if (xml_osm.way != null)
                {
                    foreach (Osm.Xml.v0_6.way xml_way in xml_osm.way)
                    {
                        box_objects.Add(this.Convertv6XmlWay(xml_way));
                    }
                }
                if (xml_osm.relation != null)
                {
                    foreach (Osm.Xml.v0_6.relation xml_relation in xml_osm.relation)
                    {
                        box_objects.Add(this.Convertv6XmlRelation(xml_relation));
                    }
                }
                return(box_objects);
            }
            return(null);
        }
Ejemplo n.º 9
0
        public override void Succes()
        {
            // get the last arc and the last point.
            AggregatedArc   latestArc         = (this.FinalMessages[this.FinalMessages.Count - 2] as MicroPlannerMessageArc).Arc;
            AggregatedPoint latestPoint       = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point;
            AggregatedArc   secondLatestArc   = (this.FinalMessages[this.FinalMessages.Count - 4] as MicroPlannerMessageArc).Arc;
            AggregatedPoint secondLatestPoint = (this.FinalMessages[this.FinalMessages.Count - 3] as MicroPlannerMessagePoint).Point;

            // count the number of streets in the same turning direction as the turn
            // that was found.
            int count = 0;

            if (MicroPlannerHelper.IsLeft(latestPoint.Angle.Direction, this.Planner.Interpreter))
            {
                count = MicroPlannerHelper.GetLeft(this.FinalMessages, this.Planner.Interpreter);
            }
            else if (MicroPlannerHelper.IsRight(latestPoint.Angle.Direction, this.Planner.Interpreter))
            {
                count = MicroPlannerHelper.GetRight(this.FinalMessages, this.Planner.Interpreter);
            }

            // construct the box indicating the location of the resulting find by this machine.
            GeoCoordinate    point1 = latestPoint.Location;
            GeoCoordinateBox box    = new GeoCoordinateBox(
                new GeoCoordinate(point1.Latitude - 0.001f, point1.Longitude - 0.001f),
                new GeoCoordinate(point1.Latitude + 0.001f, point1.Longitude + 0.001f));

            // get all the names/direction/counts.
            TagsCollectionBase nextName    = latestPoint.Next.Tags;
            TagsCollectionBase betweenName = latestArc.Tags;
            TagsCollectionBase beforeName  = secondLatestArc.Tags;

            int firstCount = count;

            RelativeDirection firstTurn  = secondLatestPoint.Angle;
            RelativeDirection secondTurn = latestPoint.Angle;

            // let the scentence planner generate the correct information.
            this.Planner.SentencePlanner.GenerateImmidiateTurn(latestPoint.EntryIdx, box, beforeName,
                                                               firstTurn, firstCount, secondTurn, betweenName, nextName, latestPoint.Points);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Returns all edges inside the given boundingbox.
        /// </summary>
        /// <param name="box"></param>
        /// <returns></returns>
        public KeyValuePair <uint, KeyValuePair <uint, CHEdgeData> >[] GetArcs(
            GeoCoordinateBox box)
        {
            // load the missing tiles.
            this.LoadMissingTile(box);

            // get all the vertices in the given box.
            IEnumerable <uint> vertices = _vertexIndex.GetInside(
                box);

            // loop over all vertices and get the arcs.
            var arcs = new List <KeyValuePair <uint, KeyValuePair <uint, CHEdgeData> > >();

            foreach (uint vertexId in vertices)
            {
                var location = _coordinates[(int)vertexId];
                if (location != null)
                {
                    // load tile if needed.
                    this.LoadMissingTile(new GeoCoordinate(
                                             location.Latitude, location.Longitude));

                    // get the arcs and return.
                    if (_vertices.Length > vertexId)
                    {
                        var vertex = _vertices[(int)vertexId];
                        if (vertex != null &&
                            vertex.Arcs != null)
                        {
                            KeyValuePair <uint, CHEdgeData>[] localArcs = vertex.Arcs;
                            foreach (KeyValuePair <uint, CHEdgeData> localArc in localArcs)
                            {
                                arcs.Add(new KeyValuePair <uint, KeyValuePair <uint, CHEdgeData> >(
                                             vertexId, localArc));
                            }
                        }
                    }
                }
            }
            return(arcs.ToArray());
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Returns all arcs inside the given bounding box.
        /// </summary>
        /// <param name="box"></param>
        /// <returns></returns>
        public KeyValuePair <uint, KeyValuePair <uint, TEdgeData> >[] GetArcs(
            GeoCoordinateBox box)
        {
            // get all the vertices in the given box.
            IEnumerable <uint> vertices = _vertexIndex.GetInside(
                box);

            // loop over all vertices and get the arcs.
            var arcs = new List <KeyValuePair <uint, KeyValuePair <uint, TEdgeData> > >();

            foreach (uint vertex in vertices)
            {
                KeyValuePair <uint, TEdgeData>[] localArcs = this.GetArcs(vertex);
                foreach (KeyValuePair <uint, TEdgeData> localArc in localArcs)
                {
                    arcs.Add(new KeyValuePair <uint, KeyValuePair <uint, TEdgeData> >(
                                 vertex, localArc));
                }
            }
            return(arcs.ToArray());
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Adds a point.
        /// </summary>
        public void AddPoint(GeoCoordinate coordinate, float sizePixels, int color)
        {
            if (coordinate == null)
            {
                throw new ArgumentNullException();
            }

            // update envelope.
            if (_envelope == null)
            { // create initial envelope.
                _envelope = new GeoCoordinateBox(coordinate, coordinate);
            }
            // also include the current point.
            _envelope.ExpandWith(coordinate);

            double[] projectedCoordinates = _projection.ToPixel(coordinate);
            uint     pointId = _scene.AddPoint(projectedCoordinates[0], projectedCoordinates[1]);

            _scene.AddStylePoint(pointId, 0, float.MinValue, float.MaxValue, color, sizePixels);
            this.RaiseLayerChanged();
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Builds the scene.
        /// </summary>
        /// <param name="map"></param>
        /// <param name="zoomFactor"></param>
        /// <param name="center"></param>
        /// <param name="view"></param>
        private void BuildScene(Map map, float zoomFactor, GeoCoordinate center, View2D view)
        {
            // build the boundingbox.
            var viewBox = view.OuterBox;
            var box     = new GeoCoordinateBox(map.Projection.ToGeoCoordinates(viewBox.Min[0], viewBox.Min[1]),
                                               map.Projection.ToGeoCoordinates(viewBox.Max[0], viewBox.Max[1]));
            var zoomLevel = (int)map.Projection.ToZoomLevel(zoomFactor);

            if (_lastBox != null && _lastBox.Contains(box) &&
                zoomLevel == _lastZoom)
            {
                return;
            }
            _lastBox  = box;
            _lastZoom = zoomLevel;

            lock (_index)
            {
                _primitives = _index.Get(view, zoomFactor);
            }
        }
Ejemplo n.º 14
0
        void AddMarkers()
        {
            var from = new GeoCoordinate(51.261203, 4.780760);
            var to   = new GeoCoordinate(51.267797, 4.801362);

            var box = new GeoCoordinateBox(from, to);

            _mapView.ClearMarkers();

            MapMarker marker;

            for (int idx = 0; idx < 20; idx++)
            {
                var pos = box.GenerateRandomIn();
                marker = _mapView.AddMarker(pos);
                var popupTextView = new UITextView();
                popupTextView.Text            = "Hey, this is popup text!";
                popupTextView.BackgroundColor = UIColor.FromWhiteAlpha(0.5f, 0.5f);
                marker.AddPopup(popupTextView, 100, 100);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Returns all arcs inside the given bounding box.
        /// </summary>
        /// <param name="box"></param>
        /// <returns></returns>
        public override INeighbourEnumerator <TEdgeData> GetEdges(
            GeoCoordinateBox box)
        {
            if (_vertexIndex == null)
            {
                // rebuild on-the-fly.
                this.RebuildVertexIndex();
            }

            // get all the vertices in the given box.
            var vertices = _vertexIndex.GetInside(
                box);

            // loop over all vertices and get the arcs.
            var neighbours = new List <Tuple <uint, uint, uint, TEdgeData> >();

            foreach (uint vertexId in vertices)
            {
                var  localArcs = this.GetEdges(vertexId);
                uint arcIdx    = 0;
                while (localArcs.MoveNext())
                {
                    if (localArcs.EdgeData.RepresentsNeighbourRelations)
                    {
                        //if (localArcs.isInverted)
                        //{
                        //    neighbours.Add(new Tuple<uint, uint, uint, TEdgeData>(vertexId, localArcs.Neighbour, arcIdx,
                        //        (TEdgeData)localArcs.EdgeData.Reverse()));
                        //}
                        //else
                        //{ // not inverted.
                        neighbours.Add(new Tuple <uint, uint, uint, TEdgeData>(vertexId, localArcs.Neighbour, arcIdx,
                                                                               localArcs.EdgeData));
                        //}
                    }
                    arcIdx++;
                }
            }
            return(new NeighbourEnumerator(this, neighbours));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Adds a new OsmSharpRoute.
        /// </summary>
        /// <param name="route">Stream.</param>
        /// <param name="argb">Stream.</param>
        /// <param name="width"></param>
        public void AddRoute(Route route, int argb, double width)
        {
            if (route != null &&
                route.Segments != null &&
                route.Segments.Length > 0)
            { // there are entries.
                // get x/y.
                var x = new double[route.Segments.Length];
                var y = new double[route.Segments.Length];
                for (int idx = 0; idx < route.Segments.Length; idx++)
                {
                    x[idx] = _projection.LongitudeToX(
                        route.Segments[idx].Longitude);
                    y[idx] = _projection.LatitudeToY(
                        route.Segments[idx].Latitude);

                    // update envelope.
                    if (_envelope == null)
                    { // create initial envelope.
                        _envelope = new GeoCoordinateBox(
                            new GeoCoordinate(route.Segments[idx].Latitude, route.Segments[idx].Longitude),
                            new GeoCoordinate(route.Segments[idx].Latitude, route.Segments[idx].Longitude));
                    }
                    // also include the current point.
                    _envelope.ExpandWith(new GeoCoordinate(route.Segments[idx].Latitude, route.Segments[idx].Longitude));
                }

                // set the default color if none is given.
                var color    = SimpleColor.FromArgb(argb);
                var pointsId = _scene.AddPoints(x, y);
                if (pointsId.HasValue)
                {
                    _scene.AddStyleLine(pointsId.Value, 0, float.MinValue, float.MaxValue,
                                        color.Value, (float)width, Renderer.Primitives.LineJoin.Round, null);
                }
            }

            this.RaiseLayerChanged();
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Returns all edges inside the given boundingbox.
        /// </summary>
        /// <param name="box"></param>
        /// <returns></returns>
        public INeighbourEnumerator <LiveEdge> GetEdges(
            GeoCoordinateBox box)
        {
            // load the missing tiles.
            this.LoadMissingTile(box);

            // get all the vertices in the given box.
            var vertices = _vertexIndex.GetInside(box);

            // loop over all vertices and get the arcs.
            var neighbours = new List <Tuple <uint, uint, uint, LiveEdge> >();

            foreach (uint vertexId in vertices)
            {
                var location = _coordinates[(int)vertexId];
                if (location != null)
                {
                    //// load tile if needed.
                    //this.LoadMissingTile(new GeoCoordinate(
                    //    location.Latitude, location.Longitude));

                    // get the arcs and return.
                    if (_vertices.Length > vertexId)
                    {
                        var vertex = _vertices[(int)vertexId];
                        if (vertex != null &&
                            vertex.Arcs != null)
                        {
                            var localArcs = vertex.Arcs;
                            for (int arcIdx = 0; arcIdx < vertex.Arcs.Length; arcIdx++)
                            {
                                neighbours.Add(new Tuple <uint, uint, uint, LiveEdge>(vertexId, (uint)arcIdx, localArcs[arcIdx].Item1, localArcs[arcIdx].Item2));
                            }
                        }
                    }
                }
            }
            return(new NeighbourEnumerator(this, neighbours));
        }
Ejemplo n.º 18
0
        public override IList <OsmGeo> Get(GeoCoordinateBox box, Filter filter)
        {
            IList <OsmGeo> osmGeoList = this._source.Get(box, filter);
            long?          id;

            foreach (OsmGeo osmGeo in (IEnumerable <OsmGeo>)osmGeoList)
            {
                switch (osmGeo.Type)
                {
                case OsmGeoType.Node:
                    LRUCache <long, Node> nodesCache = this._nodesCache;
                    id = osmGeo.Id;
                    long key1 = id.Value;
                    Node node = osmGeo as Node;
                    nodesCache.Add(key1, node);
                    continue;

                case OsmGeoType.Way:
                    LRUCache <long, Way> waysCache = this._waysCache;
                    id = osmGeo.Id;
                    long key2 = id.Value;
                    Way  way  = osmGeo as Way;
                    waysCache.Add(key2, way);
                    continue;

                case OsmGeoType.Relation:
                    LRUCache <long, Relation> relationsCache = this._relationsCache;
                    id = osmGeo.Id;
                    long     key3     = id.Value;
                    Relation relation = osmGeo as Relation;
                    relationsCache.Add(key3, relation);
                    continue;

                default:
                    continue;
                }
            }
            return(osmGeoList);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Returns all data in the given bounding box.
        /// </summary>
        /// <param name="box"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override IList <OsmGeo> Get(GeoCoordinateBox box, Filter filter)
        {
            IList <OsmGeo> objects = _source.Get(box, filter);

            foreach (OsmGeo osmGeo in objects)
            {
                switch (osmGeo.Type)
                {
                case OsmGeoType.Node:
                    _nodesCache.Add(osmGeo.Id.Value, osmGeo as Node);
                    break;

                case OsmGeoType.Way:
                    _waysCache.Add(osmGeo.Id.Value, osmGeo as Way);
                    break;

                case OsmGeoType.Relation:
                    _relationsCache.Add(osmGeo.Id.Value, osmGeo as Relation);
                    break;
                }
            }
            return(objects);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Builds the scene.
        /// </summary>
        /// <param name="map"></param>
        /// <param name="zoomFactor"></param>
        /// <param name="center"></param>
        /// <param name="view"></param>
        private void BuildScene(Map map, float zoomFactor, GeoCoordinate center, View2D view)
        {
            // build the boundingbox.
            var viewBox = view.OuterBox;
            var box     = new GeoCoordinateBox(map.Projection.ToGeoCoordinates(viewBox.Min [0], viewBox.Min [1]),
                                               map.Projection.ToGeoCoordinates(viewBox.Max [0], viewBox.Max [1]));
            var zoomLevel = (int)map.Projection.ToZoomLevel(zoomFactor);

            if (_lastBox != null && _lastBox.IsInside(box) &&
                zoomLevel == _lastZoom)
            {
                return;
            }
            _lastBox  = box;
            _lastZoom = zoomLevel;

            // reset the scene.
            _scene2DSimple = new Scene2DSimple();

            // get from the index.
            this.Scene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value;
            _index.Get(_scene2DSimple, view, zoomFactor);
        }
Ejemplo n.º 21
0
        public override void Succes()
        {
            OsmSharp.Routing.ArcAggregation.Output.AggregatedPoint pois_point = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point;
            OsmSharp.Routing.ArcAggregation.Output.AggregatedArc previous_arc = (this.FinalMessages[this.FinalMessages.Count - 2] as MicroPlannerMessageArc).Arc;

            // get the pois list.
            List<Routing.ArcAggregation.Output.PointPoi> pois = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point.Points;

            // get the angle from the pois point.
            RelativeDirection direction = pois_point.Angle;

            // calculate the box.
            List<GeoCoordinate> coordinates = new List<GeoCoordinate>();
            foreach (Routing.ArcAggregation.Output.PointPoi poi in pois)
            {
                coordinates.Add(poi.Location);
            }
            coordinates.Add(pois_point.Location);
            GeoCoordinateBox box = new GeoCoordinateBox(coordinates.ToArray());

            // let the scentence planner generate the correct information.
            this.Planner.SentencePlanner.GeneratePoi(box, pois, direction);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Loads all vertices inside the given boundingbox.
        /// </summary>
        /// <param name="box"></param>
        /// <returns></returns>
        private List <uint> LoadVerticesIn(GeoCoordinateBox box)
        {
            List <uint> vertices = new List <uint>();
            TileRange   range    = TileRange.CreateAroundBoundingBox(box, _zoom);

            foreach (Tile tile in range)
            {
                CHVertexRegion region;
                if (!_regions.TryGet(tile.Id, out region))
                {
                    region = this.DeserializeRegion(tile.Id);
                    if (region != null)
                    {
                        _regions.Add(tile.Id, region);
                    }
                }
                if (region != null)
                {
                    vertices.AddRange(region.Vertices);
                }
            }
            return(vertices);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Tests routing from a serialized routing file.
        /// </summary>
        /// <param name="data"></param>
        /// <param name="box"></param>
        /// <param name="testCount"></param>
        public static void TestSerializedResolved(RouterDataSource <CHEdgeData> data,
                                                  GeoCoordinateBox box, int testCount = 100)
        {
            var successCount = 0;
            var totalCount   = testCount;

            var router = Router.CreateCHFrom(data, new CHRouter(), new OsmRoutingInterpreter());

            var performanceInfo = new PerformanceInfoConsumer("CHRouting");

            performanceInfo.Start();
            performanceInfo.Report("Routing {0} routes...", testCount);

            while (testCount > 0)
            {
                var point1 = router.Resolve(Vehicle.Car, box.GenerateRandomIn());
                var point2 = router.Resolve(Vehicle.Car, box.GenerateRandomIn());

                Route route = null;
                if (point1 != null && point2 != null)
                {
                    route = router.Calculate(Vehicle.Car, point1, point2);
                }

                if (route != null)
                {
                    successCount++;
                }
                testCount--;
            }

            performanceInfo.Stop();

            OsmSharp.Logging.Log.TraceEvent("CHRouting", OsmSharp.Logging.TraceEventType.Information,
                                            string.Format("{0}/{1} routes successfull!", successCount, totalCount));
        }
Ejemplo n.º 24
0
        public override void Succes()
        {
            OsmSharp.Routing.ArcAggregation.Output.AggregatedPoint pois_point   = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point;
            OsmSharp.Routing.ArcAggregation.Output.AggregatedArc   previous_arc = (this.FinalMessages[this.FinalMessages.Count - 2] as MicroPlannerMessageArc).Arc;

            // get the pois list.
            List <Routing.ArcAggregation.Output.PointPoi> pois = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point.Points;

            // get the angle from the pois point.
            RelativeDirection direction = pois_point.Angle;

            // calculate the box.
            List <GeoCoordinate> coordinates = new List <GeoCoordinate>();

            foreach (Routing.ArcAggregation.Output.PointPoi poi in pois)
            {
                coordinates.Add(poi.Location);
            }
            coordinates.Add(pois_point.Location);
            GeoCoordinateBox box = new GeoCoordinateBox(coordinates.ToArray());

            // let the scentence planner generate the correct information.
            this.Planner.SentencePlanner.GeneratePoi(box, pois, direction);
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Creates a new instruction with only a location.
 /// </summary>
 /// <param name="location"></param>
 public Instruction(GeoCoordinateBox location)
 {
     this.Location = location;
 }
        /// <summary>
        /// Filters the geo objects in the changeset and omits the ones not inside the bb.
        /// </summary>
        /// <param name="simpleChangeSet"></param>
        /// <returns></returns>
        private KeyValuePair<SimpleChangeSet, GeoCoordinateBox> FilterChanges(SimpleChangeSet simpleChangeSet)
        {
            List<GeoCoordinate> changes_coordinates = new List<GeoCoordinate>();

            SimpleChangeSet filtered_changeset = new SimpleChangeSet();
            filtered_changeset.Changes = new List<SimpleChange>();

            // keep a list of tested relation to prevent circular references from hanging this process.
            _tested_relations = new List<long>();

            // keep all the objects that could not be checked and check them later.
            List<KeyValuePair<SimpleOsmGeo, SimpleChange>> objects_not_checked = new List<KeyValuePair<SimpleOsmGeo, SimpleChange>>();

            // loop over all objects inside this box and if they are nodes they can be checked.
            HashSet<long> nodes_inside = new HashSet<long>(); // keep track of all the nodes inside for quick checks later!
            foreach (SimpleChange change in simpleChangeSet.Changes)
            {
                // keep the changed nodes that are ok for the filter.
                List<SimpleOsmGeo> nodes_changed = new List<SimpleOsmGeo>();

                // loop over all objects in this set and keep the nodes.
                foreach (SimpleOsmGeo geo in change.OsmGeo)
                {
                    if (geo is SimpleNode)
                    {
                        SimpleNode node = geo as SimpleNode;
                        GeoCoordinate coord = new GeoCoordinate(node.Latitude.Value, node.Longitude.Value);

                        if (_box.IsInsideAny(new OsmSharp.Tools.Math.PointF2D[] { coord }))
                        {
                            nodes_changed.Add(node);
                            nodes_inside.Add(node.Id.Value);
                            changes_coordinates.Add(coord);
                        }
                    }
                    else
                    {
                        objects_not_checked.Add(new  KeyValuePair<SimpleOsmGeo,SimpleChange>(geo as SimpleOsmGeo,change));
                    }
                }

                // are there changes in the nodes?
                if (nodes_changed.Count > 0)
                {
                   SimpleChange nodes_change = new SimpleChange();
                    nodes_change.OsmGeo = nodes_changed;
                    nodes_change.Type = change.Type;

                    filtered_changeset.Changes.Add(nodes_change);
                }
            }

            // try all ways.
            HashSet<long> ways_inside = new HashSet<long>(); // keep the ways inside for quick checks later!
            foreach(KeyValuePair<SimpleOsmGeo,SimpleChange> change_pair in objects_not_checked)
            {
                SimpleOsmGeo geo = change_pair.Key;
                SimpleChange change = change_pair.Value;

                // keep the changed ways that are ok for the filter.
                List<SimpleOsmGeo> ways_changed = new List<SimpleOsmGeo>();

                // detect if the way is part of the filter!
                if (geo is SimpleWay && (geo as SimpleWay).Nodes != null)
                {
                    // try the cached nodes.
                    foreach (long node_id in (geo as SimpleWay).Nodes)
                    {
                        if (nodes_inside.Contains(node_id))
                        {
                            ways_changed.Add(geo);
                            ways_inside.Add(geo.Id.Value);
                            break;
                        }
                    }

                    // first try to load the complete way.
                    OsmSharp.Osm.Way way = _data_source.GetWay(geo.Id.Value);
                    if (way != null && way.Nodes != null)
                    {
                        foreach (Osm.Node node in way.Nodes)
                        {
                            if (node != null)
                            { // only if the node is found
                                changes_coordinates.Add(node.Coordinate);
                                if (_box.IsInsideAny(new OsmSharp.Tools.Math.PointF2D[] { node.Coordinate }))
                                {
                                    changes_coordinates.Add(node.Coordinate);
                                    ways_changed.Add(geo);
                                    ways_inside.Add(geo.Id.Value);
                                    break;
                                }
                            }
                        }
                    }
                    if (change.Type == SimpleChangeType.Delete && way != null && (way.Nodes == null || way.Nodes.Count == 0))
                    { // alway delete empty ways!
                        ways_changed.Add(geo);
                        ways_inside.Add(geo.Id.Value);
                    }

                    // second try to load the nodes individually.
                    foreach (long node_id in (geo as SimpleWay).Nodes)
                    {
                        OsmSharp.Osm.Node node = _data_source.GetNode(node_id);
                        if (node != null)
                        { // only if the node is found
                            if (_box.IsInsideAny(new OsmSharp.Tools.Math.PointF2D[] { node.Coordinate }))
                            {
                                changes_coordinates.Add(node.Coordinate);
                                ways_changed.Add(geo);
                                ways_inside.Add(geo.Id.Value);
                                break;
                            }
                        }
                    }
                }

                // are there changes in the nodes?
                if (ways_changed.Count > 0)
                {
                    SimpleChange ways_change = new SimpleChange();
                    ways_change.OsmGeo = ways_changed;
                    ways_change.Type = change.Type;

                    filtered_changeset.Changes.Add(ways_change);
                }
            }

            // try all relations.
            foreach(KeyValuePair<SimpleOsmGeo,SimpleChange> change_pair in objects_not_checked)
            {
                SimpleOsmGeo geo = change_pair.Key;
                SimpleChange change = change_pair.Value;

                // keep the changed ways that are ok for the filter.
                List<SimpleOsmGeo> relations_changed = new List<SimpleOsmGeo>();

                // test all relations.
                if (geo is SimpleRelation)
                {
                    if (!_tested_relations.Contains(geo.Id.Value))
                    {
                        _tested_relations.Add(geo.Id.Value);
                        if (this.IsInsideBoxRelation((geo as SimpleRelation).Members,nodes_inside,ways_inside))
                        {
                            relations_changed.Add(geo);
                        }
                    }
                }

                // are there changes in the nodes?
                if (relations_changed.Count > 0)
                {
                    SimpleChange relations_change = new SimpleChange();
                    relations_change.OsmGeo = relations_changed;
                    relations_change.Type = change.Type;

                    filtered_changeset.Changes.Add(relations_change);
                }
            }

            // create bounding box of the found changes!
            GeoCoordinateBox box = null;
            if (changes_coordinates.Count > 0)
            {
                box = new GeoCoordinateBox(changes_coordinates);
            }
            return new KeyValuePair<SimpleChangeSet, GeoCoordinateBox>(filtered_changeset, box);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Returns all objects in the given bounding box that are valid according to the given filter.
        /// </summary>
        /// <param name="box"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public IList<OsmGeo> Get(GeoCoordinateBox box, Filter filter)
        {
            // initialize connection.
            OracleConnection con = this.CreateConnection();
            List<OsmGeo> base_list = new List<OsmGeo>();

            // calculate bounding box parameters to query db.
            long latitude_min = (long)(box.MinLat * 10000000.0);
            long longitude_min = (long)(box.MinLon * 10000000.0);
            long latitude_max = (long)(box.MaxLat * 10000000.0);
            long longitude_max = (long)(box.MaxLon * 10000000.0);

            // TODO: improve this to allow loading of bigger bb's.
            uint x_min = lon2x(box.MinLon);
            uint x_max = lon2x(box.MaxLon);
            uint y_min = lat2y(box.MinLat);
            uint y_max = lat2y(box.MaxLat);

            IList<long> boxes = new List<long>();

            for (uint x = x_min; x <= x_max; x++)
            {
                for (uint y = y_min; y <= y_max; y++)
                {
                    boxes.Add(this.xy2tile(x, y));
                }
            }

            // STEP 1: query nodes table.
            //id	latitude	longitude	changeset_id	visible	timestamp	tile	version
            string sql
                = "SELECT * FROM node WHERE (visible = 1) AND  (tile IN ({4})) AND (latitude BETWEEN {0} AND {1} AND longitude BETWEEN {2} AND {3})";
            sql = string.Format(sql,
                    latitude_min.ToString(),
                    latitude_max.ToString(),
                    longitude_min.ToString(),
                    longitude_max.ToString(),
                    this.ConstructIdList(boxes));

            // TODO: parameters.
            OracleCommand com = new OracleCommand(sql);
            com.Connection = con;
            OracleDataReader reader = com.ExecuteReader();
            Node node = null;
            Dictionary<long, Node> nodes = new Dictionary<long, Node>();
            List<long> node_ids = new List<long>();
            while (reader.Read())
            {
                // load/parse data.
                long returned_id = reader.GetInt64(0);
                int latitude_int = reader.GetInt32(1);
                int longitude_int = reader.GetInt32(2);
                long changeset_id = reader.GetInt64(3);
                bool visible = reader.GetInt64(4)==1;
                DateTime timestamp = reader.GetDateTime(5);
                long tile = reader.GetInt64(6);
                long version = reader.GetInt64(7);

                // create node.
                node = OsmBaseFactory.CreateNode(returned_id);
                node.Version = version;
                //node.UserId = user_id;
                node.TimeStamp = timestamp;
                node.ChangeSetId = changeset_id;
                node.Coordinate = new GeoCoordinate(
                    ((double)latitude_int) / 10000000.0, ((double)longitude_int) / 10000000.0);

                nodes.Add(node.Id,node);
                node_ids.Add(node.Id);
            }
            reader.Close();

            // STEP2: Load all node tags.
            this.LoadNodeTags(nodes);

            // STEP3: Load all ways for the given nodes.
            IList<Way> ways = this.GetWaysForNodes(nodes);

            // Add all objects to the base list.
            foreach (Node node_result in nodes.Values.ToList<Node>())
            {
                base_list.Add(node_result);
            }
            foreach (Way way in ways)
            {
                base_list.Add(way);
            }
            return base_list;
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Returns all the elements in the given box.
        /// </summary>
        /// <param name="coordinate"></param>
        /// <returns></returns>
        public MapQueryResult GetElementsAt(GeoCoordinateBox box, double zoom_factor)
        {
            List<IElement> elements = new List<IElement>();

            for(int idx = this.Layers.Count-1;idx>=0;idx--)
            {
                if (this.Layers[idx].Visible)
                { // only add elements from visible layers.
                    elements.AddRange(
                        this.Layers[idx].GetElements(box, zoom_factor));
                }
            }

            return new MapQueryResult(box.Center,elements);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Adds the given node.
        /// </summary>
        /// <param name="node"></param>
        public override void AddNode(Node node)
        {
            if (!_preIndexMode)
            {
                if (_nodesToCache != null &&
                    _nodesToCache.Contains(node.Id.Value))
                { // cache this node?
                    _dataCache.AddNode(node);
                }

                if (_preIndex != null && _preIndex.Contains(node.Id.Value))
                { // only save the coordinates for relevant nodes.
                  // save the node-coordinates.
                  // add the relevant nodes.

                    if (_box == null || _box.Contains(new GeoCoordinate((float)node.Latitude.Value, (float)node.Longitude.Value)))
                    { // the coordinate is acceptable.
                        _coordinates[node.Id.Value] = new GeoCoordinateSimple()
                        {
                            Latitude  = (float)node.Latitude.Value,
                            Longitude = (float)node.Longitude.Value
                        };
                        if (_coordinates.Count == _preIndex.Count)
                        {
                            _preIndex.Clear();
                            _preIndex = null;
                        }

                        if (_bounds == null)
                        { // create bounds.
                            _bounds = new GeoCoordinateBox(
                                new GeoCoordinate(node.Latitude.Value, node.Longitude.Value),
                                new GeoCoordinate(node.Latitude.Value, node.Longitude.Value));
                        }
                        else
                        { // expand bounds.
                            _bounds.ExpandWith(
                                new GeoCoordinate(node.Latitude.Value, node.Longitude.Value));
                        }

                        // add the node as a possible restriction.
                        if (_interpreter.IsRestriction(OsmGeoType.Node, node.Tags))
                        { // tests quickly if a given node is possibly a restriction.
                            List <Vehicle> vehicles = _interpreter.CalculateRestrictions(node);
                            if (vehicles != null &&
                                vehicles.Count > 0)
                            {                                                               // add all the restrictions.
                                uint   vertexId    = this.AddRoadNode(node.Id.Value).Value; // will always exists, has just been added to coordinates.
                                uint[] restriction = new uint[] { vertexId };
                                if (vehicles.Contains(null))
                                { // restriction is valid for all vehicles.
                                    _dynamicGraph.AddRestriction(restriction);
                                }
                                else
                                { // restriction is restricted to some vehicles only.
                                    foreach (Vehicle vehicle in vehicles)
                                    {
                                        _dynamicGraph.AddRestriction(vehicle, restriction);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Writes to the osm document.
        /// </summary>
        private void WriteToDocument()
        {
            _read = true;

            // collect all needed data.
            _bb = this.BoundingBox;

            // generate osm document.
            OsmSharp.Osm.Xml.v0_6.osm osm = new OsmSharp.Osm.Xml.v0_6.osm();

            // dimension the arrays.
            osm.node = new node[_nodes.Count];
            osm.way = new way[_ways.Count];
            osm.relation = new relation[_relations.Count];

            // iterate over all objects and convert them.
            IList<Node> nodes = _nodes.Values.ToList<Node>();
            for(int idx = 0;idx < nodes.Count;idx++)
            {
                node xml_obj = nodes[idx].ConvertTo();
                osm.node[idx] = xml_obj;
            }
            IList<Way> ways = _ways.Values.ToList<Way>();
            for (int idx = 0; idx < ways.Count; idx++)
            {
                way xml_obj = ways[idx].ConvertTo();
                osm.way[idx] = xml_obj;
            }
            IList<Relation> relations = _relations.Values.ToList<Relation>();
            for (int idx = 0; idx < relations.Count; idx++)
            {
                relation xml_obj = relations[idx].ConvertTo();
                osm.relation[idx] = xml_obj;
            }

            // convert the bounds as well.
            osm.bounds = _bb.ConvertTo();

            _document.Osm = osm;
            _document.Save();
        }
Ejemplo n.º 31
0
 public override bool IsVisibleIn(GeoCoordinateBox box)
 {
     return this.Line.Inside(box);
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Builds the scene.
        /// </summary>
        /// <param name="map"></param>
        /// <param name="zoomFactor"></param>
        /// <param name="center"></param>
        /// <param name="view"></param>
        private void BuildScene(Map map, float zoomFactor, GeoCoordinate center, View2D view)
        {
            // get the indexed object at this zoom.
            HashSet <ArcId> interpretedObjects;

            if (!_interpretedObjects.TryGetValue((int)zoomFactor, out interpretedObjects))
            {
                interpretedObjects = new HashSet <ArcId>();
                _interpretedObjects.Add((int)zoomFactor, interpretedObjects);
            }

            // build the boundingbox.
            var viewBox = view.OuterBox;
            var box     = new GeoCoordinateBox(map.Projection.ToGeoCoordinates(viewBox.Min[0], viewBox.Min[1]),
                                               map.Projection.ToGeoCoordinates(viewBox.Max[0], viewBox.Max[1]));

            foreach (var requestedBox in _requestedBoxes)
            {
                if (requestedBox.Contains(box))
                {
                    return;
                }
            }
            _requestedBoxes.Add(box);

            //// set the scene backcolor.
            //SimpleColor? color = _styleInterpreter.GetCanvasColor ();
            //_scene.BackColor = color.HasValue
            //                               ? color.Value.Value
            //                               : SimpleColor.FromArgb (0, 255, 255, 255).Value;

            // get data.
            foreach (var arc in _dataSource.GetEdges(box))
            {
                // translate each object into scene object.
                var arcId = new ArcId()
                {
                    Vertex1 = arc.Key,
                    Vertex2 = arc.Value.Key
                };
                if (!interpretedObjects.Contains(arcId))
                {
                    interpretedObjects.Add(arcId);

                    // create nodes.
                    float latitude, longitude;
                    _dataSource.GetVertex(arcId.Vertex1, out latitude, out longitude);
                    var node1 = new Node();
                    node1.Id        = arcId.Vertex1;
                    node1.Latitude  = latitude;
                    node1.Longitude = longitude;
                    _dataSource.GetVertex(arcId.Vertex2, out latitude, out longitude);
                    var node2 = new Node();
                    node2.Id        = arcId.Vertex2;
                    node2.Latitude  = latitude;
                    node2.Longitude = longitude;

                    // create way.
                    var way = CompleteWay.Create(-1);
                    if (arc.Value.Value.Forward)
                    {
                        way.Nodes.Add(node1);
                        way.Nodes.Add(node2);
                    }
                    else
                    {
                        way.Nodes.Add(node2);
                        way.Nodes.Add(node1);
                    }
                    way.Tags.AddOrReplace(_dataSource.TagsIndex.Get(arc.Value.Value.Tags));

                    _styleInterpreter.Translate(_scene, map.Projection, way);
                    interpretedObjects.Add(arcId);
                }
            }
        }
Ejemplo n.º 33
0
 /// <summary>
 /// Returns all the objects within a given bounding box and filtered by a given filter.
 /// </summary>
 /// <param name="box"></param>
 /// <param name="filter"></param>
 /// <returns></returns>
 public IList<OsmGeo> Get(GeoCoordinateBox box, Filter filter)
 {
     return new List<OsmGeo>();
 }
Ejemplo n.º 34
0
 /// <summary>
 /// Returns the elements in this layer.
 /// </summary>
 /// <param name="box"></param>
 /// <returns></returns>
 public IList<IElement> GetElements(GeoCoordinateBox box, double zoom_factor)
 {
     // TODO: implement the boundingbox cache.
     return _elements;
 }
Ejemplo n.º 35
0
        /// <summary>
        /// Reads all the data from the osm document if needed.
        /// </summary>
        private void ReadFromDocument()
        {
            if (!_read)
            {
                _read = true;

                OsmSharp.Osm.Xml.v0_6.osm osm = (_document.Osm as OsmSharp.Osm.Xml.v0_6.osm);

                if (osm != null)
                { // if there was no data to begin with.
                    if (osm.node != null)
                    {
                        foreach (Osm.Xml.v0_6.node node in osm.node)
                        {
                            Node new_node = node.ConvertFrom();
                            _nodes.Add(new_node.Id, new_node);

                            this.RegisterChangeSetId(new_node.ChangeSetId);
                        }
                    }

                    if (osm.way != null)
                    {
                        foreach (Osm.Xml.v0_6.way way in osm.way)
                        {
                            Way new_way = way.ConvertFrom(this);
                            if (new_way != null)
                            {
                                _ways.Add(new_way.Id, new_way);

                                this.RegisterNodeWayRelation(new_way);
                                this.RegisterChangeSetId(new_way.ChangeSetId);
                            }
                        }
                    }

                    if (osm.relation != null)
                    {
                        foreach (Osm.Xml.v0_6.relation relation in osm.relation)
                        {
                            Relation new_relation = relation.ConvertFrom(this, this, this);
                            if (new_relation != null)
                            {
                                _relations.Add(new_relation.Id, new_relation);

                                this.RegisterRelationMemberRelation(new_relation);
                                this.RegisterChangeSetId(new_relation.ChangeSetId);
                            }
                        }
                    }

                    _bb = osm.bounds.ConvertFrom();
                    if(_bb == null)
                    {
                        _bb = osm.bound.ConvertFrom();
                    }
                }
            }
        }
Ejemplo n.º 36
0
        public void TestGetBoundingBox()
        {
            var dataSource = new MemoryDataSource();

            // test nodes.
            Node node = new Node();

            node.Id        = 1;
            node.Longitude = -2;
            node.Latitude  = -1;
            dataSource.AddNode(node);

            node           = new Node();
            node.Id        = 2;
            node.Longitude = 2;
            node.Latitude  = 1;
            dataSource.AddNode(node);

            GeoCoordinateBox box = dataSource.BoundingBox;

            IList <OsmGeo> boxResults = dataSource.Get(box, null);

            Assert.IsNotNull(boxResults);
            Assert.AreEqual(1, boxResults.Count);

            boxResults = dataSource.Get(box.Resize(0.1), null);
            Assert.IsNotNull(boxResults);
            Assert.AreEqual(2, boxResults.Count);

            node           = new Node();
            node.Id        = 3;
            node.Latitude  = 10;
            node.Longitude = 10;
            dataSource.AddNode(node);

            node           = new Node();
            node.Id        = 4;
            node.Latitude  = -10;
            node.Longitude = -10;
            dataSource.AddNode(node);

            boxResults = dataSource.Get(box, null);
            Assert.IsNotNull(boxResults);
            Assert.AreEqual(1, boxResults.Count);

            boxResults = dataSource.Get(box.Resize(0.1), null);
            Assert.IsNotNull(boxResults);
            Assert.AreEqual(2, boxResults.Count);

            // test ways.
            Way positive = new Way();

            positive.Id    = 1;
            positive.Nodes = new List <long>();
            positive.Nodes.Add(1);
            positive.Nodes.Add(2);
            dataSource.AddWay(positive);

            Way halfPositive = new Way();

            halfPositive.Id    = 2;
            halfPositive.Nodes = new List <long>();
            halfPositive.Nodes.Add(1);
            halfPositive.Nodes.Add(3);
            dataSource.AddWay(halfPositive);

            Way negative = new Way();

            negative.Id    = 3;
            negative.Nodes = new List <long>();
            negative.Nodes.Add(3);
            negative.Nodes.Add(4);
            dataSource.AddWay(negative);

            HashSet <OsmGeo> boxResultWithWays = new HashSet <OsmGeo>(dataSource.Get(box, null));

            Assert.IsTrue(boxResultWithWays.Contains(positive));
            Assert.IsTrue(boxResultWithWays.Contains(halfPositive));
            Assert.IsFalse(boxResultWithWays.Contains(negative));

            // test relations.
            Relation positiveRelation1 = new Relation();

            positiveRelation1.Id      = 1;
            positiveRelation1.Members = new List <RelationMember>();
            positiveRelation1.Members.Add(new RelationMember()
            {
                MemberId   = 1,
                MemberType = OsmGeoType.Node,
                MemberRole = "node"
            });
            dataSource.AddRelation(positiveRelation1);

            Relation positiveRelation2 = new Relation();

            positiveRelation2.Id      = 2;
            positiveRelation2.Members = new List <RelationMember>();
            positiveRelation2.Members.Add(new RelationMember()
            {
                MemberId   = 1,
                MemberType = OsmGeoType.Way,
                MemberRole = "way"
            });
            dataSource.AddRelation(positiveRelation2);

            Relation negativeRelation3 = new Relation();

            negativeRelation3.Id      = 3;
            negativeRelation3.Members = new List <RelationMember>();
            negativeRelation3.Members.Add(new RelationMember()
            {
                MemberId   = 3,
                MemberType = OsmGeoType.Way,
                MemberRole = "way"
            });
            dataSource.AddRelation(positiveRelation2);

            HashSet <OsmGeo> boxResultWithWaysAndRelations = new HashSet <OsmGeo>(dataSource.Get(box, null));

            Assert.IsTrue(boxResultWithWaysAndRelations.Contains(positiveRelation1));
            Assert.IsTrue(boxResultWithWaysAndRelations.Contains(positiveRelation2));
            Assert.IsFalse(boxResultWithWaysAndRelations.Contains(negativeRelation3));

            // test recursive relations.
            Relation recusive1 = new Relation();

            recusive1.Id      = 10;
            recusive1.Members = new List <RelationMember>();
            recusive1.Members.Add(new RelationMember()
            {
                MemberId   = 1,
                MemberType = OsmGeoType.Relation,
                MemberRole = "relation"
            });
            dataSource.AddRelation(recusive1);
            Relation recusive2 = new Relation();

            recusive2.Id      = 11;
            recusive2.Members = new List <RelationMember>();
            recusive2.Members.Add(new RelationMember()
            {
                MemberId   = 10,
                MemberType = OsmGeoType.Relation,
                MemberRole = "relation"
            });
            dataSource.AddRelation(recusive2);
            Relation recusive3 = new Relation();

            recusive3.Id      = 12;
            recusive3.Members = new List <RelationMember>();
            recusive3.Members.Add(new RelationMember()
            {
                MemberId   = 11,
                MemberType = OsmGeoType.Relation,
                MemberRole = "relation"
            });
            dataSource.AddRelation(recusive3);

            boxResultWithWaysAndRelations = new HashSet <OsmGeo>(dataSource.Get(box, null));
            Assert.IsTrue(boxResultWithWaysAndRelations.Contains(recusive1));
            Assert.IsTrue(boxResultWithWaysAndRelations.Contains(recusive2));
            Assert.IsTrue(boxResultWithWaysAndRelations.Contains(recusive3));
        }
        private bool IsInBB(OsmGeo osmGeo)
        {
            bool flag = false;

            switch (osmGeo.Type)
            {
            case OsmGeoType.Node:
                GeoCoordinateBox box      = this._box;
                double?          nullable = (osmGeo as Node).Latitude;
                double           latitude = nullable.Value;
                nullable = (osmGeo as Node).Longitude;
                double        longitude     = nullable.Value;
                GeoCoordinate geoCoordinate = new GeoCoordinate(latitude, longitude);
                flag = box.Contains((PointF2D)geoCoordinate);
                break;

            case OsmGeoType.Way:
                foreach (long node in (osmGeo as Way).Nodes)
                {
                    if (this._nodesIn.Contains(node))
                    {
                        flag = true;
                        break;
                    }
                }
                if (flag)
                {
                    using (List <long> .Enumerator enumerator = (osmGeo as Way).Nodes.GetEnumerator())
                    {
                        while (enumerator.MoveNext())
                        {
                            this._nodesToInclude.Add(enumerator.Current);
                        }
                        break;
                    }
                }
                else
                {
                    break;
                }

            case OsmGeoType.Relation:
                if (!this._relationsConsidered.Contains(osmGeo.Id.Value))
                {
                    foreach (RelationMember member in (osmGeo as Relation).Members)
                    {
                        switch (member.MemberType.Value)
                        {
                        case OsmGeoType.Node:
                            if (this._nodesIn.Contains(member.MemberId.Value))
                            {
                                flag = true;
                                continue;
                            }
                            continue;

                        case OsmGeoType.Way:
                            if (this._waysIn.Contains(member.MemberId.Value))
                            {
                                flag = true;
                                continue;
                            }
                            continue;

                        case OsmGeoType.Relation:
                            if (this._relationIn.Contains(member.MemberId.Value))
                            {
                                flag = true;
                                continue;
                            }
                            continue;

                        default:
                            continue;
                        }
                    }
                    if (flag)
                    {
                        using (List <RelationMember> .Enumerator enumerator = (osmGeo as Relation).Members.GetEnumerator())
                        {
                            while (enumerator.MoveNext())
                            {
                                RelationMember current = enumerator.Current;
                                switch (current.MemberType.Value)
                                {
                                case OsmGeoType.Node:
                                    this._nodesToInclude.Add(current.MemberId.Value);
                                    continue;

                                case OsmGeoType.Way:
                                    this._waysToInclude.Add(current.MemberId.Value);
                                    continue;

                                case OsmGeoType.Relation:
                                    this._relationsToInclude.Add(current.MemberId.Value);
                                    continue;

                                default:
                                    continue;
                                }
                            }
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    break;
                }
            }
            return(flag);
        }
 /// <summary>
 /// Creates a new bounding box filter.
 /// </summary>
 /// <param name="box"></param>
 public DataProcessorFilterBoundingBox(GeoCoordinateBox box)
     : base()
 {
     _box = box;
 }
Ejemplo n.º 39
0
        public TileRange GetTileToLoadFor(GeoCoordinateBox bbox,
            int zoom)
        {
            int n = (int)System.Math.Floor(System.Math.Pow(2, zoom));

            Radian rad = new Degree(bbox.MaxLat);

            int x_tile_min = (int)(((bbox.MinLon + 180.0f) / 360.0f) * (double)n);
            int y_tile_min = (int)(
                (1.0f - (System.Math.Log(System.Math.Tan(rad.Value) + (1.0f / System.Math.Cos(rad.Value))))
                / System.Math.PI) / 2f * (double)n);

            rad = new Degree(bbox.MinLat);
            int x_tile_max = (int)(((bbox.MaxLon + 180.0f) / 360.0f) * (double)n);
            int y_tile_max = (int)(
                (1.0f - (System.Math.Log(System.Math.Tan(rad.Value) + (1.0f / System.Math.Cos(rad.Value))))
                / System.Math.PI) / 2f * (double)n);

            TileRange range = new TileRange();
            range.XMax = x_tile_max;
            range.XMin = x_tile_min;
            range.YMax = y_tile_max;
            range.YMin = y_tile_min;
            return range;
        }
Ejemplo n.º 40
0
 /// <summary>
 /// Creates a new view.
 /// </summary>
 /// <param name="box"></param>
 public View(GeoCoordinateBox box, float zoom_factor)
 {
     _box = box;
     _zoom_factor = zoom_factor;
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Returns the elements.
        /// </summary>
        /// <param name="box"></param>
        /// <param name="zoom_factor"></param>
        /// <returns></returns>
        public IList<IElement> GetElements(GeoCoordinateBox box, double zoom_factor)
        {
            List<IElement> elements = new List<IElement>();
            List<IElement> local_elements;
            lock (_elements)
            {
                local_elements = new List<IElement>(_elements);
            }

            foreach (IElement element in local_elements)
            {
                if (element.IsVisibleIn(box))
                {
                    elements.Add(element);
                }
            }

            return elements;
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Tests adding some simple data.
        /// </summary>
        protected void DoTestSimple()
        {
            // create the index.
            ILocatedObjectIndex<GeoCoordinate, LocatedObjectData> index = this.CreateIndex();

            // add the data.
            GeoCoordinate point1 = new GeoCoordinate(0, 0);
            LocatedObjectData point1_data = new LocatedObjectData()
            {
                SomeData = point1.ToString()
            };
            GeoCoordinate point2 = new GeoCoordinate(1, 1);
            LocatedObjectData point2_data = new LocatedObjectData()
            {
                SomeData = point2.ToString()
            };

            GeoCoordinateBox location_box = new GeoCoordinateBox(
                new GeoCoordinate(point1.Latitude - 0.0001, point1.Longitude - 0.0001),
                new GeoCoordinate(point1.Latitude + 0.0001, point1.Longitude + 0.0001));

            // try and get data from empty index.
            // regression test for issue: https://osmsharp.codeplex.com/workitem/1244
            IEnumerable<LocatedObjectData> location_box_data = index.GetInside(location_box);
            Assert.IsNotNull(location_box_data);
            Assert.AreEqual(0, location_box_data.Count());

            // try point1.
            index.Add(point1, point1_data);

            location_box_data = index.GetInside(
                location_box);
            Assert.IsNotNull(location_box_data);

            bool found = false;
            foreach (LocatedObjectData location_data in location_box_data)
            {
                if (location_data.SomeData == point1.ToString())
                {
                    found = true;
                }
            }
            Assert.IsTrue(found, string.Format("Data added at location {0} not found in box {1}!",
                point1, location_box));

            // try point2.
            index.Add(point2, point2_data);
            location_box = new GeoCoordinateBox(
                new GeoCoordinate(point2.Latitude - 0.0001, point2.Longitude - 0.0001),
                new GeoCoordinate(point2.Latitude + 0.0001, point2.Longitude + 0.0001));

            location_box_data = index.GetInside(
                location_box);
            Assert.IsNotNull(location_box_data);

            found = false;
            foreach (LocatedObjectData location_data in location_box_data)
            {
                if (location_data.SomeData == point2.ToString())
                {
                    found = true;
                }
            }
            Assert.IsTrue(found, string.Format("Data added at location {0} not found in box {1}!",
                point2, location_box));
        }
Ejemplo n.º 43
0
        /// <summary>
        /// Searches the data for a point on an edge closest to the given coordinate.
        /// </summary>
        /// <param name="graph"></param>
        /// <param name="vehicle"></param>
        /// <param name="coordinate"></param>
        /// <param name="delta"></param>
        /// <param name="matcher"></param>
        /// <param name="pointTags"></param>
        /// <param name="interpreter"></param>
        /// <param name="verticesOnly"></param>
        public SearchClosestResult SearchClosest(IBasicRouterDataSource <TEdgeData> graph, IRoutingInterpreter interpreter, Vehicle vehicle,
                                                 GeoCoordinate coordinate, float delta, IEdgeMatcher matcher, TagsCollection pointTags, bool verticesOnly)
        {
            var closestWithMatch    = new SearchClosestResult(double.MaxValue, 0);
            var closestWithoutMatch = new SearchClosestResult(double.MaxValue, 0);

            double searchBoxSize = delta;
            // create the search box.
            var searchBox = new GeoCoordinateBox(new GeoCoordinate(
                                                     coordinate.Latitude - searchBoxSize, coordinate.Longitude - searchBoxSize),
                                                 new GeoCoordinate(
                                                     coordinate.Latitude + searchBoxSize, coordinate.Longitude + searchBoxSize));

            // get the arcs from the data source.
            KeyValuePair <uint, KeyValuePair <uint, TEdgeData> >[] arcs = graph.GetArcs(searchBox);

            if (!verticesOnly)
            { // find both closest arcs and vertices.
                // loop over all.
                foreach (KeyValuePair <uint, KeyValuePair <uint, TEdgeData> > arc in arcs)
                {
                    TagsCollection arcTags        = graph.TagsIndex.Get(arc.Value.Value.Tags);
                    bool           canBeTraversed = vehicle.CanTraverse(arcTags);
                    if (canBeTraversed)
                    { // the edge can be traversed.
                        // test the two points.
                        float  fromLatitude, fromLongitude;
                        float  toLatitude, toLongitude;
                        double distance;
                        if (graph.GetVertex(arc.Key, out fromLatitude, out fromLongitude) &&
                            graph.GetVertex(arc.Value.Key, out toLatitude, out toLongitude))
                        { // return the vertex.
                            var fromCoordinates = new GeoCoordinate(fromLatitude, fromLongitude);
                            distance = coordinate.Distance(fromCoordinates);

                            if (distance < 0.00001)
                            { // the distance is smaller than the tolerance value.
                                closestWithoutMatch = new SearchClosestResult(
                                    distance, arc.Key);
                                if (matcher == null ||
                                    (pointTags == null || pointTags.Count == 0) ||
                                    matcher.MatchWithEdge(vehicle, pointTags, arcTags))
                                {
                                    closestWithMatch = new SearchClosestResult(
                                        distance, arc.Key);
                                    break;
                                }
                            }

                            if (distance < closestWithoutMatch.Distance)
                            { // the distance is smaller for the without match.
                                closestWithoutMatch = new SearchClosestResult(
                                    distance, arc.Key);
                            }
                            if (distance < closestWithMatch.Distance)
                            { // the distance is smaller for the with match.
                                if (matcher == null ||
                                    (pointTags == null || pointTags.Count == 0) ||
                                    matcher.MatchWithEdge(vehicle, pointTags, graph.TagsIndex.Get(arc.Value.Value.Tags)))
                                {
                                    closestWithMatch = new SearchClosestResult(
                                        distance, arc.Key);
                                }
                            }
                            var toCoordinates = new GeoCoordinate(toLatitude, toLongitude);
                            distance = coordinate.Distance(toCoordinates);

                            if (distance < closestWithoutMatch.Distance)
                            { // the distance is smaller for the without match.
                                closestWithoutMatch = new SearchClosestResult(
                                    distance, arc.Value.Key);
                            }
                            if (distance < closestWithMatch.Distance)
                            { // the distance is smaller for the with match.
                                if (matcher == null ||
                                    (pointTags == null || pointTags.Count == 0) ||
                                    matcher.MatchWithEdge(vehicle, pointTags, arcTags))
                                {
                                    closestWithMatch = new SearchClosestResult(
                                        distance, arc.Value.Key);
                                }
                            }

                            // create a line.
                            double distanceTotal = fromCoordinates.Distance(toCoordinates);
                            if (distanceTotal > 0)
                            { // the from/to are not the same location.
                                var line = new GeoCoordinateLine(fromCoordinates, toCoordinates, true, true);
                                distance = line.Distance(coordinate);

                                if (distance < closestWithoutMatch.Distance)
                                { // the distance is smaller.
                                    PointF2D projectedPoint =
                                        line.ProjectOn(coordinate);

                                    // calculate the position.
                                    if (projectedPoint != null)
                                    { // calculate the distance
                                        double distancePoint = fromCoordinates.Distance(projectedPoint);
                                        double position      = distancePoint / distanceTotal;

                                        closestWithoutMatch = new SearchClosestResult(
                                            distance, arc.Key, arc.Value.Key, position);
                                    }
                                }
                                if (distance < closestWithMatch.Distance)
                                {
                                    PointF2D projectedPoint =
                                        line.ProjectOn(coordinate);

                                    // calculate the position.
                                    if (projectedPoint != null)
                                    { // calculate the distance
                                        double distancePoint = fromCoordinates.Distance(projectedPoint);
                                        double position      = distancePoint / distanceTotal;

                                        if (matcher == null ||
                                            (pointTags == null || pointTags.Count == 0) ||
                                            matcher.MatchWithEdge(vehicle, pointTags, arcTags))
                                        {
                                            closestWithMatch = new SearchClosestResult(
                                                distance, arc.Key, arc.Value.Key, position);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            { // only find closest vertices.
                // loop over all.
                foreach (KeyValuePair <uint, KeyValuePair <uint, TEdgeData> > arc in arcs)
                {
                    float fromLatitude, fromLongitude;
                    float toLatitude, toLongitude;
                    if (graph.GetVertex(arc.Key, out fromLatitude, out fromLongitude) &&
                        graph.GetVertex(arc.Value.Key, out toLatitude, out toLongitude))
                    {
                        var    vertexCoordinate = new GeoCoordinate(fromLatitude, fromLongitude);
                        double distance         = coordinate.Distance(vertexCoordinate);
                        if (distance < closestWithoutMatch.Distance)
                        { // the distance found is closer.
                            closestWithoutMatch = new SearchClosestResult(
                                distance, arc.Key);
                        }

                        vertexCoordinate = new GeoCoordinate(toLatitude, toLongitude);
                        distance         = coordinate.Distance(vertexCoordinate);
                        if (distance < closestWithoutMatch.Distance)
                        { // the distance found is closer.
                            closestWithoutMatch = new SearchClosestResult(
                                distance, arc.Value.Key);
                        }
                    }
                }
            }

            // return the best result.
            if (closestWithMatch.Distance < double.MaxValue)
            {
                return(closestWithMatch);
            }
            return(closestWithoutMatch);
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Tests adding a lot of random data.
        /// </summary>
        /// <param name="count"></param>
        public void DoTestAddingRandom(int count)
        {
            ILocatedObjectIndex<GeoCoordinate, LocatedObjectData> index = this.CreateIndex();

            GeoCoordinateBox box = new GeoCoordinateBox(new GeoCoordinate(50, 3), new GeoCoordinate(40, 2));
            HashSet<GeoCoordinate> locations = new HashSet<GeoCoordinate>();
            Random random = new Random();
            while (count > 0)
            {
                GeoCoordinate location = box.GenerateRandomIn(random);
                LocatedObjectData data = new LocatedObjectData()
                {
                    SomeData = location.ToString()
                };
                locations.Add(location);
                index.Add(location, data);

                // try immidiately after.
                GeoCoordinateBox location_box = new GeoCoordinateBox(
                    new GeoCoordinate(location.Latitude - 0.0001, location.Longitude - 0.0001),
                    new GeoCoordinate(location.Latitude + 0.0001, location.Longitude + 0.0001));

                IEnumerable<LocatedObjectData> location_box_data = index.GetInside(
                    location_box);

                Assert.IsNotNull(location_box_data);

                bool found = false;
                foreach (LocatedObjectData location_data in location_box_data)
                {
                    if (location_data.SomeData == location.ToString())
                    {
                        found = true;
                    }
                }
                Assert.IsTrue(found, string.Format("Data added at location {0} not found in box {1}!",
                    location, location_box));

                count--;
            }

            foreach (GeoCoordinate location in locations)
            {
                GeoCoordinateBox location_box = new GeoCoordinateBox(
                    new GeoCoordinate(location.Latitude - 0.0001, location.Longitude - 0.0001),
                    new GeoCoordinate(location.Latitude + 0.0001, location.Longitude + 0.0001));

                IEnumerable<LocatedObjectData> location_box_data = index.GetInside(
                    location_box);

                Assert.IsNotNull(location_box_data);

                bool found = false;
                foreach (LocatedObjectData location_data in location_box_data)
                {
                    if (location_data.SomeData == location.ToString())
                    {
                        found = true;
                    }
                }
                Assert.IsTrue(found, string.Format("Data added at location {0} not found in box {1}!",
                    location, location_box));
            }
        }
Ejemplo n.º 45
0
        /// <summary>
        /// Returns the objects that exist withing the given box and evaluate the filter to true.
        /// </summary>
        /// <param name="box"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public IList<OsmGeo> Get(GeoCoordinateBox box, Filter filter)
        {
            this.ReadFromDocument();

            IList<OsmGeo> res = new List<OsmGeo>();
            foreach (Node node in _nodes.Values)
            {
                if (filter.Evaluate(node) && node.Shape.Inside(box))
                {
                    res.Add(node);
                }
            }
            foreach (Way way in _ways.Values)
            {
                if (filter.Evaluate(way) && way.Shape.Inside(box))
                {
                    res.Add(way);
                }
            }
            foreach (Relation relation in _relations.Values)
            {
                if (filter.Evaluate(relation) && relation.Shape.Inside(box))
                {
                    res.Add(relation);
                }
            }

            return res;
        }
Ejemplo n.º 46
0
 /// <summary>
 /// Returns all edges inside the given bounding box.
 /// </summary>
 /// <returns></returns>
 public abstract INeighbourEnumerator <TEdgeData> GetEdges(GeoCoordinateBox box);
 /// <summary>
 /// Creates a new changeset filter.
 /// </summary>
 /// <param name="data_source"></param>
 /// <param name="box"></param>
 /// <param name="listener"></param>
 public DataProcessorChangeSetFilterBoundingBox(Osm.Data.IDataSourceReadOnly data_source, GeoCoordinateBox box, IChangeSetFilterListener listener)
     : base()
 {
     _box = box;
     _data_source = data_source;
     _listener = listener;
 }
Ejemplo n.º 48
0
        /// <summary>
        /// Utility method for ensuring a view stays within a bounding box of geo coordinated.
        /// </summary>
        /// <param name="center">The map center we want to move to.</param>
        /// <param name="boundingBox">A GeoCoordinateBox defining the bounding box.</param>
        /// <param name="view" The current view.</param>
        /// <returns>Returns a center geo coordinate that is corrected so the view stays within the bounding box.</returns>
        public GeoCoordinate EnsureViewWithinBoundingBox(GeoCoordinate center, GeoCoordinateBox boundingBox, View2D view)
        {
            double[] mapCenterSceneCoords = this.Projection.ToPixel(center);

            var    toViewPort = view.CreateToViewPort(view.Width, view.Height);
            double mapCenterPixelsX, mapCenterPixelsY;

            toViewPort.Apply(mapCenterSceneCoords[0], mapCenterSceneCoords[1], out mapCenterPixelsX, out mapCenterPixelsY);

            //double[] mapCenterPixels = view.ToViewPort(view.Width, view.Height, mapCenterSceneCoords[0], mapCenterSceneCoords[1]);

            var    fromViewPort = view.CreateFromViewPort(view.Height, view.Width);
            double leftScene, topScene, rightScene, bottomScene;

            fromViewPort.Apply(mapCenterPixelsX - (view.Width) / 2.0, mapCenterPixelsY - (view.Height) / 2.0, out leftScene, out topScene);

            //double[] topLeftSceneCoordinates = view.FromViewPort(view.Width,
            //                                                    view.Height,
            //                                                    mapCenterPixels[0] - (view.Width) / 2.0,
            //                                                    mapCenterPixels[1] - (view.Height) / 2.0);
            GeoCoordinate topLeft = this.Projection.ToGeoCoordinates(leftScene, topScene);

            //GeoCoordinate topLeft = this.Projection.ToGeoCoordinates(topLeftSceneCoordinates[0], topLeftSceneCoordinates[1]);

            fromViewPort.Apply(mapCenterPixelsX + (view.Width) / 2.0, mapCenterPixelsY + (view.Height) / 2.0, out rightScene, out bottomScene);
            //double[] bottomRightSceneCoordinates = view.FromViewPort(view.Width,
            //                                                    view.Height,
            //                                                    mapCenterPixels[0] + (view.Width) / 2.0,
            //                                                    mapCenterPixels[1] + (view.Height) / 2.0);
            GeoCoordinate bottomRight = this.Projection.ToGeoCoordinates(rightScene, bottomScene);

            // Early exit when the view is inside the box.
            if (boundingBox.Contains(topLeft) && boundingBox.Contains(bottomRight))
            {
                return(center);
            }

            double viewNorth = topLeft.Latitude;
            double viewEast  = bottomRight.Longitude;
            double viewSouth = bottomRight.Latitude;
            double viewWest  = topLeft.Longitude;

            double boxNorth = boundingBox.MaxLat;
            double boxEast  = boundingBox.MaxLon;
            double boxSouth = boundingBox.MinLat;
            double boxWest  = boundingBox.MinLon;

            //TODO: Check if the view acrually fits the bounding box, if not resize the view.

            // Correct all view bounds if neccecary.
            if (viewNorth > boxNorth)
            {
                viewSouth -= viewNorth - boxNorth;
                viewNorth  = boxNorth;
            }
            if (viewEast > boxEast)
            {
                viewWest -= viewEast - boxEast;
                viewEast  = boxEast;
            }
            if (viewSouth < boxSouth)
            {
                viewNorth += boxSouth - viewSouth;
                viewSouth  = boxSouth;
            }
            if (viewWest < boxWest)
            {
                viewEast += boxWest - viewWest;
                viewWest  = boxWest;
            }

            // Compute and return corrected map center
            return(new GeoCoordinate(viewSouth + (viewNorth - viewSouth) / 2.0f, viewWest + (viewEast - viewWest) / 2.0f));
        }
Ejemplo n.º 49
0
 /// <summary>
 /// Creates a new instruction with a location and points of interest.
 /// </summary>
 /// <param name="location"></param>
 /// <param name="pois"></param>
 public Instruction(GeoCoordinateBox location, List<PointPoi> pois)
 {
     this.Location = location;
     this.Pois = pois;
 }
Ejemplo n.º 50
0
        /// <summary>
        /// Generates an instruction from the given meta data and given pois.
        /// </summary>
        /// <param name="metaData"></param>
        /// <param name="segmentIdx"></param>
        /// <param name="box"></param>
        /// <param name="pois"></param>
        internal void GenerateInstruction(Dictionary <string, object> metaData, int segmentIdx, GeoCoordinateBox box, List <PointPoi> pois)
        {
            string text;

            if (_generator.Generate(metaData, out text))
            { // add the instruction to the instructions list.
                _instructions.Add(new Instruction(metaData, segmentIdx, box, text, pois));
            }
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Returns true if this geometry is inside the given bounding box.
 /// </summary>
 /// <param name="box"></param>
 /// <returns></returns>
 public abstract bool IsInside(GeoCoordinateBox box);
Ejemplo n.º 52
0
        public IList<IElement> GetElements(GeoCoordinateBox box, double zoom_factor)
        {
            zoom_factor = zoom_factor + _zoom_offset;
            if (zoom_factor > _max_zoom)
            {
                zoom_factor = _max_zoom;
            }
            else if (zoom_factor < _min_zoom)
            {
                zoom_factor = _min_zoom;
            }

            return this.GetTiles(box, zoom_factor);
        }
Ejemplo n.º 53
0
        public override void Succes()
        {
            // get the last arc and the last point.
            AggregatedArc latest_arc = (this.FinalMessages[this.FinalMessages.Count - 2] as MicroPlannerMessageArc).Arc;
            AggregatedPoint latest_point = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point;

            // count the number of streets in the same turning direction as the turn
            // that was found.
            int count = 0;
            if (MicroPlannerHelper.IsLeft(latest_point.Angle.Direction, this.Planner.Interpreter))
            {
                count = MicroPlannerHelper.GetLeft(this.FinalMessages, this.Planner.Interpreter);
            }
            else if (MicroPlannerHelper.IsRight(latest_point.Angle.Direction, this.Planner.Interpreter))
            {
                count = MicroPlannerHelper.GetRight(this.FinalMessages, this.Planner.Interpreter);
            }

            // construct the box indicating the location of the resulting find by this machine.
            GeoCoordinate point1 = latest_point.Location;
            GeoCoordinateBox box = new GeoCoordinateBox(
                new GeoCoordinate(point1.Latitude - 0.001f, point1.Longitude - 0.001f),
                new GeoCoordinate(point1.Latitude + 0.001f, point1.Longitude + 0.001f));

            //string next_street = latest_point.Next.Name;

            // let the scentence planner generate the correct information.
            this.Planner.SentencePlanner.GenerateRoundabout(box, count - 1, latest_point.Next.Tags);
        }
Ejemplo n.º 54
0
        /// <summary>
        /// Returns all the tile filling the given bounding box.
        /// </summary>
        /// <param name="bbox"></param>
        /// <param name="zoom_factor"></param>
        /// <returns></returns>
        public IList<IElement> GetTiles(GeoCoordinateBox bbox,
            double zoom_factor)
        {
            int zoom = (int)System.Math.Floor(zoom_factor);

            TileRange range = this.GetTileToLoadFor(bbox, zoom);
            IList<IElement> return_list = new List<IElement>();

            double tile_size = 360.0f / (double)(System.Math.Pow(2, zoom));

            for (int x = range.XMin; x < range.XMax + 1; x++)
            {
                for (int y = range.YMin; y < range.YMax + 1; y++)
                {
                    IElement new_tile = this.GetTile(x, y, zoom);
                    if (new_tile != null)
                    {
                        return_list.Add(new_tile);
                    }
                }
            }
            return return_list;
        }
        /// <summary>
        /// Returns all data within the given bounding box and filtered by the given filter.
        /// </summary>
        /// <param name="box"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        public override IList <OsmGeo> Get(GeoCoordinateBox box, OsmSharp.Osm.Filters.Filter filter)
        {
            // initialize connection.
            NpgsqlConnection con = this.CreateConnection();
            List <OsmGeo>    res = new List <OsmGeo>();

            // calculate bounding box parameters to query db.
            long latitude_min  = (long)(box.MinLat * 10000000.0);
            long longitude_min = (long)(box.MinLon * 10000000.0);
            long latitude_max  = (long)(box.MaxLat * 10000000.0);
            long longitude_max = (long)(box.MaxLon * 10000000.0);

            // calculate bounding box parameters to query db.
            TileRange range = TileRange.CreateAroundBoundingBox(box, 14);

            IList <long> boxes = new List <long>();

            foreach (Tile tile in range)
            {
                boxes.Add((long)tile.Id);
            }

            // STEP 1: query nodes table.
            //id	latitude	longitude	changeset_id	visible	timestamp	tile	version
            string sql
                = "SELECT id, latitude, longitude, changeset_id, visible, timestamp, tile, version, usr, usr_id FROM node WHERE (visible = true) AND  (tile IN ({4})) AND (latitude >= {0} AND latitude < {1} AND longitude >= {2} AND longitude < {3})";

            sql = string.Format(sql,
                                latitude_min.ToString(),
                                latitude_max.ToString(),
                                longitude_min.ToString(),
                                longitude_max.ToString(),
                                this.ConstructIdList(boxes));

            // TODO: parameters.
            NpgsqlCommand com = new NpgsqlCommand(sql);

            com.Connection = con;
            NpgsqlDataReader        reader  = com.ExecuteReader();
            Node                    node    = null;
            Dictionary <long, Node> nodes   = new Dictionary <long, Node>();
            List <long>             nodeIds = new List <long>();

            while (reader.Read())
            {
                // load/parse data.
                long     returned_id   = reader.GetInt64(0);
                int      latitude_int  = reader.GetInt32(1);
                int      longitude_int = reader.GetInt32(2);
                long?    changeset_id  = reader.IsDBNull(3) ? null : (long?)reader.GetInt64(3);
                bool?    visible       = reader.IsDBNull(4) ? null : (bool?)reader.GetBoolean(4);
                DateTime?timestamp     = reader.IsDBNull(5) ? null : (DateTime?)reader.GetDateTime(5);
                long     tile          = reader.GetInt64(6);
                ulong?   version       = reader.IsDBNull(7) ? null : (ulong?)reader.GetInt32(7);
                string   usr           = reader.IsDBNull(8) ? null : reader.GetString(8);
                long?    usr_id        = reader.IsDBNull(9) ? null : (long?)reader.GetInt32(9);

                if (!nodes.ContainsKey(returned_id))
                {
                    // create node.
                    node             = new Node();
                    node.Id          = returned_id;
                    node.Version     = version;
                    node.UserId      = usr_id;
                    node.UserName    = usr;
                    node.TimeStamp   = timestamp;
                    node.ChangeSetId = changeset_id;
                    node.Latitude    = ((double)latitude_int) / 10000000.0;
                    node.Longitude   = ((double)longitude_int) / 10000000.0;
                    node.Visible     = visible;

                    nodes.Add(node.Id.Value, node);
                    nodeIds.Add(node.Id.Value);
                }
            }
            reader.Close();

            // STEP2: Load all node tags.
            this.LoadNodeTags(nodes);
            res.AddRange(nodes.Values);

            // load all ways that contain the nodes that have been found.
            res.AddRange(this.GetWaysFor(nodeIds));

            // get relations containing any of the nodes or ways in the current results-list.
            List <Relation> relations   = new List <Relation>();
            HashSet <long>  relationIds = new HashSet <long>();

            foreach (OsmGeo osmGeo in res)
            {
                IList <Relation> relationsFor = this.GetRelationsFor(osmGeo);
                foreach (Relation relation in relationsFor)
                {
                    if (!relationIds.Contains(relation.Id.Value))
                    {
                        relations.Add(relation);
                        relationIds.Add(relation.Id.Value);
                    }
                }
            }

            // recursively add all relations containing other relations as a member.
            do
            {
                res.AddRange(relations); // add previous relations-list.
                List <Relation> newRelations = new List <Relation>();
                foreach (OsmGeo osmGeo in relations)
                {
                    IList <Relation> relationsFor = this.GetRelationsFor(osmGeo);
                    foreach (Relation relation in relationsFor)
                    {
                        if (!relationIds.Contains(relation.Id.Value))
                        {
                            newRelations.Add(relation);
                            relationIds.Add(relation.Id.Value);
                        }
                    }
                }
                relations = newRelations;
            } while (relations.Count > 0);

            if (filter != null)
            {
                var filtered = new List <OsmGeo>();
                foreach (OsmGeo geo in res)
                {
                    if (filter.Evaluate(geo))
                    {
                        filtered.Add(geo);
                    }
                }
                return(filtered);
            }

            return(res);
        }
Ejemplo n.º 56
0
 public override bool IsVisibleIn(GeoCoordinateBox box)
 {
     return box.IsInside(_dot.Point);
 }
Ejemplo n.º 57
0
 /// <summary>
 /// Returns all data in this source for the given bounding box.
 /// </summary>
 /// <param name="box"></param>
 /// <returns></returns>
 public DataProcessorSource Get(GeoCoordinateBox box)
 {
     return new OsmGeoListDataProcessorSource(
         _dataSourceReadOnly.Get(box, null));
 }
Ejemplo n.º 58
0
 /// <summary>
 /// Creates a new osm edge data processing target.
 /// </summary>
 /// <param name="dynamicGraph"></param>
 /// <param name="interpreter"></param>
 /// <param name="tagsIndex"></param>
 /// <param name="box"></param>
 public LiveGraphOsmStreamTarget(IDynamicGraphRouterDataSource <LiveEdge> dynamicGraph,
                                 IOsmRoutingInterpreter interpreter, ITagsIndex tagsIndex, GeoCoordinateBox box)
     : this(dynamicGraph, interpreter, tagsIndex, new Dictionary <long, uint>(), box, null)
 {
 }
        public void Scene2DSimpleSerializeDeserializeTest()
        {
            // create the MapCSS image source.
            var imageSource = new MapCSSDictionaryImageSource();

            // load mapcss style interpreter.
            var mapCSSInterpreter = new MapCSSInterpreter(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    "OsmSharp.UI.Test.Unittests.Data.MapCSS.test.mapcss"),
                imageSource);

            // initialize the data source.
            var xmlSource = new XmlOsmStreamSource(
                Assembly.GetExecutingAssembly().GetManifestResourceStream(
                    "OsmSharp.UI.Test.Unittests.Data.test.osm"));
            IEnumerable <OsmGeo> dataSource = xmlSource;
            MemoryDataSource     source     = MemoryDataSource.CreateFrom(xmlSource);

            // get data.
            var scene            = new Scene2DSimple();
            var projection       = new WebMercator();
            GeoCoordinateBox box = null;

            foreach (var osmGeo in dataSource)
            {
                CompleteOsmGeo completeOsmGeo = null;
                switch (osmGeo.Type)
                {
                case OsmGeoType.Node:
                    completeOsmGeo = CompleteNode.CreateFrom(osmGeo as Node);
                    break;

                case OsmGeoType.Way:
                    completeOsmGeo = CompleteWay.CreateFrom(osmGeo as Way,
                                                            source);
                    break;

                case OsmGeoType.Relation:
                    completeOsmGeo = CompleteRelation.CreateFrom(osmGeo as Relation,
                                                                 source);
                    break;
                }

                // update box.
                if (completeOsmGeo != null)
                {
                    if (box == null)
                    {
                        box = completeOsmGeo.BoundingBox;
                    }
                    else if (completeOsmGeo.BoundingBox != null)
                    {
                        box = box + completeOsmGeo.BoundingBox;
                    }
                }

                // translate each object into scene object.
                mapCSSInterpreter.Translate(scene, projection, source, osmGeo as OsmGeo);
            }

            // create the stream.
            var stream = new MemoryStream();

            scene.Serialize(stream, false);

            // deserialize the stream.
            IScene2DPrimitivesSource sceneSource = Scene2DSimple.Deserialize(stream, false);

            if (box != null)
            {
                // query both and get the same results.
                int counter = 100;
                var rand    = new Random();
                while (counter > 0)
                {
                    var queryBox = new GeoCoordinateBox(
                        box.GenerateRandomIn(rand),
                        box.GenerateRandomIn(rand));
                    var    zoomFactor = (float)projection.ToZoomFactor(15);
                    View2D testView   = View2D.CreateFromBounds(
                        projection.LatitudeToY(queryBox.MaxLat),
                        projection.LongitudeToX(queryBox.MinLon),
                        projection.LatitudeToY(queryBox.MinLat),
                        projection.LongitudeToX(queryBox.MaxLon));
                    var testScene = new Scene2DSimple();
                    sceneSource.Get(testScene, testView, zoomFactor);

//                    var resultIndex = new HashSet<Scene2DPrimitive>(testScene.Get(testView, zoomFactor));
//                    var resultReference = new HashSet<Scene2DPrimitive>(scene.Get(testView, zoomFactor));

                    //Assert.AreEqual(resultReference.Count, resultIndex.Count);
                    //foreach (var data in resultIndex)
                    //{
                    //    Assert.IsTrue(resultReference.Contains(data));
                    //}
                    //foreach (var data in resultReference)
                    //{
                    //    Assert.IsTrue(resultIndex.Contains(data));
                    //}
                    counter--;
                }
            }
        }
Ejemplo n.º 60
0
 public override bool IsVisibleIn(GeoCoordinateBox box)
 {
     return box.IsInside(_center);
 }