Exemple #1
0
        public static PointF ToUIKit(this Point point)
        {
            double xo = OffSet.X;
            double yo = OffSet.Y;

            return(new PointF((float)(point.X - (xo)), (float)(point.Y - yo)));
        }
        public static XamlShapes.Shape RenderPoint(Point point, IStyle style, IViewport viewport)
        {
            XamlShapes.Shape symbol;
            var matrix = XamlMedia.Matrix.Identity;

            if (style is SymbolStyle)
            {
                var symbolStyle = style as SymbolStyle;

                if (symbolStyle.BitmapId < 0)
                    symbol = CreateSymbolFromVectorStyle(symbolStyle, symbolStyle.Opacity, symbolStyle.SymbolType, symbolStyle.Width, symbolStyle.Height);
                else
                    symbol = CreateSymbolFromBitmap(BitmapRegistry.Instance.Get(symbolStyle.BitmapId), symbolStyle.Opacity);
                matrix = CreatePointSymbolMatrix(viewport.Resolution, symbolStyle);
            }
            else
            {
                symbol = CreateSymbolFromVectorStyle((style as VectorStyle) ?? new VectorStyle());
                MatrixHelper.ScaleAt(ref matrix, viewport.Resolution, viewport.Resolution);
            }

            MatrixHelper.Append(ref matrix, CreateTransformMatrix(point, viewport));

            symbol.RenderTransform = new XamlMedia.MatrixTransform { Matrix = matrix };
            symbol.IsHitTestVisible = false;

            return symbol;
        }
 internal static IEnumerable<Point> WorldToScreen(LineString linearRing, IViewport viewport)
 {
     var v = new Point[linearRing.Vertices.Count];
     for (int i = 0; i < linearRing.Vertices.Count; i++)
         v[i] = viewport.WorldToScreen(linearRing.Vertices[i]);
     return v;
 }
        public static void DrawRaster(Graphics graphics, IGeometry feature, IStyle style, IViewport viewport)
        {
            var stream = ((IRaster)feature).Data;

            stream.Position = 0;
            var bitmap = new Bitmap(stream);

            Point min = viewport.WorldToScreen(new Point(feature.GetBoundingBox().MinX, feature.GetBoundingBox().MinY));
            Point max = viewport.WorldToScreen(new Point(feature.GetBoundingBox().MaxX, feature.GetBoundingBox().MaxY));

            Rectangle destination = RoundToPixel(new RectangleF((float)min.X, (float)max.Y, (float)(max.X - min.X), (float)(min.Y - max.Y)));

            graphics.DrawImage(bitmap,
                               destination,
                               0, 0, bitmap.Width, bitmap.Height,
                               GraphicsUnit.Pixel,
                               new ImageAttributes());

            if (DeveloperTools.DeveloperMode)
            {
                var font    = new System.Drawing.Font("Arial", 12);
                var message = (GC.GetTotalMemory(true) / 1000).ToString(CultureInfo.InvariantCulture) + " KB";
                graphics.DrawString(message, font, new SolidBrush(Color.Black), 10f, 10f);
            }

            bitmap.Dispose();
        }
Exemple #5
0
        public static UIElement RenderPoint(Point point, IStyle style, IViewport viewport)
        {
            UIElement symbol;
            var       matrix = XamlMedia.Matrix.Identity;

            if (style is SymbolStyle)
            {
                var symbolStyle = style as SymbolStyle;

                if (symbolStyle.BitmapId < 0)
                {
                    symbol = CreateSymbolFromVectorStyle(symbolStyle, symbolStyle.Opacity, symbolStyle.SymbolType);
                }
                else
                {
                    symbol = CreateSymbolFromBitmap(BitmapRegistry.Instance.Get(symbolStyle.BitmapId), symbolStyle.Opacity);
                }
                matrix = CreatePointSymbolMatrix(viewport.Resolution, symbolStyle);
            }
            else
            {
                symbol = CreateSymbolFromVectorStyle((style as VectorStyle) ?? new VectorStyle());
                MatrixHelper.ScaleAt(ref matrix, viewport.Resolution, viewport.Resolution);
            }

            MatrixHelper.Append(ref matrix, CreateTransformMatrix(point, viewport));

            symbol.RenderTransform = new XamlMedia.MatrixTransform {
                Matrix = matrix
            };

            symbol.IsHitTestVisible = false;

            return(symbol);
        }
Exemple #6
0
        public void setMaker()
        {
            Mapsui.Geometries.Point pWldPosi = Mapsui.Projection.SphericalMercator.FromLonLat((ImageInfo.startCoord.Lon + ImageInfo.endCoord.Lon) / 2, (ImageInfo.startCoord.Lat + ImageInfo.endCoord.Lat) / 2);
            Mapsui.Geometries.Point pWinPosi = MapControl.Map.Viewport.WorldToScreen(pWldPosi);
            iconMaker.Margin = new Thickness(pWinPosi.X - 20, pWinPosi.Y - 40, 0, 0);
            Mapsui.Geometries.Point pLB = MapControl.Map.Viewport.WorldToScreen(Mapsui.Projection.SphericalMercator.FromLonLat(ImageInfo.startCoord.Lon, ImageInfo.startCoord.Lat));
            Mapsui.Geometries.Point pRT = MapControl.Map.Viewport.WorldToScreen(Mapsui.Projection.SphericalMercator.FromLonLat(ImageInfo.endCoord.Lon, ImageInfo.endCoord.Lat));

            double len0 = 5;
            double len1 = Math.Sqrt(Math.Pow((pLB.X - pRT.X), 2) + Math.Pow((pLB.Y - pRT.Y), 2));
            double len2 = Math.Sqrt(Math.Pow(len0, 2) + Math.Pow(len1, 2));
            double lenx = len0 * len0 / len2;
            double leny = len0 * len1 / len2;

            var pathFigure = new PathFigure {
                StartPoint = new System.Windows.Point(pLB.X - lenx, pLB.Y - leny)
            };
            var l1 = new LineSegment {
                Point = new System.Windows.Point(pLB.X + lenx, pLB.Y + leny)
            };
            var l2 = new LineSegment {
                Point = new System.Windows.Point(pRT.X + lenx, pRT.Y + leny)
            };
            var l3 = new LineSegment {
                Point = new System.Windows.Point(pRT.X - lenx, pRT.Y - leny)
            };

            pathFigure.Segments.Add(l1);
            pathFigure.Segments.Add(l2);
            pathFigure.Segments.Add(l3);
            var pathGeometry = new PathGeometry();

            pathGeometry.Figures.Add(pathFigure);
            pathOrbit.Data = pathGeometry;
        }
