/// <summary> /// Initialize this instance. /// </summary> public void Initialize() { this.BackgroundColor = UIColor.White; var panGesture = new UIPanGestureRecognizer(Pan); this.AddGestureRecognizer(panGesture); var pinchGesture = new UIPinchGestureRecognizer(Pinch); this.AddGestureRecognizer(pinchGesture); // // create the renderer // _renderer = new MapRenderer<CGContextWrapper> ( // new CGContextRenderer()); // // create the cache renderer. _cacheRenderer = new MapRenderer <CGContextWrapper> ( new CGContextRenderer()); _cachedScene = new Scene2DSimple(); _cachedScene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value; // create invalidation timer. _render = true; System.Threading.Timer timer = new System.Threading.Timer(InvalidateSimple, null, 0, 50); }
void mapControl1_MapMouseClick(MapControlEventArgs e) { if (_router != null) { var routerPoint = _router.Resolve(Vehicle.Car, e.Position); if (routerPoint != null) { _points.Add(routerPoint); _layerPrimitives.AddPoint(routerPoint.Location, 15, SimpleColor.FromKnownColor(KnownColor.Black).Value); _layerPrimitives.AddPoint(routerPoint.Location, 7, SimpleColor.FromKnownColor(KnownColor.White).Value); } if (_points.Count > 1) { var tspRouter = new RouterTSPWrapper <RouterTSPAEXGenetic>( new RouterTSPAEXGenetic(), _router); var route = tspRouter.CalculateTSP(Vehicle.Car, _points.ToArray()); if (route != null) { _layerRoute.Clear(); _layerRoute.AddRoute(route); } } } }
/// <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. if (_scene2DSimple == null) { _scene2DSimple = new Scene2DSimple(); } _scene2DSimple.Clear(); // get from the index. this.Scene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value; lock (_sync) { _index.Get(_scene2DSimple, view, zoomFactor); } }
/// <summary> /// Initialize implementation from IMapView. /// </summary> /// <param name="mapLayout"></param> void IMapViewSurface.Initialize(MapView mapLayout) { _mapView = mapLayout; this.SetWillNotDraw(false); this.MapMinZoomLevel = 10; this.MapMaxZoomLevel = 20; _renderer = new MapRenderer <global::Android.Graphics.Canvas>( new CanvasRenderer2D()); // initialize the gesture detection. this.SetOnTouchListener(this); _scaleGestureDetector = new ScaleGestureDetector( this.Context, this); _rotateGestureDetector = new RotateGestureDetector( this.Context, this); _moveGestureDetector = new MoveGestureDetector( this.Context, this); _tagGestureDetector = new TapGestureDetector( this.Context, this); _makerLayer = new LayerPrimitives( new WebMercator()); // initialize all the caching stuff. _backgroundColor = SimpleColor.FromKnownColor(KnownColor.White).Value; _cacheRenderer = new MapRenderer <global::Android.Graphics.Canvas>( new CanvasRenderer2D()); }
public void TestMapCSSWayRendering1() { // create the data source. MemoryDataSource source = new MemoryDataSource( Node.Create(1, 1, 1), Node.Create(2, -1, -1), Way.Create(1, new SimpleTagsCollection(Tag.Create("highway", "residential")), 1, 2)); // create CSS. string css = "canvas { " + "fill-color: white; " + "} " + "way { " + " width: 2; " + " color: black; " + "} "; // do the rendering. Bitmap rendering = this.Render(source, css); // check result. Assert.AreEqual(SimpleColor.FromKnownColor(OsmSharp.UI.KnownColor.White).Value, rendering.GetPixel(0, 99).ToArgb()); Assert.AreEqual(SimpleColor.FromKnownColor(OsmSharp.UI.KnownColor.White).Value, rendering.GetPixel(99, 0).ToArgb()); for (int x = 0; x < 100; x++) { Assert.AreEqual(SimpleColor.FromKnownColor(OsmSharp.UI.KnownColor.Black).Value, rendering.GetPixel(x, x).ToArgb()); } }
/// <summary> /// Initialize this instance. /// </summary> void Initialize(MapView mapLayout) { _mapLayout = mapLayout; this.SetWillNotDraw(false); this.MapMinZoomLevel = 10; this.MapMaxZoomLevel = 20; _renderer = new MapRenderer <global::Android.Graphics.Canvas>( new CanvasRenderer2D()); // initialize the gesture detection. _gestureDetector = new GestureDetector( this); _scaleGestureDetector = new ScaleGestureDetector( this.Context, this); this.SetOnTouchListener(this); _makerLayer = new LayerPrimitives( new WebMercator()); // initialize all the caching stuff. //_previousCache = null; _cacheRenderer = new MapRenderer <global::Android.Graphics.Canvas>( new CanvasRenderer2D()); _scene = new Scene2DSimple(); _scene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value; System.Threading.Timer timer = new Timer(InvalidateSimple, null, 0, 50); }
/// <summary> /// Initialize implementation from IMapView. /// </summary> /// <param name="mapLayout"></param> void IMapViewSurface.Initialize(MapView mapLayout) { // create the Open GL 2D target. _target = new OpenGLTarget2D(); this.SetRenderer(_target); _mapView = mapLayout; this.SetWillNotDraw(false); this.MapMinZoomLevel = 10; this.MapMaxZoomLevel = 20; // create the renderer. _renderer = new MapRenderer <OpenGLTarget2D>( new OpenGLRenderer2D()); // initialize the gesture detection. this.SetOnTouchListener(this); _scaleGestureDetector = new ScaleGestureDetector( this.Context, this); _rotateGestureDetector = new RotateGestureDetector( this.Context, this); _moveGestureDetector = new MoveGestureDetector( this.Context, this); _tagGestureDetector = new TapGestureDetector( this.Context, this); _makerLayer = new LayerPrimitives( new WebMercator()); _scene = new Scene2D(new WebMercator(), 16); _scene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value; }
/// <summary> /// Creates a new OSM data layer. /// </summary> /// <param name="projection"></param> public LayerGpx(IProjection projection) { _projection = projection; this.Scene = new Scene2DSimple(); this.Scene.BackColor = SimpleColor.FromKnownColor(KnownColor.Transparent).Value; }
/// <summary> /// Adds a new OsmSharpRoute. /// </summary> /// <param name="route">Stream.</param> public void AddRoute(Route route) { // set the default color if none is given. var blue = SimpleColor.FromKnownColor(KnownColor.Blue); var transparantBlue = SimpleColor.FromArgb(128, blue.R, blue.G, blue.B); this.AddRoute(route, transparantBlue.Value); }
/// <summary> /// Returns the canvas color. /// </summary> /// <returns></returns> public override SimpleColor GetCanvasColor() { if (_mapCSSFile != null && _mapCSSFile.CanvasFillColor.HasValue) { // instantiate the simple color. return(new SimpleColor() { Value = _mapCSSFile.CanvasFillColor.Value }); } return(SimpleColor.FromKnownColor(KnownColor.Black)); }
public void TestCanvasSettingsCSS() { // create CSS. string css = "canvas { " + "fill-color: green; " + "} "; // create 'test' objects. Node node1 = new Node(); node1.Id = 1; node1.Latitude = 1; node1.Longitude = 1; Node node2 = new Node(); node2.Id = 2; node2.Latitude = 2; node2.Longitude = 2; Way way = new Way(); way.Id = 1; way.Nodes = new List <long>(); way.Nodes.Add(1); way.Nodes.Add(2); // create the datasource. MemoryDataSource dataSource = new MemoryDataSource(); dataSource.AddNode(node1); dataSource.AddNode(node2); dataSource.AddWay(way); // create the projection and scene objects. var mercator = new WebMercator(); Scene2D scene = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), 16); // create the interpreter. MapCSSInterpreter interpreter = new MapCSSInterpreter(css, new MapCSSDictionaryImageSource()); interpreter.Translate(scene, mercator, dataSource, node1); interpreter.Translate(scene, mercator, dataSource, node2); interpreter.Translate(scene, mercator, dataSource, way); // test the scene contents. Assert.AreEqual(0, scene.Count); Assert.AreEqual(SimpleColor.FromKnownColor(KnownColor.Green).Value, scene.BackColor); }
public void TestSimpleColorKnownColor() { SimpleColor simpleColor = SimpleColor.FromKnownColor(KnownColor.White); Assert.AreEqual(255, simpleColor.A); Assert.AreEqual(255, simpleColor.R); Assert.AreEqual(255, simpleColor.G); Assert.AreEqual(255, simpleColor.B); simpleColor = SimpleColor.FromKnownColor(KnownColor.Black); Assert.AreEqual(255, simpleColor.A); Assert.AreEqual(0, simpleColor.R); Assert.AreEqual(0, simpleColor.G); Assert.AreEqual(0, simpleColor.B); }
public void TestEmptyCSS() { // create 'test' objects. Node node1 = new Node(); node1.Id = 1; node1.Latitude = 1; node1.Longitude = 1; Node node2 = new Node(); node2.Id = 2; node2.Latitude = 2; node2.Longitude = 2; Way way = new Way(); way.Id = 1; way.Nodes = new List <long>(); way.Nodes.Add(1); way.Nodes.Add(2); // create the datasource. MemoryDataSource dataSource = new MemoryDataSource(); dataSource.AddNode(node1); dataSource.AddNode(node2); dataSource.AddWay(way); // create the projection and scene objects. var mercator = new WebMercator(); Scene2D scene = new Scene2DSimple(); // create the interpreter. MapCSSInterpreter interpreter = new MapCSSInterpreter(string.Empty, new MapCSSDictionaryImageSource()); interpreter.Translate(scene, mercator, dataSource, node1); interpreter.Translate(scene, mercator, dataSource, node2); interpreter.Translate(scene, mercator, dataSource, way); // test the scene contents. Assert.AreEqual(0, scene.Count); Assert.AreEqual(SimpleColor.FromKnownColor(KnownColor.Black).Value, scene.BackColor); }
public void TestSimpleColorFromHex() { SimpleColor color = SimpleColor.FromKnownColor(KnownColor.Red); Assert.AreEqual(color.Value, SimpleColor.FromHex(color.HexRgb).Value); color = SimpleColor.FromKnownColor(KnownColor.Blue); Assert.AreEqual(color.Value, SimpleColor.FromHex(color.HexRgb).Value); color = SimpleColor.FromKnownColor(KnownColor.Yellow); Assert.AreEqual(color.Value, SimpleColor.FromHex(color.HexRgb).Value); color = SimpleColor.FromKnownColor(KnownColor.Green); Assert.AreEqual(color.Value, SimpleColor.FromHex(color.HexRgb).Value); color = SimpleColor.FromKnownColor(KnownColor.White); Assert.AreEqual(color.Value, SimpleColor.FromHex(color.HexRgb).Value); }
/// <summary> /// Initialize implementation from IMapView. /// </summary> /// <param name="mapLayout"></param> void IMapViewSurface.Initialize(MapView mapLayout) { this.MapAllowPan = true; this.MapAllowTilt = true; this.MapAllowZoom = true; // register default invalidation trigger. (this as IInvalidatableMapSurface).RegisterListener(new DefaultTrigger(this)); _mapView = mapLayout; this.SetWillNotDraw(false); // this.SetWillNotCacheDrawing(true); this.MapMinZoomLevel = 0; this.MapMaxZoomLevel = 20; // gets the system density. _density = global::Android.Content.Res.Resources.System.DisplayMetrics.Density; _bufferFactor = _density; // set default scale factor relative to density. // create the renderer. _renderer = new MapRenderer <global::Android.Graphics.Canvas>( new CanvasRenderer2D(1)); // initialize the gesture detection. this.SetOnTouchListener(this); _scaleGestureDetector = new ScaleGestureDetector( this.Context, this); _rotateGestureDetector = new RotateGestureDetector( this.Context, this); _moveGestureDetector = new MoveGestureDetector( this.Context, this); _tagGestureDetector = new TapGestureDetector( this.Context, this); _makerLayer = new LayerPrimitives( new WebMercator()); // initialize all the caching stuff. _backgroundColor = SimpleColor.FromKnownColor(KnownColor.White).Value; _cacheRenderer = new MapRenderer <global::Android.Graphics.Canvas>( new CanvasRenderer2D(1)); }
private void UserPositionChanged(object sender, PositionEventArgs e) { if (layerUser != null && IsShowingUser) { var center = new GeoCoordinate(e.Position.Latitude, e.Position.Longitude); layerUser.Clear(); layerAccuracy.Clear(); if (IsShowingUserInCenter) { mapView.MapCenter = center; } layerAccuracy.AddPoint(center, 2.2f + mapView.Density * (float)e.Position.Accuracy, SimpleColor.FromArgb(32, 0, 0, 255).Value); layerUser.AddPoint(center, mapView.Density * 2.2f, SimpleColor.FromKnownColor(KnownColor.Blue).Value); layerUser.AddPoint(center, mapView.Density * 1.8f, SimpleColor.FromKnownColor(KnownColor.White).Value); layerUser.AddPoint(center, mapView.Density * 1.2f, SimpleColor.FromKnownColor(KnownColor.Blue).Value); } }
/// <summary> /// Initialize this instance. /// </summary> void Initialize() { // create the Open GL 2D target. _target = new OpenGLTarget2D(); this.SetRenderer(_target); // initialize the gesture detection. _gestureDetector = new GestureDetector( this); _scaleGestureDetector = new ScaleGestureDetector( this.Context, this); this.SetOnTouchListener(this); // create the renderer. _renderer = new MapRenderer <OpenGLTarget2D>( new OpenGLRenderer2D()); // initialize the scene. _scene = new Scene2DSimple(); _scene.BackColor = SimpleColor.FromKnownColor(KnownColor.White).Value; }
/// <summary> /// Raises the draw frame event. /// </summary> /// <param name="gl">Gl.</param> public void OnDrawFrame(IGL10 gl) { lock (_triangles) { // Replace the current matrix with the identity matrix gl.GlMatrixMode(GL10.GlProjection); gl.GlLoadIdentity(); // OpenGL docs gl.GlOrthof(_left, _right, _bottom, _top, -1, 1); SimpleColor color = SimpleColor.FromKnownColor(KnownColor.White); gl.GlClearColor(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f); gl.GlClear(GL10.GlColorBufferBit); for (int idx = 0; idx < _triangles.Count; idx++) { gl.GlVertexPointer(3, GL10.GlFloat, 0, _triangles[idx].Vertices); gl.GlEnableClientState(GL10.GlVertexArray); gl.GlColorPointer(4, GL10.GlUnsignedByte, 0, _triangles[idx].Colors); gl.GlEnableClientState(GL10.GlColorArray); gl.GlDrawArrays(GL10.GlTriangleStrip, 0, _triangles[idx].Count); } for (int idx = 0; idx < _lines.Count; idx++) { gl.GlVertexPointer(3, GL10.GlFloat, 0, _lines[idx].Vertices); gl.GlEnableClientState(GL10.GlVertexArray); color = new SimpleColor() { Value = _lines[idx].Color }; gl.GlColor4f(color.R / 255f, color.G / 255f, color.B / 255f, color.A / 255f); gl.GlLineWidth(_lines[idx].Width); gl.GlDrawArrays(GL10.GlLineStrip, 0, _lines[idx].Count); } } }
public void TestMapCSSCanvasRendering() { // create the data source. MemoryDataSource source = new MemoryDataSource(); // define the MapCSS file. string css = "canvas { " + "fill-color: green; " + "} "; // do the rendering. Bitmap rendering = this.Render(source, css); // check result. for (int x = 0; x < 100; x++) { for (int y = 0; y < 100; y++) { Assert.AreEqual(SimpleColor.FromKnownColor(OsmSharp.UI.KnownColor.Green).Value, rendering.GetPixel(x, y).ToArgb()); } } }
public async Task <Primitive2D> SearchPrimitiveAsync(GeoCoordinate coordinate, CancellationToken cancellationToken) { try { return(await Task.Run(() => { var scene = CurrentScene; var zoomFactor = (float)Map.Projection.ToZoomFactor(scene.Zoom); var view = CreateView(CurrentScene); var point = ToPixels(coordinate, scene); var backColor = SimpleColor.FromKnownColor(KnownColor.Transparent).Value; var objs = new List <Primitive2D>(); for (int i = 0; i < Map.LayerCount; i++) { if (cancellationToken.IsCancellationRequested) { return null; } var layer = Map[i]; if (layer.IsLayerVisibleFor((float)scene.Zoom)) { objs.AddRange(layer.Get(zoomFactor, view)); } } objs.Reverse(); foreach (var obj in objs.Where(o => o != null && o.ToolTip != null)) { if (cancellationToken.IsCancellationRequested) { return null; } var context = new RenderContext(SceneSize); _renderer.SceneRenderer.Render(context, view, zoomFactor, new[] { obj }, backColor); var image = context.BuildScene(); image.Freeze(); int bytePerPixel = (image.Format.BitsPerPixel + 7) / 8; int stride = image.PixelWidth *bytePerPixel; byte[] data = new byte[stride *image.PixelHeight]; image.CopyPixels(data, stride, 0); //Pbgra32 var pixel = new byte[bytePerPixel]; var offset = stride * (int)point.Y + (int)point.X *bytePerPixel; for (int i = 0; i < bytePerPixel; i++) { pixel[i] = data[offset + i]; } if (pixel.Any(p => p != 0)) { return obj; } } return null; }, cancellationToken)); } catch (TaskCanceledException) { return(null); } }
/// <summary> /// Initializes the View property. /// </summary> public override void LoadView() { base.LoadView(); // initialize OsmSharp native hooks. Native.Initialize(); // enable the loggging. OsmSharp.Logging.Log.Enable(); OsmSharp.Logging.Log.RegisterListener(new OsmSharp.iOS.UI.Log.ConsoleTraceListener()); // initialize map. var map = new Map(); // add a tile layer. map.AddLayer(new LayerTile(@"http://otile1.mqcdn.com/tiles/1.0.0/osm/{0}/{1}/{2}.png")); // map.AddLayer(new LayerMBTile(SQLiteConnection.CreateFrom( // Assembly.GetExecutingAssembly().GetManifestResourceStream(@"OsmSharp.iOS.UI.Sample.kempen.mbtiles"), "map"))); // add an online osm-data->mapCSS translation layer. //map.AddLayer(new OsmLayer(dataSource, mapCSSInterpreter)); // add a pre-processed vector data file. // var sceneStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( // "OsmSharp.iOS.UI.Sample.default.map"); // map.AddLayer(new LayerScene(Scene2D.Deserialize(sceneStream, true))); var primitivesLayer = new LayerPrimitives(map.Projection); primitivesLayer.AddPoint(new GeoCoordinate(51.26371, 4.78601), 10, SimpleColor.FromKnownColor(KnownColor.Blue).Value); map.AddLayer(primitivesLayer); // // define dummy from and to points. var from = new GeoCoordinate(51.261203, 4.780760); var to = new GeoCoordinate(51.267797, 4.801362); // // // deserialize the pre-processed graph. // var routingSerializer = new CHEdgeDataDataSourceSerializer(false); // TagsCollectionBase metaData = null; // var graphStream = Assembly.GetExecutingAssembly().GetManifestResourceStream( // "OsmSharp.iOS.UI.Sample.kempen-big.osm.pbf.routing"); // var graphDeserialized = routingSerializer.Deserialize(graphStream, out metaData, true); // // // initialize router. // _router = Router.CreateCHFrom(graphDeserialized, new CHRouter(), new OsmRoutingInterpreter()); // // // resolve points. // RouterPoint routerPoint1 = _router.Resolve(Vehicle.Car, from); // RouterPoint routerPoint2 = _router.Resolve(Vehicle.Car, to); // // // calculate route. // Route route = _router.Calculate(Vehicle.Car, routerPoint1, routerPoint2); // RouteTracker routeTracker = new RouteTracker(route, new OsmRoutingInterpreter()); // _enumerator = route.GetRouteEnumerable(10).GetEnumerator(); // // // add a router layer. // _routeLayer = new LayerRoute(map.Projection); // _routeLayer.AddRoute (route, SimpleColor.FromKnownColor(KnownColor.Blue, 125).Value, 12); // map.AddLayer(_routeLayer); // define the mapview. _mapView = new MapView(); //_mapView.MapTapEvent += new MapViewEvents.MapTapEventDelegate(_mapView_MapTapEvent); _mapView.MapAllowTilt = false; _mapView.Map = map; _mapView.MapMaxZoomLevel = 19; _mapView.MapMinZoomLevel = 0; _mapView.MapTilt = 0; _mapView.MapCenter = new GeoCoordinate(51.26371, 4.78601); _mapView.MapZoom = 18; // add markers. // _mapView.AddMarker (from); _mapView.AddMarker(to); // add control. var textView = new UITextView(); textView.Text = "Hey, now there's text on top of the map! Yay!"; textView.BackgroundColor = UIColor.FromWhiteAlpha(0.5f, 0.5f); var textViewControl = new MapControl <UITextView>(textView, from, MapControlAlignmentType.CenterBottom, 75, 75); _mapView.AddControl(textViewControl); // create the route tracker animator. // _routeTrackerAnimator = new RouteTrackerAnimator(_mapView, routeTracker, 5, 17); // // simulate a number of gps-location update along the calculated route. // Timer timer = new Timer(250); // timer.Elapsed += new ElapsedEventHandler(TimerHandler); // timer.Start(); View = _mapView; }
/// <summary> /// Renders the current complete scene. /// </summary> void Render() { if (_cacheRenderer.IsRunning) { _cacheRenderer.CancelAndWait(); } // make sure only on thread at the same time is using the renderer. lock (_cacheRenderer) { double extra = 1.25; // build the layers list. var layers = new List <ILayer> (); for (int layerIdx = 0; layerIdx < this.Map.LayerCount; layerIdx++) { // get the layer. layers.Add(this.Map[layerIdx]); } // add the internal layers. layers.Add(_makerLayer); // create a new cache if size has changed. if (_canvasBitmap == null || _canvasBitmap.Width != (int)(this.Width * extra) || _canvasBitmap.Height != (int)(this.Height * extra)) { // create a bitmap and render there. _canvasBitmap = global::Android.Graphics.Bitmap.CreateBitmap((int)(this.Width * extra), (int)(this.Height * extra), global::Android.Graphics.Bitmap.Config.Argb8888); } else { // clear the cache??? } // create and reset the canvas. global::Android.Graphics.Canvas canvas = new global::Android.Graphics.Canvas(_canvasBitmap); canvas.DrawColor(new global::Android.Graphics.Color( SimpleColor.FromKnownColor(KnownColor.Transparent).Value)); // create the view. View2D view = _cacheRenderer.Create(canvas.Width, canvas.Height, this.Map, (float)this.Map.Projection.ToZoomFactor(this.MapZoomLevel), this.MapCenter, _invertX, _invertY); long before = DateTime.Now.Ticks; OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", System.Diagnostics.TraceEventType.Information, "Rendering Start"); // notify the map that the view has changed. this.Map.ViewChanged((float)this.Map.Projection.ToZoomFactor(this.MapZoomLevel), this.MapCenter, view); long afterViewChanged = DateTime.Now.Ticks; OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", System.Diagnostics.TraceEventType.Information, "View change took: {0}ms @ zoom level {1}", (new TimeSpan(afterViewChanged - before).TotalMilliseconds), this.MapZoomLevel); // add the current canvas to the scene. double left = view.LeftTop [0]; double right = view.RightTop [0]; double top = view.LeftTop [1]; double bottom = view.LeftBottom [1]; uint canvasId = _scene.AddImage(-1, float.MinValue, float.MaxValue, left, top, right, bottom, new byte[0], _canvasBitmap); // does the rendering. bool complete = _cacheRenderer.Render(canvas, layers, view); long afterRendering = DateTime.Now.Ticks; OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", System.Diagnostics.TraceEventType.Information, "Rendering took: {0}ms @ zoom level {1}", (new TimeSpan(afterRendering - afterViewChanged).TotalMilliseconds), this.MapZoomLevel); if (complete) { // there was no cancellation, the rendering completely finished. // add the result to the scene cache. lock (_scene) { // if (_previousCache.HasValue) { // _scene.Remove (_previousCache.Value); // } // _scene.Remove (canvasId); // // add the newly rendered image again. _scene.Clear(); //_previousCache = BoxF2D viewBox = view.OuterBox; _scene.AddImage(0, float.MinValue, float.MaxValue, viewBox.Min[0], viewBox.Min[1], viewBox.Max[0], viewBox.Max[1], new byte[0], _canvasBitmap); // switch cache and canvas to prevent re-allocation of bitmaps. global::Android.Graphics.Bitmap newCanvas = _cache; _cache = _canvasBitmap; _canvasBitmap = newCanvas; } } this.PostInvalidate(); long after = DateTime.Now.Ticks; if (!complete) { OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", System.Diagnostics.TraceEventType.Information, "Rendering in {0}ms after cancellation!", new TimeSpan(after - before).TotalMilliseconds); } else { OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", System.Diagnostics.TraceEventType.Information, "Rendering in {0}ms", new TimeSpan(after - before).TotalMilliseconds); } } }
/// <summary> /// Translates a node. /// </summary> /// <param name="scene">The scene to add primitives to.</param> /// <param name="projection">The projection used to convert the objects.</param> /// <param name="node"></param> private void TranslateNode(Scene2D scene, IProjection projection, CompleteNode node) { // build the rules. IEnumerable <MapCSSRuleProperties> rules = this.BuildRules(new MapCSSObject(node)); // interpret the results. foreach (var rule in rules) { int zIndex; if (!rule.TryGetProperty <int>("zIndex", out zIndex)) { zIndex = 0; } float minZoom = (float)projection.ToZoomFactor(rule.MinZoom); float maxZoom = (float)projection.ToZoomFactor(rule.MaxZoom); uint?pointId = null; int color; if (rule.TryGetProperty <int>("color", out color)) { float width; if (rule.TryGetProperty <float>("width", out width)) { pointId = scene.AddPoint(projection.LongitudeToX(node.Coordinate.Longitude), projection.LatitudeToY(node.Coordinate.Latitude)); scene.AddStylePoint(pointId.Value, this.CalculateSceneLayer(OffsetPoint, zIndex), minZoom, maxZoom, color, width); } else { pointId = scene.AddPoint(projection.LongitudeToX(node.Coordinate.Longitude), projection.LatitudeToY(node.Coordinate.Latitude)); scene.AddStylePoint(pointId.Value, this.CalculateSceneLayer(OffsetPoint, zIndex), minZoom, maxZoom, color, 1); } } byte[] iconImage; if (rule.TryGetProperty("iconImage", out iconImage)) { if (!pointId.HasValue) { pointId = scene.AddPoint(projection.LongitudeToX(node.Coordinate.Longitude), projection.LatitudeToY(node.Coordinate.Latitude)); } // an icon is to be drawn! ushort imageId = scene.AddImage(iconImage); scene.AddIcon(pointId.Value, this.CalculateSceneLayer(OffsetPoint, zIndex), minZoom, maxZoom, imageId); } string text; if (rule.TryGetProperty("text", out text)) { int textColor; if (!rule.TryGetProperty("textColor", out textColor)) { textColor = SimpleColor.FromKnownColor(KnownColor.Black).Value; } int haloColor; int?haloColorNullable = null; if (rule.TryGetProperty("textHaloColor", out haloColor)) { haloColorNullable = haloColor; } int haloRadius; int?haloRadiusNullable = null; if (rule.TryGetProperty("textHaloRadius", out haloRadius)) { haloRadiusNullable = haloRadius; } int fontSize; if (!rule.TryGetProperty("fontSize", out fontSize)) { fontSize = 10; } string fontFamily; if (!rule.TryGetProperty("fontFamily", out fontFamily)) { fontFamily = "Arial"; // just some default font. } // a text is to be drawn. string value; if (node.Tags.TryGetValue(text, out value)) { if (!pointId.HasValue) { pointId = scene.AddPoint(projection.LongitudeToX(node.Coordinate.Longitude), projection.LatitudeToY(node.Coordinate.Latitude)); } scene.AddText(pointId.Value, this.CalculateSceneLayer(OffsetPointText, zIndex), minZoom, maxZoom, fontSize, value, textColor, haloColorNullable, haloRadiusNullable, fontFamily); } } } }
/// <summary> /// Translates OSM objects into basic renderable primitives. /// </summary> /// <param name="scene">The scene to add primitives to.</param> /// <param name="projection">The projection used to convert the objects.</param> /// <param name="osmGeo">The osm object.</param> /// <returns></returns> public override void Translate(Scene2D scene, IProjection projection, CompleteOsmGeo osmGeo) { // set the scene backcolor. scene.BackColor = this.GetCanvasColor().Value; if (osmGeo == null) { return; } // store the object count. int countBefore = scene.Count; // interpret the osm-objects. switch (osmGeo.Type) { case CompleteOsmType.Node: this.TranslateNode(scene, projection, osmGeo as CompleteNode); break; case CompleteOsmType.Way: this.TranslateWay(scene, projection, osmGeo as CompleteWay); break; case CompleteOsmType.Relation: this.TranslateRelation(scene, projection, osmGeo as CompleteRelation); break; case CompleteOsmType.ChangeSet: break; default: throw new ArgumentOutOfRangeException(); } // interpret the osmGeo object and check if it makes up an area. GeometryCollection collection = _geometryInterpreter.Interpret(osmGeo); foreach (Geometry geometry in collection) { if (geometry is LineairRing) { // a simple lineair ring. this.TranslateLineairRing(scene, projection, geometry as LineairRing); } else if (geometry is Polygon) { // a simple polygon. this.TranslatePolygon(scene, projection, geometry as Polygon); } else if (geometry is MultiPolygon) { // a multipolygon. this.TranslateMultiPolygon(scene, projection, geometry as MultiPolygon); } } // check if any objects have been added to the scene. if (scene.Count <= countBefore) { // no objects have been added. Apply default styles if needed. if (osmGeo.Type == CompleteOsmType.Node && _mapCSSFile != null && _mapCSSFile.DefaultPoints) { // apply default points style. CompleteNode node = (osmGeo as CompleteNode); uint pointId = scene.AddPoint(projection.LongitudeToX(node.Coordinate.Longitude), projection.LatitudeToY(node.Coordinate.Latitude)); scene.AddStylePoint(pointId, this.CalculateSceneLayer(OffsetPoint, 0), float.MinValue, float.MaxValue, SimpleColor.FromKnownColor(KnownColor.Black).Value, 2); } else if (osmGeo.Type == CompleteOsmType.Way && _mapCSSFile != null && _mapCSSFile.DefaultLines) { // apply default lines style. CompleteWay way = (osmGeo as CompleteWay); // get x/y. double[] x = null, y = null; if (x == null) { // pre-calculate x/y. x = new double[way.Nodes.Count]; y = new double[way.Nodes.Count]; for (int idx = 0; idx < way.Nodes.Count; idx++) { x[idx] = projection.LongitudeToX( way.Nodes[idx].Coordinate.Longitude); y[idx] = projection.LatitudeToY( way.Nodes[idx].Coordinate.Latitude); } // simplify. if (x.Length > 2) { double[][] simplified = SimplifyCurve.Simplify(new double[][] { x, y }, 0.0001); x = simplified[0]; y = simplified[1]; } } uint?points = scene.AddPoints(x, y); if (points.HasValue) { scene.AddStyleLine(points.Value, this.CalculateSceneLayer(OffsetLine, 0), float.MinValue, float.MaxValue, SimpleColor.FromKnownColor(KnownColor.Red).Value, 1, LineJoin.Round, null); } } } }
public void TestCanvasJOSMSettingsCSS() { // create CSS. string css = "canvas { " + "background-color: white; " + "default-points: true; " + // adds default points for every node (color: black, size: 2). "default-lines: true; " + // adds default lines for every way (color: red, width: 1). "} "; // create 'test' objects. Node node1 = new Node(); node1.Id = 1; node1.Latitude = 1; node1.Longitude = 1; Node node2 = new Node(); node2.Id = 2; node2.Latitude = 2; node2.Longitude = 2; Way way = new Way(); way.Id = 1; way.Nodes = new List <long>(); way.Nodes.Add(1); way.Nodes.Add(2); // create the datasource. MemoryDataSource dataSource = new MemoryDataSource(); dataSource.AddNode(node1); dataSource.AddNode(node2); dataSource.AddWay(way); // create the projection and scene objects. var mercator = new WebMercator(); Scene2D scene = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), 16); // create the interpreter. MapCSSInterpreter interpreter = new MapCSSInterpreter(css, new MapCSSDictionaryImageSource()); interpreter.Translate(scene, mercator, dataSource, node1); interpreter.Translate(scene, mercator, dataSource, node2); interpreter.Translate(scene, mercator, dataSource, way); // test the scene contents. Assert.AreEqual(3, scene.Count); Assert.AreEqual(SimpleColor.FromKnownColor(KnownColor.White).Value, scene.BackColor); // test the scene point 1. Primitive2D primitive = scene.Get(0); Assert.IsNotNull(primitive); Assert.IsInstanceOf <Primitive2D>(primitive); Point2D pointObject = primitive as Point2D; Assert.AreEqual(2, pointObject.Size); Assert.AreEqual(SimpleColor.FromKnownColor(KnownColor.Black).Value, pointObject.Color); Assert.AreEqual(mercator.LongitudeToX(1), pointObject.X); Assert.AreEqual(mercator.LatitudeToY(1), pointObject.Y); // test the scene point 2. primitive = scene.Get(1); Assert.IsNotNull(primitive); Assert.IsInstanceOf <Point2D>(primitive); pointObject = primitive as Point2D; Assert.AreEqual(2, pointObject.Size); Assert.AreEqual(SimpleColor.FromKnownColor(KnownColor.Black).Value, pointObject.Color); Assert.AreEqual(mercator.LongitudeToX(2), pointObject.X); Assert.AreEqual(mercator.LatitudeToY(2), pointObject.Y); // test the scene line 2. primitive = scene.Get(2); Assert.IsNotNull(primitive); Assert.IsInstanceOf <Line2D>(primitive); Line2D line = primitive as Line2D; Assert.AreEqual(1, line.Width); Assert.AreEqual(SimpleColor.FromKnownColor(KnownColor.Red).Value, line.Color); Assert.IsNotNull(line.X); Assert.IsNotNull(line.Y); Assert.AreEqual(2, line.X.Length); Assert.AreEqual(2, line.Y.Length); Assert.AreEqual(mercator.LongitudeToX(1), line.X[0]); Assert.AreEqual(mercator.LatitudeToY(1), line.Y[0]); Assert.AreEqual(mercator.LongitudeToX(2), line.X[1]); Assert.AreEqual(mercator.LatitudeToY(2), line.Y[1]); }
/// <summary> /// Renders the current complete scene. /// </summary> void Render() { if (_cacheRenderer.IsRunning) { _cacheRenderer.CancelAndWait(); } // make sure only on thread at the same time is using the renderer. lock (_cacheRenderer) { double extra = 1.25; // build the layers list. var layers = new List <ILayer> (); for (int layerIdx = 0; layerIdx < this.Map.LayerCount; layerIdx++) { // get the layer. layers.Add(this.Map[layerIdx]); } // add the internal layers. layers.Add(_makerLayer); // create a new cache if size has changed. if (_canvasBitmap == null || _canvasBitmap.Width != (int)(this.Width * extra) || _canvasBitmap.Height != (int)(this.Height * extra)) { // create a bitmap and render there. _canvasBitmap = global::Android.Graphics.Bitmap.CreateBitmap((int)(this.Width * extra), (int)(this.Height * extra), global::Android.Graphics.Bitmap.Config.Argb8888); } else { // clear the cache??? } // create and reset the canvas. global::Android.Graphics.Canvas canvas = new global::Android.Graphics.Canvas(_canvasBitmap); canvas.DrawColor(new global::Android.Graphics.Color( SimpleColor.FromKnownColor(KnownColor.Transparent).Value)); // create the view. double[] sceneCenter = this.Map.Projection.ToPixel(this.MapCenter.Latitude, this.MapCenter.Longitude); float sceneZoomFactor = (float)this.Map.Projection.ToZoomFactor(this.MapZoom); // create the view for this control. View2D view = View2D.CreateFrom((float)sceneCenter[0], (float)sceneCenter[1], this.Width * extra, this.Height * extra, sceneZoomFactor, _invertX, _invertY, this.MapTilt); long before = DateTime.Now.Ticks; OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", System.Diagnostics.TraceEventType.Information, "Rendering Start"); // notify the map that the view has changed. this.Map.ViewChanged((float)this.Map.Projection.ToZoomFactor(this.MapZoom), this.MapCenter, view); long afterViewChanged = DateTime.Now.Ticks; OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", System.Diagnostics.TraceEventType.Information, "View change took: {0}ms @ zoom level {1}", (new TimeSpan(afterViewChanged - before).TotalMilliseconds), this.MapZoom); // add the current canvas to the scene. _scene.AddImage(-1, float.MaxValue, float.MinValue, view.Rectangle, new byte[0], _canvasBitmap); // does the rendering. bool complete = _cacheRenderer.Render(canvas, layers, view); long afterRendering = DateTime.Now.Ticks; OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", System.Diagnostics.TraceEventType.Information, "Rendering took: {0}ms @ zoom level {1}", (new TimeSpan(afterRendering - afterViewChanged).TotalMilliseconds), this.MapZoom); if (complete) { // there was no cancellation, the rendering completely finished. // add the result to the scene cache. lock (_scene) { // add the newly rendered image again. _scene.Clear(); _scene.AddImage(0, float.MinValue, float.MaxValue, view.Rectangle, new byte[0], _canvasBitmap); // switch cache and canvas to prevent re-allocation of bitmaps. global::Android.Graphics.Bitmap newCanvas = _cache; _cache = _canvasBitmap; _canvasBitmap = newCanvas; } } this.PostInvalidate(); long after = DateTime.Now.Ticks; } }
/// <summary> /// Raises the create event. /// </summary> /// <param name="bundle">Bundle.</param> protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // enable the logggin. OsmSharp.Logging.Log.Enable(); OsmSharp.Logging.Log.RegisterListener(new OsmSharp.Android.UI.Log.LogTraceListener()); // initialize map. var map = new Map(); // add a tile layer. //map.AddLayer(new LayerTile(@"http://otile1.mqcdn.com/tiles/1.0.0/osm/{0}/{1}/{2}.png")); // add an online osm-data->mapCSS translation layer. //map.AddLayer(new OsmLayer(dataSource, mapCSSInterpreter)); // add a pre-processed vector data file. var sceneStream = Assembly.GetExecutingAssembly().GetManifestResourceStream(@"OsmSharp.Android.UI.Sample.default.map"); map.AddLayer(new LayerScene(Scene2D.Deserialize(sceneStream, true))); // define dummy from and to points. var from = new GeoCoordinate(51.261203, 4.780760); var to = new GeoCoordinate(51.267797, 4.801362); // deserialize the pre-processed graph. var routingSerializer = new CHEdgeDataDataSourceSerializer(false); TagsCollectionBase metaData = null; var graphStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("OsmSharp.Android.UI.Sample.kempen-big.osm.pbf.routing"); var graphDeserialized = routingSerializer.Deserialize(graphStream, out metaData, true); // initialize router. _router = Router.CreateCHFrom(graphDeserialized, new CHRouter(), new OsmRoutingInterpreter()); // resolve points. RouterPoint routerPoint1 = _router.Resolve(Vehicle.Car, from); RouterPoint routerPoint2 = _router.Resolve(Vehicle.Car, to); // calculate route. Route route = _router.Calculate(Vehicle.Car, routerPoint1, routerPoint2); RouteTracker routeTracker = new RouteTracker(route, new OsmRoutingInterpreter()); _enumerator = route.GetRouteEnumerable(10).GetEnumerator(); // add a router layer. _routeLayer = new LayerRoute(map.Projection); _routeLayer.AddRoute(route, SimpleColor.FromKnownColor(KnownColor.Blue, 125).Value, 12); map.AddLayer(_routeLayer); // define the mapview. _mapView = new MapView(this, new MapViewSurface(this)); //_mapView = new MapView(this, new MapViewGLSurface(this)); //_mapView.MapTapEvent += new MapViewEvents.MapTapEventDelegate(_mapView_MapTapEvent); _mapView.Map = map; _mapView.MapMaxZoomLevel = 20; _mapView.MapMinZoomLevel = 10; _mapView.MapTilt = 0; _mapView.MapCenter = new GeoCoordinate(51.26371, 4.78601); _mapView.MapZoom = 18; // add markers. _mapView.AddMarker(from); _mapView.AddMarker(to); // initialize a text view to display routing instructions. _textView = new TextView(this); _textView.SetBackgroundColor(global::Android.Graphics.Color.White); _textView.SetTextColor(global::Android.Graphics.Color.Black); // add the mapview to the linear layout. var layout = new LinearLayout(this); layout.Orientation = Orientation.Vertical; layout.AddView(_textView); layout.AddView(_mapView); // create the route tracker animator. _routeTrackerAnimator = new RouteTrackerAnimator(_mapView, routeTracker, 5, 17); // simulate a number of gps-location update along the calculated route. Timer timer = new Timer(250); timer.Elapsed += new ElapsedEventHandler(TimerHandler); timer.Start(); SetContentView(layout); }
/// <summary> /// Renders the current complete scene. /// </summary> private void Render() { try { if (_renderingSuspended) { // no rendering when rendering is suspended. return; } if (_cacheRenderer.IsRunning) { // cancel previous render. _cacheRenderer.CancelAndWait(); } // make sure only on thread at the same time is using the renderer. lock (_cacheRenderer) { this.Map.ViewChangedCancel(); // build the layers list. var layers = new List <Layer>(); for (int layerIdx = 0; layerIdx < this.Map.LayerCount; layerIdx++) { // get the layer. if (this.Map[layerIdx].IsVisible) { layers.Add(this.Map[layerIdx]); } } // add the internal layers. layers.Add(_makerLayer); if (this.SurfaceHeight == 0) { // the surface has no height yet. Impossible to render like this. return; } // get old image if available. NativeImage image = null; if (_offScreenBuffer != null) { // get the native image from the off-screen buffer. image = _offScreenBuffer.NativeImage as NativeImage; } // resize image if needed. float sizeX = this.SurfaceWidth; float sizeY = this.SurfaceHeight; //if(this.MapAllowTilt) //{ // when rotation is allowed make sure a square is rendered. // sizeX = System.Math.Max(this.SurfaceWidth, this.SurfaceHeight); // sizeY = System.Math.Max(this.SurfaceWidth, this.SurfaceHeight); //} // float size = System.Math.Max(this.SurfaceHeight, this.SurfaceWidth); if (image == null || image.Image.Width != (int)(sizeX * _extra) || image.Image.Height != (int)(sizeY * _extra)) { // create a bitmap and render there. if (image != null) { // make sure to dispose the old image. image.Dispose(); } image = new NativeImage(global::Android.Graphics.Bitmap.CreateBitmap((int)(sizeX * _extra), (int)(sizeY * _extra), global::Android.Graphics.Bitmap.Config.Argb8888)); } // create and reset the canvas. using (var canvas = new global::Android.Graphics.Canvas(image.Image)) { canvas.DrawColor(new global::Android.Graphics.Color( SimpleColor.FromKnownColor(KnownColor.White).Value)); // create the view. double[] sceneCenter = this.Map.Projection.ToPixel(this.MapCenter.Latitude, this.MapCenter.Longitude); float mapZoom = this.MapZoom; float sceneZoomFactor = (float)this.Map.Projection.ToZoomFactor(this.MapZoom); // create the view for this control. float scaledNormalWidth = image.Image.Width / _bufferFactor; float scaledNormalHeight = image.Image.Height / _bufferFactor; var view = View2D.CreateFrom((float)sceneCenter[0], (float)sceneCenter[1], scaledNormalWidth * _extra, scaledNormalHeight * _extra, sceneZoomFactor, _invertX, _invertY, this.MapTilt); long before = DateTime.Now.Ticks; OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", TraceEventType.Information, "Rendering Start"); // notify the map that the view has changed. if (_previouslyChangedView == null || !_previouslyChangedView.Equals(view)) { // report change once! var normalView = View2D.CreateFrom((float)sceneCenter[0], (float)sceneCenter[1], scaledNormalWidth, scaledNormalHeight, sceneZoomFactor, _invertX, _invertY, this.MapTilt); this.Map.ViewChanged((float)this.Map.Projection.ToZoomFactor(this.MapZoom), this.MapCenter, normalView, view); _previouslyChangedView = view; long afterViewChanged = DateTime.Now.Ticks; OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", TraceEventType.Information, "View change took: {0}ms @ zoom level {1}", (new TimeSpan(afterViewChanged - before).TotalMilliseconds), this.MapZoom); } // does the rendering. bool complete = _cacheRenderer.Render(canvas, layers, view, (float)this.Map.Projection.ToZoomFactor(this.MapZoom)); long afterRendering = DateTime.Now.Ticks; OsmSharp.Logging.Log.TraceEvent("OsmSharp.Android.UI.MapView", TraceEventType.Information, "Rendering took: {0}ms @ zoom level {1} and {2}", (new TimeSpan(afterRendering - before).TotalMilliseconds), this.MapZoom, this.MapCenter); if (complete) { // there was no cancellation, the rendering completely finished. // add the result to the scene cache. // add the newly rendered image again. if (_offScreenBuffer == null) { // create the offscreen buffer first. _offScreenBuffer = new ImageTilted2D(view.Rectangle, image, float.MinValue, float.MaxValue); } else { // augment the previous buffer. _offScreenBuffer.Bounds = view.Rectangle; _offScreenBuffer.NativeImage = image; } var temp = _onScreenBuffer; _onScreenBuffer = _offScreenBuffer; _offScreenBuffer = temp; } long after = DateTime.Now.Ticks; if (complete) { // report a successful render to listener. _listener.NotifyRenderSuccess(view, mapZoom, (int)new TimeSpan(after - before).TotalMilliseconds); } } } // notify the the current surface of the new rendering. this.PostInvalidate(); } catch (Exception ex) { // exceptions can be thrown when the mapview is disposed while rendering. // don't worry too much about these, the mapview is garbage anyway. OsmSharp.Logging.Log.TraceEvent("MapViewSurface", TraceEventType.Critical, string.Format("An unhandled exception occured:{0}", ex.ToString())); } }
private void DrawUserIcon(GeoCoordinate coord, double accuracy) { // If there no coordiantes, we have nothing to do if (coord == null) { return; } if (layerAccuracy == null) { // Create layer for accuracy layerAccuracy = new LayerPrimitives(map.Projection); // Add new accuracy layer map.AddLayer(layerAccuracy); } if (layerUser == null) { // Create layer for user icon layerUser = new LayerPrimitives(map.Projection); // Add layer for user icon map.AddLayer(layerUser); } var repaintUserIcon = coord.Latitude != lastKnownPosition?.Latitude || coord.Longitude != lastKnownPosition?.Longitude; var repaintAccuracy = true; // Stop painting layerAccuracy.Pause(); layerUser.Pause(); if (repaintAccuracy) { layerAccuracy.Clear(); } if (repaintUserIcon) { layerUser.Clear(); } if (IsShowingUserInCenter) { mapView.MapCenter = coord; } if (repaintAccuracy) { var size = 2.2f + mapView.Density * (float)accuracy; layerAccuracy.AddPoint(coord, size > 40 ? 40 : size, SimpleColor.FromArgb(32, 0, 0, 255).Value); } if (repaintUserIcon) { layerUser.AddPoint(coord, mapView.Density * 2.2f, SimpleColor.FromKnownColor(KnownColor.Blue).Value); layerUser.AddPoint(coord, mapView.Density * 1.8f, SimpleColor.FromKnownColor(KnownColor.White).Value); layerUser.AddPoint(coord, mapView.Density * 1.2f, SimpleColor.FromKnownColor(KnownColor.Blue).Value); } layerAccuracy.Resume(); layerUser.Resume(); }
/// <summary> /// Adds a new GPX. /// </summary> /// <param name="stream">Stream.</param> public GeoCoordinateBox AddGpx(Stream stream) { GeoCoordinateBox bounds = null; var gpxStream = new GpxGeoStreamSource(stream); foreach (var geometry in gpxStream) { if (geometry is Point) { // add the point. var point = (geometry as Point); // get x/y. var x = _projection.LongitudeToX(point.Coordinate.Longitude); var y = _projection.LatitudeToY(point.Coordinate.Latitude); // set the default color if none is given. SimpleColor blue = SimpleColor.FromKnownColor(KnownColor.Blue); SimpleColor transparantBlue = SimpleColor.FromArgb(128, blue.R, blue.G, blue.B); uint pointId = _scene.AddPoint(x, y); _scene.AddStylePoint(pointId, 0, float.MinValue, float.MaxValue, transparantBlue.Value, 8); if (bounds == null) { // create box. bounds = point.Box; } else { // add to the current box. bounds = bounds + point.Box; } } else if (geometry is LineString) { // add the lineString. var lineString = (geometry as LineString); // get x/y. var x = new double[lineString.Coordinates.Count]; var y = new double[lineString.Coordinates.Count]; for (int idx = 0; idx < lineString.Coordinates.Count; idx++) { x[idx] = _projection.LongitudeToX( lineString.Coordinates[idx].Longitude); y[idx] = _projection.LatitudeToY( lineString.Coordinates[idx].Latitude); } // set the default color if none is given. SimpleColor blue = SimpleColor.FromKnownColor(KnownColor.Blue); SimpleColor transparantBlue = SimpleColor.FromArgb(128, blue.R, blue.G, blue.B); uint?pointsId = _scene.AddPoints(x, y); if (pointsId.HasValue) { _scene.AddStyleLine(pointsId.Value, 0, float.MinValue, float.MaxValue, transparantBlue.Value, 8, Renderer.Primitives.LineJoin.Round, null); if (bounds == null) { // create box. bounds = lineString.Box; } else { // add to the current box. bounds = bounds + lineString.Box; } } } } return(bounds); }