public override void Succes() { 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, poisPoint.EntryIdx, box, pois); }
/// <summary> /// Generates an instruction from the given meta data and given pois. /// </summary> /// <param name="metaData"></param> /// <param name="firstSegmentIdx"></param> /// <param name="lastSegmentIdx"></param> /// <param name="box"></param> /// <param name="pois"></param> public void GenerateInstruction(Dictionary<string, object> metaData, int firstSegmentIdx, int lastSegmentIdx, 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, firstSegmentIdx, lastSegmentIdx, box, text, pois)); } }
/// <summary> /// Tests the live routing. /// </summary> public static void Test() { var box = new GeoCoordinateBox( new GeoCoordinate(51.20190, 4.66540), new GeoCoordinate(51.30720, 4.89820)); LiveRoutingTest.TestSerializedRouting("LiveRouting", "kempen-big.osm.pbf", box, 2500); }
/// <summary> /// Tests routing from a serialized routing file. /// </summary> public static void Test(Stream stream, int testCount) { GeoCoordinateBox box = new GeoCoordinateBox( new GeoCoordinate(51.20190, 4.66540), new GeoCoordinate(51.30720, 4.89820)); CHSerializedRoutingTest.TestSerializedRouting("CHSerializedRouting", stream, box, testCount); }
/// <summary> /// Tests routing from a serialized routing file. /// </summary> public static void TestResolved(string name, string osmPbfFile, GeoCoordinateBox box, int testCount) { var testFile = new FileInfo(string.Format(@".\TestFiles\{0}", osmPbfFile)); var stream = testFile.OpenRead(); RoutingResolveTest.TestResolved(name, stream, box, testCount); stream.Dispose(); }
/// <summary> /// Creates a new polygon filter. /// </summary> public OsmStreamFilterPoly(OsmSharp.Geo.Geometries.LineairRing poly) : base() { if (poly == null) { throw new ArgumentNullException("poly"); } _poly = poly; _box = new GeoCoordinateBox(poly.Coordinates); this.Meta.Add("poly", OsmSharp.Geo.Streams.GeoJson.GeoJsonConverter.ToGeoJson(_poly)); }
/// <summary> /// Creates a new instruction with a location and points of interest. /// </summary> /// <param name="metaData"></param> /// <param name="segmentIdx"></param> /// <param name="location"></param> /// <param name="text"></param> /// <param name="pois"></param> public Instruction(Dictionary<string, object> metaData, int segmentIdx, GeoCoordinateBox location, string text, List<PointPoi> pois) { this.SegmentIdx = segmentIdx; this.Location = location; this.Pois = pois; this.MetaData = metaData; this.Text = text; this.Pois = new List<PointPoi>(); }
/// <summary> /// Tests the CH pre-processor. /// </summary> public static void Test() { GeoCoordinateBox box = new GeoCoordinateBox( new GeoCoordinate(51.20190, 4.66540), new GeoCoordinate(51.30720, 4.89820)); CHSerializedRoutingTest.TestSerializedRouting("CHSerializedRouting", "kempen-big.osm.pbf.routing", box, 1000); // test instructions. CHSerializedRoutingTest.TestInstructions("CHSerializedRouting"); }
/// <summary> /// Tests routing from a serialized routing file. /// </summary> /// <param name="name"></param> /// <param name="stream"></param> /// <param name="testCount"></param> public static void TestResolved(string name, Stream stream, GeoCoordinateBox box, int testCount) { var vehicle = Vehicle.Car; var tagsIndex = new TagsIndex(); // creates a tagged index. // read from the OSM-stream. var source = new OsmSharp.Osm.Streams.Filters.OsmStreamFilterProgress(); source.RegisterSource(new OsmSharp.Osm.PBF.Streams.PBFOsmStreamSource(stream)); var data = GraphOsmStreamTarget.Preprocess(source, new OsmRoutingInterpreter()); //(data.Graph as DirectedGraph<CHEdgeData>).Compress(true); RoutingResolveTest.TestResolved(data, testCount, box); }
public override void Succes() { OsmSharp.Routing.ArcAggregation.Output.AggregatedPoint poisPoint = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point; 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(poisPoint.EntryIdx, box, pois, null); }
/// <summary> /// Tests rendering the given serialized scene. /// </summary> /// <param name="stream"></param> /// <param name="box"></param> /// <param name="testCount"></param> public static void TestRenderScene(Stream stream, GeoCoordinateBox box, int testCount) { WebMercator projection = new WebMercator(); // build a map. Map map = new Map(); IScene2DPrimitivesSource sceneSource = Scene2DLayered.Deserialize(stream, true); LayerScene layerScene = map.AddLayerScene(sceneSource); // build the target to render to. Bitmap imageTarget = new Bitmap(TargetWidth, TargetHeight); Graphics target = Graphics.FromImage(imageTarget); target.SmoothingMode = SmoothingMode.HighQuality; target.PixelOffsetMode = PixelOffsetMode.HighQuality; target.CompositingQuality = CompositingQuality.HighQuality; target.InterpolationMode = InterpolationMode.HighQualityBicubic; MapRenderer<Graphics> mapRenderer = new MapRenderer<Graphics>( new GraphicsRenderer2D()); // render the map. PerformanceInfoConsumer performanceInfo = new PerformanceInfoConsumer("Scene2DLayeredRendering"); performanceInfo.Start(); performanceInfo.Report("Rendering {0} random images...", testCount); while (testCount > 0) { // randomize view. int zoom = OsmSharp.Math.Random.StaticRandomGenerator.Get().Generate(10) + 10; GeoCoordinate center = box.GenerateRandomIn(); View2D view = mapRenderer.Create(TargetWidth, TargetHeight, map, (float)projection.ToZoomFactor(zoom), center, false, true); layerScene.ViewChanged(map, (float)projection.ToZoomFactor(zoom), center, view); mapRenderer.Render(target, map, view); if (WriteResults) { imageTarget.Save(Guid.NewGuid().ToString() + ".png", ImageFormat.Png); } testCount--; } performanceInfo.Stop(); }
/// <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(); }
/// <summary> /// Tests routing from a serialized routing file. /// </summary> /// <param name="name"></param> /// <param name="stream"></param> /// <param name="box"></param> /// <param name="testCount"></param> public static void TestSerializedRouting(string name, Stream stream, GeoCoordinateBox box, int testCount) { var router = Router.CreateLiveFrom(new OsmSharp.Osm.PBF.Streams.PBFOsmStreamSource(stream), new OsmRoutingInterpreter()); var performanceInfo = new PerformanceInfoConsumer("LiveRouting"); performanceInfo.Start(); performanceInfo.Report("Routing {0} routes...", testCount); int successCount = 0; int totalCount = testCount; float latestProgress = -1; while (testCount > 0) { var from = box.GenerateRandomIn(); var to = box.GenerateRandomIn(); var fromPoint = router.Resolve(Vehicle.Car, from); var toPoint = router.Resolve(Vehicle.Car, to); if (fromPoint != null && toPoint != null) { var route = router.Calculate(Vehicle.Car, fromPoint, toPoint); if (route != null) { successCount++; } } testCount--; // report progress. float progress = (float)System.Math.Round(((double)(totalCount - testCount) / (double)totalCount) * 100); if (progress != latestProgress) { OsmSharp.Logging.Log.TraceEvent("LiveEdgePreprocessor", TraceEventType.Information, "Routing... {0}%", progress); latestProgress = progress; } } performanceInfo.Stop(); OsmSharp.Logging.Log.TraceEvent("LiveRouting", OsmSharp.Logging.TraceEventType.Information, string.Format("{0}/{1} routes successfull!", successCount, totalCount)); }
public override void Succes() { var poisPoint = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point; var pois = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point.Points; // construct the box indicating the location of the resulting find by this machine. var point1 = pois[0].Location; var 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. var metaData = new Dictionary<string, object>(); metaData["direction"] = null; metaData["pois"] = pois; metaData["type"] = "poi"; this.Planner.SentencePlanner.GenerateInstruction(metaData, poisPoint.EntryIdx, box, pois); }
public override void Succes() { OsmSharp.Routing.ArcAggregation.Output.AggregatedPoint poisPoint = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point; OsmSharp.Routing.ArcAggregation.Output.AggregatedArc previousArc = (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 = poisPoint.Angle; // calculate the box. List<GeoCoordinate> coordinates = new List<GeoCoordinate>(); foreach (Routing.ArcAggregation.Output.PointPoi poi in pois) { coordinates.Add(poi.Location); } coordinates.Add(poisPoint.Location); GeoCoordinateBox box = new GeoCoordinateBox(coordinates.ToArray()); // let the scentence planner generate the correct information. this.Planner.SentencePlanner.GeneratePoi(poisPoint.EntryIdx, box, pois, direction); }
/// <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; // reset the scene. _scene2DSimple = new Scene2DSimple(); // get from the index. this.Scene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value; lock (_sync) { _index.Get (_scene2DSimple, view, zoomFactor); } }
/// <summary> /// Adds a polyline. /// </summary> /// <param name="points"></param> /// <param name="color"></param> /// <param name="width"></param> /// <param name="fill"></param> /// <returns></returns> public void AddPolygon(GeoCoordinate[] points, int color, float width, bool fill) { var x = new double[points.Length]; var y = new double[points.Length]; for (int idx = 0; idx < points.Length; idx++) { // update envelope. if (_envelope == null) { // create initial envelope. _envelope = new GeoCoordinateBox(points[idx], points[idx]); } // also include the current point. _envelope.ExpandWith(points[idx]); var projected = _projection.ToPixel(points[idx]); x[idx] = projected[0]; y[idx] = projected[1]; } var pointsId = _scene.AddPoints(x, y); if (pointsId.HasValue) { _scene.AddStylePolygon(pointsId.Value, 0, float.MinValue, float.MaxValue, color, width, fill); this.RaiseLayerChanged(); } }
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); } }
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. TagsCollection nextName = latestPoint.Next.Tags; TagsCollection betweenName = latestArc.Tags; TagsCollection 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); }
static void Main(string[] args) { OsmSharp.Logging.Log.Enable(); OsmSharp.Logging.Log.RegisterListener(new OsmSharp.WinForms.UI.Logging.ConsoleTraceListener()); var outputDir = @"c:\temp\tiles"; var mbtilesFile = outputDir + "\\tiles.mbtiles"; SQLiteConnection.CreateFile(mbtilesFile); var mbtiles = new SQLiteConnection(string.Format("Data Source={0};Version=3;", mbtilesFile)); mbtiles.Open(); var query = new SQLiteCommand(mbtiles); query.CommandText = "CREATE TABLE metadata (name text, value text);"; query.ExecuteNonQuery(); new SQLiteCommand(mbtiles); query.CommandText = "CREATE TABLE tiles (zoom_level integer, tile_column integer, tile_row integer, tile_data blob);"; query.ExecuteNonQuery(); query = new SQLiteCommand(mbtiles); query.CommandText = "INSERT INTO metadata (name, value) VALUES ('name', 'tiles');" + "INSERT INTO metadata (name, value) VALUES ('type', 'baselayer');" + "INSERT INTO metadata (name, value) VALUES ('version', '1');" + "INSERT INTO metadata (name, value) VALUES ('minzoom', '5');" + "INSERT INTO metadata (name, value) VALUES ('maxzoom', '6');" + "INSERT INTO metadata (name, value) VALUES ('version', '1');" + "INSERT INTO metadata (name, value) VALUES ('description', 'A description of this layer');" + "INSERT INTO metadata (name, value) VALUES ('bounds', '-5.2294921875,42.195968776291780,8.50341796875,51.248163159055906');" + "INSERT INTO metadata (name, value) VALUES ('format', 'png');"; query.ExecuteNonQuery(); query = new SQLiteCommand(mbtiles); query.CommandText = "INSERT INTO tiles VALUES (:zoom_level, :tile_column, :tile_row, :tile_data) ;"; query.Parameters.Add(new SQLiteParameter(@"zoom_level", DbType.Int64)); query.Parameters.Add(new SQLiteParameter(@"tile_column", DbType.Int64)); query.Parameters.Add(new SQLiteParameter(@"tile_row", DbType.Int64)); query.Parameters.Add(new SQLiteParameter(@"tile_data", DbType.Binary)); var url = "http://localhost:1234/default/{z}/{x}/{y}.png"; var box = new GeoCoordinateBox( new GeoCoordinate(42.195968776291780, -5.2294921875), new GeoCoordinate(51.248163159055906, 8.50341796875)); var minZoom = 5; var maxZoom = 6; // download tiles. for (var zoom = maxZoom; zoom >= minZoom; zoom--) { var tileRange = TileRange.CreateAroundBoundingBox(box, zoom); OsmSharp.Logging.Log.TraceEvent(string.Empty, OsmSharp.Logging.TraceEventType.Information, string.Format("Downloading {0} tiles at zoom {1}.", tileRange.Count, zoom)); foreach(var tile in tileRange) { // download tile. var data = Download(url, tile); // save tile. var tileDir = new DirectoryInfo(Path.Combine(outputDir, tile.Zoom.ToString(), tile.X.ToString())); if (!tileDir.Exists) { // creates target dir. tileDir.Create(); } var tileFile = new FileInfo(Path.Combine(tileDir.ToString(), tile.Y.ToString() + ".png")); using (var outputStream = tileFile.OpenWrite()) { outputStream.Write(data, 0, data.Length); } var inverted = tile.InvertY(); query.Parameters[0].Value = zoom; query.Parameters[1].Value = tile.X; query.Parameters[2].Value = inverted.Y; query.Parameters[3].Value = data; query.ExecuteNonQuery(); Thread.Sleep(100); } } mbtiles.Close(); }
/// <summary> /// Called after this machine reached the final state. /// </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; } // get the last arc and the last point. var latestArc = (this.FinalMessages[this.FinalMessages.Count - 2] as MicroPlannerMessageArc).Arc; var latestPoint = (this.FinalMessages[this.FinalMessages.Count - 1] as MicroPlannerMessagePoint).Point; var secondLatestArc = (this.FinalMessages[this.FinalMessages.Count - 4] as MicroPlannerMessageArc).Arc; var 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. var point1 = latestPoint.Location; var 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. var nextName = latestPoint.Next.Tags; var betweenName = latestArc.Tags; var beforeName = secondLatestArc.Tags; int firstCount = count; RelativeDirection firstTurn = secondLatestPoint.Angle; RelativeDirection secondTurn = latestPoint.Angle; // let the scentence planner generate the correct information. var metaData = new Dictionary<string, object>(); metaData["first_street"] = beforeName; metaData["first_direction"] = firstTurn; metaData["second_street"] = betweenName; metaData["second_direction"] = secondTurn; metaData["count_before"] = firstCount; metaData["pois"] = latestPoint.Points; metaData["type"] = "immidiate_turn"; this.Planner.SentencePlanner.GenerateInstruction(metaData, firstPoint.SegmentIdx, latestPoint.SegmentIdx, box, latestPoint.Points); }
/// <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; }
/// <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); }
/// <summary> /// Returns all objects with the given bounding box and valid for 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. SQLiteConnection 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); // 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 node.id, node.latitude, node.longitude, node.changeset_id, node.timestamp, node.version, " + // "node.usr, node.usr_id, node.visible FROM node WHERE (tile IN ({4})) AND (visible = 1) AND (latitude BETWEEN {0} AND {1} AND longitude BETWEEN {2} AND {3})"; // remove this nasty BETWEEN operation because it depends on the database (!) what results are returned (including or excluding bounds!!!) string sql = "SELECT node.id, node.latitude, node.longitude, node.changeset_id, node.timestamp, node.version, " + "node.usr, node.usr_id, node.visible FROM node WHERE (tile IN ({4})) AND (visible = 1) AND (latitude >= {0} AND latitude < {1} AND longitude >= {2} AND longitude < {3})"; sql = string.Format(sql, latitude_min.ToString(System.Globalization.CultureInfo.InvariantCulture), latitude_max.ToString(System.Globalization.CultureInfo.InvariantCulture), longitude_min.ToString(System.Globalization.CultureInfo.InvariantCulture), longitude_max.ToString(System.Globalization.CultureInfo.InvariantCulture), this.ConstructIdList(boxes)); // TODO: parameters. var com = new SQLiteCommand(sql); com.Connection = con; SQLiteDataReader reader = ExecuteReader(com); Node node = null; var nodes = new Dictionary<long, Node>(); var nodeIds = new List<long>(); while (reader.Read()) { node = new Node(); node.Id = reader.GetInt64(0); int latitude_int = reader.GetInt32(1); int longitude_int = reader.GetInt32(2); node.ChangeSetId = reader.IsDBNull(3) ? null : (long?)reader.GetInt64(3); node.TimeStamp = reader.IsDBNull(4) ? null : (DateTime?)this.ConvertDateTime(reader.GetInt64(4)); node.Version = reader.IsDBNull(5) ? null : (ulong?)reader.GetInt64(5); node.Latitude = latitude_int / 10000000.0; node.Longitude = longitude_int / 10000000.0; node.UserName = reader.IsDBNull(6) ? null : reader.GetString(6); node.UserId = reader.IsDBNull(7) ? null : (long?)reader.GetInt64(7); node.Visible = reader.IsDBNull(8) ? null : (bool?)reader.GetBoolean(8); nodeIds.Add(node.Id.Value); nodes.Add(node.Id.Value, node); } 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) { List<OsmGeo> filtered = new List<OsmGeo>(); foreach (OsmGeo geo in res) { if (filter.Evaluate(geo)) { filtered.Add(geo); } } } return res; }
/// <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)); } }
/// <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)); }
/// <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.GetArcs(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 = CompleteNode.Create (arcId.Vertex1); node1.Coordinate = new GeoCoordinate (latitude, longitude); _dataSource.GetVertex (arcId.Vertex2, out latitude, out longitude); var node2 = CompleteNode.Create (arcId.Vertex2); node2.Coordinate = new GeoCoordinate (latitude, 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); } } }
/// <summary> /// Adds a polyline. /// </summary> /// <param name="points"></param> /// <param name="sizePixels"></param> /// <param name="color"></param> /// <returns></returns> public void AddPolyline(GeoCoordinate[] points, float sizePixels, int color) { var x = new double[points.Length]; var y = new double[points.Length]; for(int idx = 0; idx < points.Length; idx++) { // update envelope. if (_envelope == null) { // create initial envelope. _envelope = new GeoCoordinateBox(points[idx], points[idx]); } // also include the current point. _envelope.ExpandWith(points[idx]); var projected =_projection.ToPixel(points[idx]); x[idx] = projected[0]; y[idx] = projected[1]; } uint? pointsId = _scene.AddPoints(x, y); if (pointsId.HasValue) { _scene.AddStyleLine(pointsId.Value, 0, float.MinValue, float.MaxValue, color, sizePixels, Renderer.Primitives.LineJoin.Round, null); this.RaiseLayerChanged(); } }
/// <summary> /// Adds a line. /// </summary> /// <param name="point1"></param> /// <param name="point2"></param> /// <param name="sizePixels"></param> /// <param name="color"></param> /// <returns></returns> public void AddLine(GeoCoordinate point1, GeoCoordinate point2, float sizePixels, int color) { // update envelope. if (_envelope == null) { // create initial envelope. _envelope = new GeoCoordinateBox(point1, point2); } // also include the current point. _envelope.ExpandWith(point1); _envelope.ExpandWith(point2); var projected1 = _projection.ToPixel(point1); var projected2 = _projection.ToPixel(point2); var x = new double[] { projected1[0], projected2[0] }; var y = new double[] { projected1[1], projected2[1] }; uint? pointsId = _scene.AddPoints(x, y); if (pointsId.HasValue) { _scene.AddStyleLine(pointsId.Value, 0, float.MinValue, float.MaxValue, color, sizePixels, Renderer.Primitives.LineJoin.Round, null); this.RaiseLayerChanged(); } }
/// <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); } }