Exemple #7
0
        public MapView()
        {
            InitializeComponent();

            var ubication = new Point(-3.7025600, 40.4165000);
            var sphericalMercatorCoordinate = SphericalMercator.FromLonLat(ubication.X, ubication.Y);

            var mapControl = new MapsUIView();


            mapControl.NativeMap.NavigateTo(sphericalMercatorCoordinate);
            mapControl.NativeMap.Layers.Add(OpenStreetMap.CreateTileLayer());
            mapControl.NativeMap.NavigateTo(mapControl.NativeMap.Resolutions[9]);



            var layer = GenerateIconLayer();

            mapControl.NativeMap.Layers.Add(layer);
            mapControl.NativeMap.InfoLayers.Add(layer);

            ContentGrid.Children.Add(mapControl);

            mapControl.NativeMap.Info += (sender, args) =>
            {
                var layername    = args.MapInfo?.Layer.Name;
                var featureLabel = args.MapInfo.Feature?["Label"]?.ToString();
                var featureType  = args.MapInfo.Feature?["Type"]?.ToString();

                if (featureType != null && featureType.Equals("Point"))
                {
                    ShowPopup(featureLabel);
                }
            };
        }
        public static UIElement RenderPoint(Point point, IStyle style, IViewport viewport)
        {
            UIElement symbol;
            var matrix = XamlMedia.Matrix.Identity;

            if (style is SymbolStyle)
            {
                var symbolStyle = style as SymbolStyle;

                if (symbolStyle.Symbol == null || symbolStyle.Symbol.Data == null)
                    symbol = CreateSymbolFromVectorStyle(symbolStyle, symbolStyle.Opacity, symbolStyle.SymbolType);
                else
                    symbol = CreateSymbolFromBitmap(symbolStyle.Symbol.Data, symbolStyle.Opacity);
                matrix = CreatePointSymbolMatrix(viewport.Resolution, symbolStyle);
            }
            else
            {
                symbol = CreateSymbolFromVectorStyle((style as VectorStyle) ?? new VectorStyle());
                MatrixHelper.ScaleAt(ref matrix, viewport.Resolution, viewport.Resolution);
            }

            MatrixHelper.Append(ref matrix, CreateTransformMatrix(point, viewport));

            symbol.RenderTransform = new XamlMedia.MatrixTransform { Matrix = matrix };

            symbol.IsHitTestVisible = false;

            return symbol;
        }
Exemple #9
0
        public bool Dragging(Point worldPosition)
        {
            if (EditMode != EditMode.Modify || _dragInfo.Feature == null)
            {
                return(false);
            }

            SetPointXY(_dragInfo.Vertex, worldPosition - _dragInfo.StartOffsetToVertex);

            if (_dragInfo.Feature.Geometry is Polygon polygon) // Not this only works correctly it the feature is in the outerring.
            {
                var count    = polygon.ExteriorRing.Vertices.Count;
                var vertices = polygon.ExteriorRing.Vertices;
                var index    = vertices.IndexOf(_dragInfo.Vertex);
                if (index >= 0)
                {
                    // It is a ring where the first should be the same as the last.
                    // So if the first was removed than set the last to the value of the new first
                    if (index == 0)
                    {
                        SetPointXY(vertices[count - 1], vertices[0]);
                    }
                    // If the last was removed then set the first to the value of the new last
                    else if (index == vertices.Count)
                    {
                        SetPointXY(vertices[0], vertices[count - 1]);
                    }
                }
            }

            _dragInfo.Feature.RenderedGeometry.Clear();
            Layer.DataHasChanged();
            return(true);
        }
Exemple #10
0
        public static double AngleBetween(Point vector1, Point vector2)
        {
            double sin = vector1.X * vector2.Y - vector2.X * vector1.Y;
            double cos = vector1.X * vector2.X + vector1.Y * vector2.Y;

            return(Math.Atan2(sin, cos) * (180 / Math.PI));
        }
Exemple #11
0
        public static XamlShapes.Shape RenderPoint(Point point, IStyle style, IViewport viewport, BrushCache brushCache = null)
        {
            XamlShapes.Shape symbol;
            var matrix = XamlMedia.Matrix.Identity;

            if (style is SymbolStyle)
            {
                var symbolStyle = style as SymbolStyle;

                if (symbolStyle.BitmapId < 0)
                {
                    symbol = CreateSymbolFromVectorStyle(symbolStyle, symbolStyle.Opacity, symbolStyle.SymbolType);
                }
                else
                {
                    symbol = CreateSymbolFromBitmap(symbolStyle.BitmapId, symbolStyle.Opacity, brushCache);
                }
                matrix = CreatePointSymbolMatrix(viewport.Resolution, symbolStyle);
            }
            else
            {
                symbol = CreateSymbolFromVectorStyle((style as VectorStyle) ?? new VectorStyle());
                MatrixHelper.ScaleAt(ref matrix, viewport.Resolution, viewport.Resolution);
            }

            MatrixHelper.Append(ref matrix, CreateTransformMatrix(point, viewport));

            symbol.RenderTransform = new XamlMedia.MatrixTransform {
                Matrix = matrix
            };
            symbol.IsHitTestVisible = false;

            return(symbol);
        }
Exemple #12
0
        public static CATextLayer RenderLabel(Mapsui.Geometries.Point point, LabelStyle style, IFeature feature, IViewport viewport, string text)
        {
            // Offset stackOffset,
            Mapsui.Geometries.Point p = viewport.WorldToScreen(point);
            //var pointF = new xPointF((float)p.X, (float)p.Y);
            var label = new CATextLayer();


            var aString = new MonoTouch.Foundation.NSAttributedString(text,
                                                                      new MonoTouch.CoreText.CTStringAttributes()
            {
                Font = new MonoTouch.CoreText.CTFont("ArialMT", 10)
            });

            var frame = new RectangleF(new System.Drawing.Point((int)p.X, (int)p.Y), GetSizeForText(0, aString));

            //label.Frame = frame;
            //frame.Width = (float)(p2.X - p1.X);// + margin);
            //frame.Height = (float)(p1.Y - p2.Y);

            label.FontSize        = 10;
            label.ForegroundColor = new MonoTouch.CoreGraphics.CGColor(0, 0, 255, 150);
            label.BackgroundColor = new MonoTouch.CoreGraphics.CGColor(255, 0, 2, 150);
            label.String          = text;

            label.Frame = frame;

            Console.WriteLine("Pos " + label.Frame.X + ":" + label.Frame.Y + " w " + label.Frame.Width + " h " + label.Frame.Height);

            // = MonoTouch.UIKit.UIScreen.MainScreen.Scale;
            //	label.ContentsScale = scale;

            return(label);
        }
Exemple #13
0
        /*
         * public static void CenterClusters(IEnumerable<Cluster> clusters, IViewport viewport)
         * {
         *      foreach (var cluster in clusters)
         *      {
         *              var feature = cluster.Features.FirstOrDefault ();
         *              var center = cluster.Box.GetCentroid ();
         *
         *              var styles = feature.Styles ?? Enumerable.Empty<IStyle>();
         *              var style = styles.FirstOrDefault () as SymbolStyle;
         *
         *              var min = viewport.WorldToScreen (cluster.Box.Left, cluster.Box.Bottom);
         *              var max = viewport.WorldToScreen (cluster.Box.Right, cluster.Box.Top);
         *              //style.Width = .Width;
         *              //style.Height = cluster.Box.Height;
         *
         *              var size = (int)Math.Min ((max.X - min.X), (min.Y - max.Y));
         *
         *              //Console.WriteLine ("Size = " + size);
         *              //style.Width = size;
         *              //style.Height = size;
         *
         *              feature.Geometry = center;
         *
         *              //var fCenter = firstFeature.Geometry.GetBoundingBox ().GetCentroid ();
         *              //if(fCenter.X == cluster.Box.GetCentroid().X)
         *      }
         * }
         */

        private static BoundingBox GetFeatureBoundingBox(IFeature feature,
                                                         IViewport viewport)
        {
            var styles      = feature.Styles ?? Enumerable.Empty <IStyle>();
            var symbolStyle = styles.FirstOrDefault() as SymbolStyle;
            var boundingBox = feature.Geometry.GetBoundingBox();
            //var width = style.Width;

            //var frame = GeometryRenderer.ConvertPointBoundingBox (style, feature.Geometry.GetBoundingBox (), viewport);
            var screenMin = viewport.WorldToScreen(boundingBox.Min);
            var screenMax = viewport.WorldToScreen(boundingBox.Max);

            var min = new Mapsui.Geometries.Point(screenMin.X - (symbolStyle.Width / 2), screenMax.Y - (symbolStyle.Height / 2));
            var max = new Mapsui.Geometries.Point((min.X + symbolStyle.Width), (min.Y + symbolStyle.Height));

            var x      = min.X;
            var y      = min.Y;
            var width  = max.X - min.X;
            var height = max.Y - min.Y;

            var frame = new RectangleF((float)x, (float)y, (float)width, (float)height);

            var nmin = viewport.ScreenToWorld(frame.Left, frame.Bottom);
            var nmax = viewport.ScreenToWorld(frame.Right, frame.Top);


            var bb = new BoundingBox(nmin, nmax);


            return(bb);
        }
Exemple #14
0
        public static Canvas RenderStackedLabelLayer(IViewport viewport, LabelLayer layer)
        {
            var canvas = new Canvas();

            canvas.Opacity = layer.Opacity;

            //todo: take into account the priority
            var features = layer.GetFeaturesInView(viewport.Extent, viewport.Resolution);
            var margin   = viewport.Resolution * 50;

            foreach (var layerStyle in layer.Styles)
            {
                var style = layerStyle;

                var clusters = new List <Cluster>();
                //todo: repeat until there are no more merges
                ClusterFeatures(clusters, features, margin, layerStyle, viewport.Resolution);

                foreach (var cluster in clusters)
                {
                    Offset stackOffset = null;

                    foreach (var feature in cluster.Features.OrderBy(f => f.Geometry.GetBoundingBox().GetCentroid().Y))
                    {
                        if (layerStyle is IThemeStyle)
                        {
                            style = (layerStyle as IThemeStyle).GetStyle(feature);
                        }
                        if ((style == null) || (style.Enabled == false) || (style.MinVisible > viewport.Resolution) || (style.MaxVisible < viewport.Resolution))
                        {
                            continue;
                        }

                        if (stackOffset == null) //first time
                        {
                            stackOffset = new Offset();
                            if (cluster.Features.Count > 1)
                            {
                                canvas.Children.Add(RenderBox(cluster.Box, viewport));
                            }
                        }
                        else
                        {
                            stackOffset.Y += 18;  //todo: get size from text, (or just pass stack nr)
                        }
                        if (!(style is LabelStyle))
                        {
                            throw new Exception("Style of label is not a LabelStyle");
                        }
                        var    labelStyle = style as LabelStyle;
                        string labelText  = layer.GetLabel(feature);
                        var    position   = new Mapsui.Geometries.Point(cluster.Box.GetCentroid().X, cluster.Box.Bottom);
                        canvas.Children.Add(RenderLabel(position, stackOffset, labelStyle, viewport, labelText));
                    }
                }
            }

            return(canvas);
        }
Exemple #15
0
        private static RectangleF WorldToView(Extent extent, IViewport viewport)
        {
            Point min = viewport.WorldToScreen(new Point(extent.MinX, extent.MinY));
            Point max = viewport.WorldToScreen(new Point(extent.MaxX, extent.MaxY));

            return(new RectangleF((float)min.X, (float)max.Y,
                                  (float)(max.X - min.X), (float)(min.Y - max.Y)));
        }
Exemple #16
0
        public async Task <List <Marker> > GetAllMarkers()
        {
            Debug.WriteLine("MarkerService.GetAllMarkers() called.");

            List <MarkerDto> markerDtos = null;
            var json = string.Empty;

            try
            {
                json = await _client.GetStringAsync($"/?q=mobileapi/markersjson.json");

                Debug.WriteLine("Loaded marker json:");
                Debug.WriteLine(json);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Error fetching markersjson: " + e.ToString());
                // TODO: Show error to user.
            }
            try
            {
                markerDtos = JsonConvert.DeserializeObject <List <MarkerDto> >(json);
            }
            catch (JsonReaderException e)
            {
                Debug.WriteLine("Error parsing markersjson: " + e.ToString());
            }
            List <Marker> markersList = new List <Marker>();
            int           tempNodeId  = 1;

            foreach (MarkerDto markerDto in markerDtos)
            {
                string label = _htmlHelper.ExtractText(markerDto.title);

                try
                {
                    double lat       = Double.Parse(markerDto.Coordinates[0]);
                    double longitude = Double.Parse(markerDto.Coordinates[1]);
                    // Format (Long, Lat)
                    // Zoom to marker location
                    var currentMarker = new Mapsui.Geometries.Point(longitude, lat);
                    // OSM uses spherical mercator coordinates. So transform the lon lat coordinates to spherical mercator
                    Point  sphericalMercatorCoordinate = SphericalMercator.FromLonLat(currentMarker.X, currentMarker.Y);
                    string description = "Marker is located in city of " + _htmlHelper.ExtractText(markerDto.City)
                                         + " and county: " + _htmlHelper.ExtractText(markerDto.County);
                    var marker = new Marker(label, tempNodeId.ToString(), sphericalMercatorCoordinate, description);
                    marker.Latitude  = lat;
                    marker.Longitude = longitude;
                    markersList.Add(marker);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Ignoring marker with bad or missing GPS location data! GPS coordinates are in invalid format for this marker: " + label + " exception: " + e.ToString());
                }
            }

            return(markersList);
        }
Exemple #17
0
        public PrimerMapa()
        {
            InitializeComponent();

            var mapControl = new Mapsui.UI.Forms.MapControl();

            mapControl.Map.Layers.Add(OpenStreetMap.CreateTileLayer());

            mapControl.Map.Widgets.Add(new ScaleBarWidget(mapControl.Map)
            {
                TextAlignment       = Alignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment   = VerticalAlignment.Top
            });

            mapControl.Map.Widgets.Add(new ZoomInOutWidget()
            {
                MarginX = 20,
                MarginY = 40
            });

            var gdl = lugares.First(x => x.Nombre == "Guadalajara");

            var coordenada         = new Point(gdl.Longitud, gdl.Latitud);
            var coordenadaMercator = SphericalMercator.FromLonLat(coordenada.X, coordenada.Y);

            mapControl.Map.Home = n => n.NavigateTo(coordenadaMercator, mapControl.Map.Resolutions[9]);

            var layer = GenerateIconLayer();

            layer.IsMapInfoLayer = true;
            mapControl.Map.Layers.Add(layer);

            mapControl.Info += (sender, args) =>
            {
                var layername    = args.MapInfo.Layer?.Name;
                var featureLabel = args.MapInfo.Feature?["Label"]?.ToString();
                var featureType  = args.MapInfo.Feature?["Type"]?.ToString();

                if (!string.IsNullOrWhiteSpace(featureLabel))
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        ShowPopup(featureLabel, featureType);
                    });
                }

                Debug.WriteLine("Info Event was invoked.");
                Debug.WriteLine("Layername: " + layername);
                Debug.WriteLine("Feature Label: " + featureLabel);
                Debug.WriteLine("Feature Type: " + featureType);

                Debug.WriteLine("World Position: {0:F4} , {1:F4}", args.MapInfo.WorldPosition?.X, args.MapInfo.WorldPosition?.Y);
                Debug.WriteLine("Screen Position: {0:F4} , {1:F4}", args.MapInfo.ScreenPosition?.X, args.MapInfo.ScreenPosition?.Y);
            };

            ContentGrid.Children.Add(mapControl);
        }
Exemple #18
0
 private void OnPreviewMouseMove(object sender, MouseEventArgs e)
 {
     if (draggingFeature != null)
     {
         Point mousePoint = ScreenPointToGlobal(e.GetPosition(mapControl).ToMapsui());
         draggingFeature.Geometry = editedObject.Position = mousePoint - draggingOffset;
         Refresh();
     }
 }
Exemple #19
0
        private IEnumerable <IFeature> GetFeaturesAtScreenPoint(Point point)
        {
            var    worldPoint      = ScreenPointToGlobal(point);
            double extentReduction = DraggingLayer.Scale / 3.5f;
            double resolution      = mapControl.Viewport.Resolution * extentReduction;
            var    features        = draggingLayer.GetFeaturesInView(new BoundingBox(worldPoint, worldPoint), resolution);

            return(features);
        }
        internal static IEnumerable <Point> WorldToScreen(LineString linearRing, IViewport viewport)
        {
            var v = new Point[linearRing.Vertices.Count];

            for (int i = 0; i < linearRing.Vertices.Count; i++)
            {
                v[i] = viewport.WorldToScreen(linearRing.Vertices[i]);
            }
            return(v);
        }
Exemple #21
0
 public static MemoryLayer CreateWalkerLayer(Mapsui.Geometries.Point currentNodePosition)
 {
     return(new MemoryLayer
     {
         Name = "Walker",
         IsMapInfoLayer = true,
         DataSource = new MemoryProvider(CreateFeature(currentNodePosition)),
         Style = CreateBitmapStyle()
     });
 }
Exemple #22
0
    private static IEnumerable <IFeature> CreateFeature(Mapsui.Geometries.Point currentNodePosition)
    {
        List <Feature> res     = new List <Feature>();
        Feature        feature = new Feature();

        feature.Geometry = currentNodePosition;
        feature["name"]  = "Current walker position";
        res.Add(feature);
        return(res);
    }
        private IEnumerable <IMapObject> GetFeaturesAt(Point point)
        {
            var boundingBox = new BoundingBox(point, point);

            return(mapObjectLayer.GetFeaturesInView(boundingBox, mapControl.Viewport.Resolution)
                   .Concat(boundingAreaLayer.GetFeaturesInView(boundingBox, mapControl.Viewport.Resolution))
                   .Concat(attractorLayer.GetFeaturesInView(boundingBox, mapControl.Viewport.Resolution))
                   .OfType <IMapObject>()
                   .Where(p => p.IsMouseOver(point, mapControl)));
        }
Exemple #24
0
        public static Mapsui.Map CreateMap()
        {
            var map = new Mapsui.Map();

            map.Layers.Add(OpenStreetMap.CreateTileLayer());
            var b = CreateMbTilesLayer(mbpath);

            if (b != null)
            {
                map.Layers.Add(b);
            }
            var c = CreateMbTilesLayer(mbpath2);

            if (c != null)
            {
                map.Layers.Add(c);
            }

            // Get the lon lat coordinates from somewhere (Mapsui can not help you there)
            var centerOfLondonOntario = new Point(-81.2497, 42.9837);
            // OSM uses spherical mercator coordinates. So transform the lon lat coordinates to spherical mercator
            var sphericalMercatorCoordinate = SphericalMercator.FromLonLat(centerOfLondonOntario.X, centerOfLondonOntario.Y);

            // Set the center of the viewport to the coordinate. The UI will refresh automatically
            // Additionally you might want to set the resolution, this could depend on your specific purpose

            map.Layers.Add(CreatePointLayer());
            map.Layers.Add(CreateLayer());
            map.Layers.Add(CreateLineStringLayer());
            map.Layers.Add(new RasterizingLayer(CreateRandomPointLayer()));//, pixelDensity: pixelDensity));
            //map.Layers.Add(CreateMbTilesLayer());

            //mapView.Map.Layers.Add(CreateLineStringLayer());

            //mapView.Map.Viewport.Center = new Mapsui.Geometries.Point(-46.4, -23.2);
            //mapView.Rotation = false;
            // mapView.UnSnapRotationDegrees = 30;
            //mapView.ReSnapRotationDegrees = 5;

            //mapView.ev += OnPinClicked;
            //mapView.MapClicked += OnMapClicked;

            //mapView.la.UpdateMyLocation(new UI.Forms.Position());

            // mapView.Info += MapView_Info;

            //var abc = Task.Run(() => StartGPS());

            //setup(mapView);

            //Clicker = c;
            map.Home = n => n.NavigateTo(sphericalMercatorCoordinate, map.Resolutions[9]);

            return(map);
        }
Exemple #25
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            double[] GPS_Values = TCP.GPS_Information();
            var      point      = new Mapsui.Geometries.Point(GPS_Values[1], GPS_Values[0]);
            var      sphericalMercatorCoordinate = SphericalMercator.FromLonLat(point.X, point.Y);

            MyMapControl.Map.NavigateTo(sphericalMercatorCoordinate);
            MyMapControl.Map.NavigateTo(MyMapControl.Map.Resolutions[18]);
            MyMapControl.Map.Layers.Add(OpenStreetMap.CreateTileLayer());
            MyMapControl.Map.Layers.Add(Auxiliary.CreatePointLayer(sphericalMercatorCoordinate));
        }
Exemple #26
0
        public static void DrawPoint(Graphics graphics, Point point, Styles.IStyle style, IViewport viewport)
        {
            var vectorStyle = (Styles.SymbolStyle)style;

            if (vectorStyle.Symbol == null)
            {
                throw  new ArgumentException("No bitmap symbol set in Gdi rendering");                             //todo: allow vector symbol
            }
            Bitmap symbol      = vectorStyle.Symbol.Convert();
            var    symbolscale = vectorStyle.SymbolScale;
            PointF offset      = vectorStyle.SymbolOffset.Convert();
            var    rotation    = vectorStyle.SymbolRotation;

            if (point == null)
            {
                return;
            }
            if (symbol == null)
            {
                symbol = DefaultSymbol;
            }

            PointF dest = ConvertPoint(viewport.WorldToScreen(point));

            if (rotation != 0 && !double.IsNaN(rotation))
            {
                graphics.TranslateTransform(dest.X, dest.Y);
                graphics.RotateTransform((float)rotation);
                graphics.TranslateTransform((int)(-symbol.Width / 2.0), (int)(-symbol.Height / 2.0));
                if (symbolscale == 1f)
                {
                    graphics.DrawImageUnscaled(symbol, (int)(dest.X - symbol.Width / 2.0 + offset.X), (int)(dest.Y - symbol.Height / 2.0 + offset.Y));
                }
                else
                {
                    var width  = symbol.Width * symbolscale;
                    var height = symbol.Height * symbolscale;
                    graphics.DrawImage(symbol, (int)(dest.X - width / 2 + offset.X * symbolscale), (int)(dest.Y - height / 2 + offset.Y * symbolscale), (float)width, (float)height);
                }
            }
            else
            {
                if (symbolscale == 1f)
                {
                    graphics.DrawImageUnscaled(symbol, (int)(dest.X - symbol.Width / 2.0 + offset.X), (int)(dest.Y - symbol.Height / 2.0 + offset.Y));
                }
                else
                {
                    var width  = symbol.Width * symbolscale;
                    var height = symbol.Height * symbolscale;
                    graphics.DrawImage(symbol, (int)(dest.X - width / 2 + offset.X * symbolscale), (int)(dest.Y - height / 2 + offset.Y * symbolscale), (float)width, (float)height);
                }
            }
        }
Exemple #27
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //MyMapControl.ZoomOut();
            var centerOfCC = new Mapsui.Geometries.Point(-6.3714, 39.4768);
            var center     = GetCoordenates();
            // OSM uses spherical mercator coordinates. So transform the lon lat coordinates to spherical mercator
            var sphericalMercatorCoordinate = SphericalMercator.FromLonLat(center.X, center.Y);

            MyMapControl.Map.NavigateTo(sphericalMercatorCoordinate);


            MyMapControl.Map.NavigateTo(MyMapControl.Map.Resolutions[15]);
        }
Exemple #28
0
        private static Label CreateLabel(IGeometry feature, string text, float rotation, int priority, LabelStyle style, IViewport viewport,
                                         Graphics g, LabelLayer labelTheme)
        {
            SizeF gdiSize = g.MeasureString(text, style.Font.Convert());
            var   size    = new Mapsui.Styles.Size {
                Width = gdiSize.Width, Height = gdiSize.Height
            };

            Mapsui.Geometries.Point position = viewport.WorldToScreen(feature.GetBoundingBox().GetCentroid());
            position.X = position.X - size.Width * (short)style.HorizontalAlignment * 0.5f;
            position.Y = position.Y - size.Height * (short)style.VerticalAlignment * 0.5f;
            if (position.X - size.Width > viewport.Width || position.X + size.Width < 0 ||
                position.Y - size.Height > viewport.Height || position.Y + size.Height < 0)
            {
                return(null);
            }
            else
            {
                Label lbl;

                if (!style.CollisionDetection)
                {
                    lbl = new Label(text, position, rotation, priority, null, style);
                }
                else
                {
                    //Collision detection is enabled so we need to measure the size of the string
                    lbl = new Label(text, position, rotation, priority,
                                    new LabelBox(position.X - size.Width * 0.5f - style.CollisionBuffer.Width,
                                                 position.Y + size.Height * 0.5f + style.CollisionBuffer.Height,
                                                 size.Width + 2f * style.CollisionBuffer.Width,
                                                 size.Height + style.CollisionBuffer.Height * 2f), style);
                }
                if (feature.GetType() == typeof(LineString))
                {
                    var line = feature as LineString;
                    if (line.Length / viewport.Resolution > size.Width) //Only label feature if it is long enough
                    {
                        CalculateLabelOnLinestring(line, ref lbl, viewport);
                    }
                    else
                    {
                        return(null);
                    }
                }

                return(lbl);
            }
        }
Exemple #29
0
        private static XamlMedia.Matrix CreateTransformMatrix(Point point, IViewport viewport)
        {
            var matrix = XamlMedia.Matrix.Identity;

            MatrixHelper.Translate(ref matrix, point.X, point.Y);
            var mapCenterX = viewport.Width * 0.5;
            var mapCenterY = viewport.Height * 0.5;

            MatrixHelper.Translate(ref matrix, mapCenterX - viewport.CenterX, mapCenterY - viewport.CenterY);
            MatrixHelper.ScaleAt(ref matrix, 1 / viewport.Resolution, 1 / viewport.Resolution, mapCenterX, mapCenterY);

            // This will invert the Y axis, but will also put images upside down
            MatrixHelper.InvertY(ref matrix, mapCenterY);
            return(matrix);
        }
        /// <summary>
        /// Save the temporary geometry
        /// </summary>
        private void SaveNewGeom()
        {
            MessagingCenter.Subscribe <MapPage, string>(this, "GeometryName", (sender, arg) =>
            {
                var geomName = arg as string;
                ReferenceGeometry.SaveGeometry(TempCoordinates, geomName);
                RemoveTempGeometry();
                RefreshShapes();
                MessagingCenter.Unsubscribe <MapPage, string>(this, "GeometryName");
            });
            Mapsui.Geometries.Point point = TempCoordinates[0];
            var coords      = point.ToDoubleArray();
            var coordString = coords[1].ToString("#.000#") + ", " + coords[0].ToString("#.000#");

            MessagingCenter.Send <MapPageVM, string>(this, "RequestGeometryName", coordString);
        }
Exemple #31
0
        private static XamlMedia.Geometry ConvertSymbol(Point point, SymbolStyle style, IViewport viewport)
        {
            Point p = viewport.WorldToScreen(point);

            var rect = new XamlMedia.RectangleGeometry();

            if (style.BitmapId >= 0)
            {
                var bitmapImage = BitmapRegistry.Instance.Get(style.BitmapId).CreateBitmapImage();
                var width       = bitmapImage.PixelWidth * style.SymbolScale;
                var height      = bitmapImage.PixelHeight * style.SymbolScale;
                rect.Rect = new Rect(p.X - width * 0.5, p.Y - height * 0.5, width, height);
            }

            return(rect);
        }
Exemple #32
0
        private void userControl_MouseMove(object sender, MouseEventArgs e)
        {
            Mapsui.Geometries.Point p       = this.MapControl.Map.Viewport.ScreenToWorld(e.GetPosition(MapControl).X, e.GetPosition(MapControl).Y);
            Mapsui.Geometries.Point pLonLat = new Mapsui.Geometries.Point(0, 0);
            pLonLat.X = Mapsui.Projection.SphericalMercator.ToLonLat(p.X, p.Y).X;
            pLonLat.Y = Mapsui.Projection.SphericalMercator.ToLonLat(p.X, p.Y).Y;

            this.pLon.Content = pLonLat.X.ToString();
            this.pLat.Content = pLonLat.Y.ToString();

            setMaker();
            //Mapsui.Geometries.Point pWldPosi = Mapsui.Projection.SphericalMercator.FromLonLat(pLonLat.X, pLonLat.Y);
            //Mapsui.Geometries.Point pWinPosi = MapControl.Map.Viewport.WorldToScreen(pWldPosi);
            ////iconMaker.Margin = new Thickness(pWinPosi.X - 20, pWinPosi.Y - 40, 0, 0);
            //setMaker(pWinPosi);
        }
Exemple #33
0
        public static void PositionPoint(UIElement renderedGeometry, Point point, IStyle style, IViewport viewport)
        {
            var matrix = XamlMedia.Matrix.Identity;

            if (style is SymbolStyle)
            {
                matrix = CreatePointSymbolMatrix(viewport.Resolution, style as SymbolStyle);
            }
            else
            {
                MatrixHelper.ScaleAt(ref matrix, viewport.Resolution, viewport.Resolution);
            }
            MatrixHelper.Append(ref matrix, CreateTransformMatrix(point, viewport));
            renderedGeometry.RenderTransform = new XamlMedia.MatrixTransform {
                Matrix = matrix
            };
        }
        public static Canvas RenderStackedLabelLayer(IViewport viewport, LabelLayer layer)
        {
            var canvas = new Canvas();
            canvas.Opacity = layer.Opacity;

            //todo: take into account the priority 
            var features = layer.GetFeaturesInView(viewport.Extent, viewport.Resolution);
            var margin = viewport.Resolution * 50;

            foreach (var layerStyle in layer.Styles)
            {
                var style = layerStyle;

                var clusters = new List<Cluster>();
                //todo: repeat until there are no more merges
                ClusterFeatures(clusters, features, margin, layerStyle, viewport.Resolution);

                foreach (var cluster in clusters)
                {
                    Offset stackOffset = null;
                    
                    foreach (var feature in cluster.Features.OrderBy(f => f.Geometry.GetBoundingBox().GetCentroid().Y))
                    {
                        if (layerStyle is IThemeStyle) style = (layerStyle as IThemeStyle).GetStyle(feature);
                        if ((style == null) || (style.Enabled == false) || (style.MinVisible > viewport.Resolution) || (style.MaxVisible < viewport.Resolution)) continue;

                        if (stackOffset == null) //first time
                        {
                            stackOffset = new Offset();
                            if (cluster.Features.Count > 1)
                                canvas.Children.Add(RenderBox(cluster.Box, viewport));
                        }
                        else stackOffset.Y += 18; //todo: get size from text, (or just pass stack nr)
                                                
                        if (!(style is LabelStyle)) throw new Exception("Style of label is not a LabelStyle");
                        var labelStyle = style as LabelStyle;
                        string labelText = layer.GetLabel(feature);
                        var position = new Mapsui.Geometries.Point(cluster.Box.GetCentroid().X, cluster.Box.Bottom);
                        canvas.Children.Add(RenderLabel(position, stackOffset, labelStyle, viewport, labelText));
                    }
                }
            }

            return canvas;
        }
        public static XamlMedia.Matrix CreateTransformMatrix(Point point, IViewport viewport)
        {
            var matrix = XamlMedia.Matrix.Identity;
            var mapCenterX = viewport.Width * 0.5;
            var mapCenterY = viewport.Height * 0.5;

            var pointOffsetFromViewPortCenterX = point.X - viewport.Center.X;
            var pointOffsetFromViewPortCenterY = point.Y - viewport.Center.Y;

            MatrixHelper.Translate(ref matrix, pointOffsetFromViewPortCenterX, pointOffsetFromViewPortCenterY);

            if (viewport.IsRotated)
            {
                MatrixHelper.Rotate(ref matrix, -viewport.Rotation);
            }

            MatrixHelper.Translate(ref matrix, mapCenterX, mapCenterY);
            MatrixHelper.ScaleAt(ref matrix, 1 / viewport.Resolution, 1 / viewport.Resolution, mapCenterX, mapCenterY);

            // This will invert the Y axis, but will also put images upside down
            MatrixHelper.InvertY(ref matrix, mapCenterY);
            return matrix;
        }
Exemple #36
0
 public void InsertPoint(int index, Point point)
 {
     _currentProjection.SetToMap(point);
     _points.Insert(index, point);
 }
 public static void PositionPoint(CALayer symbol, CGPoint point, IStyle style, IViewport viewport)
 {
     var frame = ConvertPointBoundingBox(style as SymbolStyle, point.GetBoundingBox(), viewport);
     symbol.Frame = frame;
 }
Exemple #38
0
 public void AddPoint(Point point)
 {
     _currentProjection.SetToMap(point);
     _points.Add(point);
 }
        private static XamlMedia.Matrix CreateTransformMatrix(Point point, IViewport viewport)
        {
            var matrix = XamlMedia.Matrix.Identity;
            MatrixHelper.Translate(ref matrix, point.X, point.Y);
            var mapCenterX = viewport.Width * 0.5;
            var mapCenterY = viewport.Height * 0.5;

            MatrixHelper.Translate(ref matrix, mapCenterX - viewport.CenterX, mapCenterY - viewport.CenterY);
            MatrixHelper.ScaleAt(ref matrix, 1 / viewport.Resolution, 1 / viewport.Resolution, mapCenterX, mapCenterY);

            // This will invert the Y axis, but will also put images upside down
            MatrixHelper.InvertY(ref matrix, mapCenterY);
            return matrix;
        }
        private static XamlMedia.Geometry ConvertSymbol(Point point, SymbolStyle style, IViewport viewport)
        {
            Point p = viewport.WorldToScreen(point);

            var rect = new XamlMedia.RectangleGeometry();
            if (style.Symbol != null)
            {
                var bitmapImage = CreateBitmapImage(style.Symbol.Data);
                var width = bitmapImage.PixelWidth * style.SymbolScale;
                var height = bitmapImage.PixelHeight * style.SymbolScale;
                rect.Rect = new Rect(p.X - width * 0.5, p.Y - height * 0.5, width, height);
            }

            return rect;
        }
 public static void PositionPoint(UIElement renderedGeometry, Point point, IStyle style, IViewport viewport)
 {
     var matrix = XamlMedia.Matrix.Identity;
     if (style is SymbolStyle) matrix = CreatePointSymbolMatrix(viewport.Resolution, style as SymbolStyle);
     else MatrixHelper.ScaleAt(ref matrix, viewport.Resolution, viewport.Resolution);
     MatrixHelper.Append(ref matrix, CreateTransformMatrix(point, viewport));
     renderedGeometry.RenderTransform = new XamlMedia.MatrixTransform { Matrix = matrix };
 }
 public static Point WorldToView(Point point, IViewport viewport)
 {
     return viewport.WorldToScreen(point);
 }
 internal static Point WorldToScreen(Point point, IViewport viewport)
 {
     return viewport.WorldToScreen(point);
 }
        /// <summary>
        /// Renders a label to the map.
        /// </summary>
        /// <param name="graphics">Graphics reference</param>
        /// <param name="labelPoint">Label placement</param>
        /// <param name="offset">Offset of label in screen coordinates</param>
        /// <param name="font">Font used for rendering</param>
        /// <param name="forecolor">Font forecolor</param>
        /// <param name="backcolor">Background color</param>
        /// <param name="halo">Color of halo</param>
        /// <param name="rotation">Text rotation in degrees</param>
        /// <param name="text">Text to render</param>
        /// <param name="viewport"></param>
        public static void DrawLabel(Graphics graphics, Point labelPoint, Styles.Offset offset, Styles.Font font, Styles.Color forecolor, Styles.Brush backcolor, Styles.Pen halo, double rotation, string text, IViewport viewport)
        {
            SizeF fontSize = graphics.MeasureString(text, font.Convert()); //Calculate the size of the text
            labelPoint.X += offset.X; labelPoint.Y += offset.Y; //add label offset
            if (rotation != 0 && !double.IsNaN(rotation))
            {
                graphics.TranslateTransform((float)labelPoint.X, (float)labelPoint.Y);
                graphics.RotateTransform((float)rotation);
                graphics.TranslateTransform(-fontSize.Width / 2, -fontSize.Height / 2);
                if (backcolor != null && backcolor.Convert() != Brushes.Transparent)
                    graphics.FillRectangle(backcolor.Convert(), 0, 0, fontSize.Width * 0.74f + 1f, fontSize.Height * 0.74f);
                var path = new GraphicsPath();
                path.AddString(text, new FontFamily(font.FontFamily), (int)font.Convert().Style, font.Convert().Size, new System.Drawing.Point(0, 0), null);
                if (halo != null)
                    graphics.DrawPath(halo.Convert(), path);
                graphics.FillPath(new SolidBrush(forecolor.Convert()), path);
                //g.DrawString(text, font, new System.Drawing.SolidBrush(forecolor), 0, 0);                
            }
            else
            {
                if (backcolor != null && backcolor.Convert() != Brushes.Transparent)
                    graphics.FillRectangle(backcolor.Convert(), (float)labelPoint.X, (float)labelPoint.Y, fontSize.Width * 0.74f + 1, fontSize.Height * 0.74f);

                var path = new GraphicsPath();

                //Arial hack
                path.AddString(text, new FontFamily("Arial"), (int)font.Convert().Style, (float)font.Size, new System.Drawing.Point((int)labelPoint.X, (int)labelPoint.Y), null);
                if (halo != null)
                    graphics.DrawPath(halo.Convert(), path);
                graphics.FillPath(new SolidBrush(forecolor.Convert()), path);
                //g.DrawString(text, font, new System.Drawing.SolidBrush(forecolor), LabelPoint.X, LabelPoint.Y);
            }
        }
Exemple #45
0
		/*
		public static void CenterClusters(IEnumerable<Cluster> clusters, IViewport viewport)
		{
			foreach (var cluster in clusters)
			{
				var feature = cluster.Features.FirstOrDefault ();
				var center = cluster.Box.GetCentroid ();

				var styles = feature.Styles ?? Enumerable.Empty<IStyle>();
				var style = styles.FirstOrDefault () as SymbolStyle;

				var min = viewport.WorldToScreen (cluster.Box.Left, cluster.Box.Bottom);
				var max = viewport.WorldToScreen (cluster.Box.Right, cluster.Box.Top);
				//style.Width = .Width;
				//style.Height = cluster.Box.Height;

				var size = (int)Math.Min ((max.X - min.X), (min.Y - max.Y));

				//Console.WriteLine ("Size = " + size);
				//style.Width = size;
				//style.Height = size;

				feature.Geometry = center;

				//var fCenter = firstFeature.Geometry.GetBoundingBox ().GetCentroid ();
				//if(fCenter.X == cluster.Box.GetCentroid().X)
			}
		}
		*/

		private static BoundingBox GetFeatureBoundingBox(IFeature feature, 
		                                   IViewport viewport)
		{
			var styles = feature.Styles ?? Enumerable.Empty<IStyle>();
			var symbolStyle = styles.FirstOrDefault () as SymbolStyle;
			var boundingBox = feature.Geometry.GetBoundingBox ();
			//var width = style.Width;

			//var frame = GeometryRenderer.ConvertPointBoundingBox (style, feature.Geometry.GetBoundingBox (), viewport); 
			var screenMin = viewport.WorldToScreen(boundingBox.Min);
			var screenMax = viewport.WorldToScreen(boundingBox.Max);

			var min = new Mapsui.Geometries.Point(screenMin.X - (symbolStyle.Width / 2), screenMax.Y - (symbolStyle.Height / 2));
			var max = new Mapsui.Geometries.Point((min.X + symbolStyle.Width), (min.Y + symbolStyle.Height));
	
			var x = min.X;
			var y = min.Y;
			var width = max.X - min.X;
			var height = max.Y - min.Y;

			var frame = new RectangleF((float)x, (float)y, (float)width, (float)height);

			var nmin = viewport.ScreenToWorld (frame.Left, frame.Bottom);
			var nmax = viewport.ScreenToWorld (frame.Right, frame.Top);


			var bb = new BoundingBox (nmin, nmax);


			return bb;
		}
        public static void DrawPoint(Graphics graphics, Point point, Styles.IStyle style, IViewport viewport)
        {
            var vectorStyle = (Styles.SymbolStyle)style;
            if (vectorStyle.Symbol == null) throw  new ArgumentException("No bitmap symbol set in Gdi rendering"); //todo: allow vector symbol
            Bitmap symbol= vectorStyle.Symbol.Convert();
            var symbolscale = vectorStyle.SymbolScale;
            PointF offset = vectorStyle.SymbolOffset.Convert();
            var rotation = vectorStyle.SymbolRotation;

            if (point == null)
                return;
            if (symbol == null)
                symbol = DefaultSymbol;

            PointF dest = ConvertPoint(viewport.WorldToScreen(point));

            if (rotation != 0 && !double.IsNaN(rotation))
            {
                graphics.TranslateTransform(dest.X, dest.Y);
                graphics.RotateTransform((float)rotation);
                graphics.TranslateTransform((int)(-symbol.Width / 2.0), (int)(-symbol.Height / 2.0));
                if (symbolscale == 1f)
                    graphics.DrawImageUnscaled(symbol, (int)(dest.X - symbol.Width / 2.0 + offset.X), (int)(dest.Y - symbol.Height / 2.0 + offset.Y));
                else
                {
                    var width = symbol.Width * symbolscale;
                    var height = symbol.Height * symbolscale;
                    graphics.DrawImage(symbol, (int)(dest.X - width / 2 + offset.X * symbolscale), (int)(dest.Y - height / 2 + offset.Y * symbolscale), (float)width, (float)height);
                }
            }
            else
            {
                if (symbolscale == 1f)
                    graphics.DrawImageUnscaled(symbol, (int)(dest.X - symbol.Width / 2.0 + offset.X), (int)(dest.Y - symbol.Height / 2.0 + offset.Y));
                else
                {
                    var width = symbol.Width * symbolscale;
                    var height = symbol.Height * symbolscale;
                    graphics.DrawImage(symbol, (int)(dest.X - width / 2 + offset.X * symbolscale), (int)(dest.Y - height / 2 + offset.Y * symbolscale), (float)width, (float)height);
                }
            }
        }
 public static PointF ConvertPoint(Point point)
 {
     return new PointF((float)point.X, (float)point.Y);
 }