示例#1
0
        /// <summary>
        /// Shows how to render circles with a geographic radius of 250km
        /// Note: you'll have to take the latitude into account!
        /// </summary>
        /// <param name="layer"></param>
        public void AddCircles(ShapeLayer layer)
        {
            for (int lon = -180; lon <= +180; lon = lon + 10)
            {
                for (int lat = -80; lat <= +80; lat = lat + 10)
                {
                    double radius      = 250000;                                // radius in meters
                    double cosB        = Math.Cos(lat / 360.0 * (2 * Math.PI)); // factor depends on latitude
                    double ellipseSize = Math.Abs(1.0 / cosB * radius) * 2;     // size mercator units

                    var ellipse = new Ellipse
                    {
                        Width           = ellipseSize,
                        Height          = ellipseSize,
                        Fill            = new SolidColorBrush(Color.FromArgb(128, 0, 0, 255)),
                        Stroke          = new SolidColorBrush(Colors.Black),
                        StrokeThickness = 25000
                    };

                    ShapeCanvas.SetScaleFactor(ellipse, 1); // scale linear
                    ShapeCanvas.SetLocation(ellipse, new Point(lon, lat));
                    layer.Shapes.Add(ellipse);

                    // bonus: show how to add a popup that the location (a the ellipse center)
                    ellipse.Tag         = new Point(lon, lat);
                    ellipse.MouseEnter += Ellipse_MouseEnter;
                    ellipse.MouseLeave += Ellipse_MouseLeave;
                }
            }
        }
        private void SetScenario(Scenario newScenario)
        {
            scenario = newScenario;

            #region doc:ConfigureLayers

            tourLayer.Shapes.Clear();
            orderLayer.Shapes.Clear();
            depotLayer.Shapes.Clear();

            foreach (var order in scenario.Orders)
            {
                var pin = new Cube {
                    Color = unplannedColor
                };
                pin.Width = pin.Height = Math.Sqrt(order.Quantity) * 10;
                ShapeCanvas.SetLocation(pin, new Point(order.Longitude, order.Latitude));
                orderLayer.Shapes.Add(pin);
                pin.Tag = order;
            }

            foreach (var depot in scenario.Depots)
            {
                var pyramid = new Pyramid();
                pyramid.Width = pyramid.Height = 30;
                pyramid.Color = depot.Color;
                ShapeCanvas.SetLocation(pyramid, new Point(depot.Longitude, depot.Latitude));
                depotLayer.Shapes.Add(pyramid);
            }

            #endregion // doc:ConfigureLayers
        }
示例#3
0
        /// <summary> Builds up the layer content. Shows a pin for each geocoded address on the map. </summary>
        protected void UdpatePins()
        {
            #region doc:display pins for addresses
            ContentLayer.Shapes.Clear();

            if (Addresses == null || Addresses.Count == 0)
            {
                return;
            }

            // Add a pin to the map for each result.
            foreach (ResultAddress address in Addresses)
            {
                var pin = new Pin
                {
                    Color  = PinColor,
                    Height = 40,
                    Width  = 40
                };
                ToolTipService.SetToolTip(pin, $"{address.postCode} {address.city} {address.city2} {address.street} {address.houseNumber}");
                ShapeCanvas.SetAnchor(pin, LocationAnchor.RightBottom);
                ShapeCanvas.SetLocation(pin, new System.Windows.Point(address.coordinates.point.x, address.coordinates.point.y));
                ContentLayer.Shapes.Add(pin);
            }

            ContentLayer.Refresh();
            #endregion
        }
        /// <summary> Adds a pin to the map for each way point of the example route. </summary>
        private void SetWayPointPins(Scenario scenario)

        {
            for (var i = 0; i < scenario.wayPoints.Length; ++i)
            {
                var pin = new Pin
                {
                    // Sets the color of the pin to green if it's the start waypoint. Otherwise red.
                    Color  = (i == 0) ? Colors.Green : Colors.Red,
                    Width  = 40,
                    Height = 40,
                    // Sets the name of the pin to Start it it's the start waypoint. Otherwise to End.
                    Name = (i == 0) ? "Start" : "End",
                };

                // Sets Anchor and Location of the pin.
                ShapeCanvas.SetAnchor(pin, LocationAnchor.RightBottom);
                ShapeCanvas.SetLocation(pin, new System.Windows.Point(scenario.wayPoints[i].x, scenario.wayPoints[i].y));

                // Sets tooltip of the pin to Start if it is the start waypoint. Otherwise to End.
                ToolTipService.SetToolTip(pin, pin.Name);

                // Adds the pin to the layer.
                shapeLayer.Shapes.Add(pin);
            }
        }
        public void ShowDimaInDynMap(dynamic idList, dynamic locationsList, dynamic violatedLocationsList)
        {
            var dimaPointsLayer = new List <System.Windows.Point>();

            reachablePointsLayer = new ShapeLayer("Reachable")
            {
                SpatialReferenceId = "EPSG:4326"
            };
            int i = 0;

            foreach (var reachWaypoint in locationsList)
            {
                i++;
                System.Windows.Point reachableDimaPoint;
                var markerBlue = new Ptv.XServer.Controls.Map.Symbols.Ball
                {
                    Color = System.Windows.Media.Colors.Blue
                };
                reachableDimaPoint = new System.Windows.Point(reachWaypoint.coordinate.x, reachWaypoint.coordinate.y);
                ShapeCanvas.SetLocation(markerBlue, reachableDimaPoint);
                markerBlue.Width   = markerBlue.Height = 20;
                markerBlue.ToolTip = i + " - " + idList[i - 1];

                reachablePointsLayer.Shapes.Add(markerBlue);
                reachablePointsLayer.Refresh();
                dimaPointsLayer.Add(reachableDimaPoint);
            }

            violatedPointsLayer = new ShapeLayer("Violated")
            {
                SpatialReferenceId = "EPSG:4326"
            };
            int j = 0;

            foreach (var reachWaypoint in violatedLocationsList)
            {
                j++;
                System.Windows.Point reachableDimaPoint;
                var markerBlue = new Ptv.XServer.Controls.Map.Symbols.Ball
                {
                    Color = System.Windows.Media.Colors.Red
                };
                reachableDimaPoint = new System.Windows.Point(reachWaypoint.coordinate.x, reachWaypoint.coordinate.y);
                ShapeCanvas.SetLocation(markerBlue, reachableDimaPoint);
                markerBlue.Width = markerBlue.Height = 13;
                //markerBlue.ToolTip = i + " - " + idList[i - 1];

                reachablePointsLayer.Shapes.Add(markerBlue);
                reachablePointsLayer.Refresh();
                dimaPointsLayer.Add(reachableDimaPoint);
            }

            dynMap.Layers.Add(reachablePointsLayer);
            dynMap.Layers.Add(violatedPointsLayer);
            reachablePointsLayer.Refresh();
            violatedPointsLayer.Refresh();
            dynMap.SetEnvelope(new Ptv.XServer.Controls.Map.MapRectangle(dimaPointsLayer).Inflate(1.1, 1.1), "EPSG:4326");
            dynMap.Focus();
        }
示例#6
0
        public void SetScenario(Scenario usedScenario)
        {
            scenario         = usedScenario;
            scenario.Profile = ProfileComboBox.Text;

            statusLabel.Content        = "Scenario initialized";
            StartButton.IsEnabled      = true;
            ScenarioComboBox.IsEnabled = true;

            tourLayer.Shapes.Clear();
            orderLayer.Shapes.Clear();
            depotLayer.Shapes.Clear();

            // add orders, oder by latitude so they overlap nicely on the map
            foreach (var order in from o in usedScenario.Orders orderby o.Latitude descending select o)
            {
                var cube = new Cube
                {
                    Color   = unplannedColor,
                    Width   = Math.Sqrt(order.Quantity) * 10,
                    Height  = Math.Sqrt(order.Quantity) * 10,
                    ToolTip = order.Description
                };

                ShapeCanvas.SetLocation(cube, new Point(order.Longitude, order.Latitude));
                orderLayer.Shapes.Add(cube);
                cube.Tag = order;
            }

            // add depots, oder by latitude so they overlap nicely on the map
            foreach (var depot in from d in usedScenario.Depots orderby d.Latitude descending select d)
            {
                var pin = new Pyramid {
                    Width   = 30,
                    Height  = 30,
                    Color   = depot.Color,
                    ToolTip = depot.Description
                };
                ShapeCanvas.SetLocation(pin, new Point(depot.Longitude, depot.Latitude));
                depotLayer.Shapes.Add(pin);
            }

            if (!firstTime)
            {
                return;
            }
            firstTime = false;
            MessageBox.Show(this,
                            "This sample shows some best practices for PTV xTour in a " +
                            ".NET Windows client application. The main techniques demonstrated in this sample:\n" +
                            "* Using xTour at xServer internet\n" +
                            "* Visualizing the tour plan with the xServer .NET control\n" +
                            "* Mapping your application objects from and to xServer objects\n" +
                            "* Invoking PTV xServers from a windows application in a non-blocking way\n" +
                            "* Using the job API to control and display the tour calculation progress",
                            "What's this?");
        }
        public async void Initialize()
        {
            // initialize base map (for xServer internet)
            formsMap1.XMapUrl         = "https://xmap-eu-n-test.cloud.ptvgroup.com/xmap/ws/XMap";
            formsMap1.XMapCredentials = token;

            // add a new Shape Layer
            var layer = new ShapeLayer("MyShapes");

            formsMap1.Layers.Add(layer);

            var startPoint = new Point(7.10052, 50.73117);
            var destPoint  = new Point(9.99337, 53.54897);

            // set map view
            formsMap1.SetEnvelope(new MapRectangle(new[] { startPoint, destPoint }).Inflate(1.25));

            // create start marker
            var startMarker = new Truck
            {
                Color   = Colors.Blue,
                Width   = 50,
                ToolTip = "Start"
            };

            // set position and add to map
            ShapeCanvas.SetLocation(startMarker, startPoint);
            ShapeCanvas.SetZIndex(startMarker, 10);
            layer.Shapes.Add(startMarker);

            // create destination marker
            var destMarker = new Pyramid
            {
                Color   = Colors.Green,
                Width   = 50,
                Height  = 50,
                ToolTip = "Destination",
            };

            // set position and add to map
            ShapeCanvas.SetLocation(destMarker, destPoint);
            ShapeCanvas.SetZIndex(destMarker, 10);
            layer.Shapes.Add(destMarker);

            // calculate route, non-blocking
            var route = await Task.Run(() => CalcRoute(startPoint.Y, startPoint.X, destPoint.Y, destPoint.X));

            // display route
            SetRoute(route, layer, Colors.Blue, "Route");
        }
        /// <summary>
        /// Besides the individual customized symbols, which can be any objects of type FrameworkElement,
        /// additionally labels are added into the shape layer.
        /// </summary>
        /// <param name="frameworkElement">New shape element to insert into the shape layer.</param>
        /// <param name="animation">Optionally an animation can be specified applied to the new shape.</param>
        private void AddToLayer(FrameworkElement frameworkElement, Timeline animation = null)
        {
            #region doc:add to layer

            // Because of a different positioning of labels for objects of type MapPolylineBase compared
            // to other object types, two different implementations are available
            if (frameworkElement is MapPolylineBase)
            {
                shapeLayer.Shapes.Add(frameworkElement);
                // Create a label at the position specified in the Location property of the MapPolyline object.
                var border = CreateLabel("Hello");
                ShapeCanvas.SetLocation(border, ShapeCanvas.GetLocation(frameworkElement));
                shapeLayer.Shapes.Add(border);
            }
            else
            {
                // Arrange symbol and text label in a stack panel
                var stackPanel = new StackPanel();

                stackPanel.Children.Add(frameworkElement);
                stackPanel.Children.Add(CreateLabel("Hello"));

                // The following properties of the new object are transferred to the StackPanel for
                // correct behavior.
                ShapeCanvas.SetLocation(stackPanel, ShapeCanvas.GetLocation(frameworkElement));
                ShapeCanvas.SetAnchor(stackPanel, ShapeCanvas.GetAnchor(frameworkElement));
                ShapeCanvas.SetScale(stackPanel, ShapeCanvas.GetScale(frameworkElement));
                ShapeCanvas.SetScaleFactor(stackPanel, ShapeCanvas.GetScaleFactor(frameworkElement));

                shapeLayer.Shapes.Add(stackPanel);

                // Add the option animation
                if (animation == null)
                {
                    return;
                }

                // Set the animation to target the Center property of the stack panel object
                Storyboard.SetTarget(animation, stackPanel);
                Storyboard.SetTargetProperty(animation, new PropertyPath(ShapeCanvas.LocationProperty));

                // Create a storyboard to apply the animation.
                var sb = new Storyboard();
                sb.Children.Add(animation);
                sb.Begin();
            }
            #endregion //doc:add to layer
        }
示例#9
0
        public void AddSymbols()
        {
            var layer = Map.Layers["Symbols"];

            if (layer != null)
            {
                Map.Layers.Remove(layer);
            }

            var symbolLayer = new ShapeLayer("Symbols")
            {
                LazyUpdate = useSymLazyUpdate
            };

            Map.Layers.Add(symbolLayer);

            for (int i = 0; i < coordinates.Count; i++)
            {
                const int symbolSize = 25;
                var       color      = i % 3 == 0 ? Colors.Blue : i % 3 == 1 ? Colors.Green : Colors.Red;

                FrameworkElement symbol;
                if (useSymBitmapCaching)
                {
                    var bitmap = GetCachedBitmap(color, symbolSize);
                    symbol = new Image {
                        Source = bitmap
                    };
                }
                else
                {
                    symbol = new Pyramid {
                        Color = color
                    };
                    symbol.Width = symbol.Height = symbolSize;
                }

                // log-scaling parameters
                ShapeCanvas.SetScale(symbol, 10);
                ShapeCanvas.SetScaleFactor(symbol, 0.4);

                ShapeCanvas.SetLocation(symbol, coordinates[i]);
                symbol.ToolTip = "Hello";
                symbolLayer.Shapes.Add(symbol);
            }
        }
示例#10
0
        /// <summary>
        /// Creates the way point
        /// </summary>
        /// <param name="layer">Assigned route layer</param>
        /// <param name="p">Position of the way point (world coordinates)</param>
        /// <param name="style">Style of the way point</param>
        protected WayPoint(RouteLayer layer, Point p, ShapeStyle style)
        {
            this.layer = layer;

            Width = Height = style.Size;

            // set initial position and show polyline
            // do not use Point property to avoid LocationChanged event in initialization
            ShapeCanvas.SetLocation(this, p);

            // drag and drop handlers
            InProcessDragDropBehavior.AddDragHandler(this, Drag);
            InProcessDragDropBehavior.AddDragMoveHandler(this, DragMove);
            InProcessDragDropBehavior.SetEnableDragDrop(this, true);

            // handler for context menu
            MouseRightButtonDown += WayPoint_MouseRightButtonDown;
        }
        /// <inheritdoc/>
        public bool AddMarker(int id, double x, double y, int size, string color, string Symbol, string toolTip)
        {
            if (idMap.ContainsKey(id))
            {
                return(false);
            }

            // create shape
            var frameworkElement = CreateSymbol(size, color);

            // set location
            ShapeCanvas.SetLocation(frameworkElement, new Point(x, y));

            // add shape
            InsertShape(frameworkElement, id, toolTip);

            return(true);
        }
示例#12
0
        private static void AddCircle(ShapeLayer layer, Point center, double radius)
        {
            // calculate the size in mercator units
            var cosB        = Math.Cos(center.Y * Math.PI / 180.0); // factor depends on latitude
            var ellipseSize = Math.Abs(1.0 / cosB * radius) * 2;    // size mercator units

            var ellipse = new Ellipse
            {
                Width           = ellipseSize,
                Height          = ellipseSize,
                Fill            = new SolidColorBrush(Color.FromArgb(128, 0, 0, 255)),
                Stroke          = new SolidColorBrush(Colors.LightBlue),
                StrokeThickness = 25
            };

            ShapeCanvas.SetScaleFactor(ellipse, 1); // scale linear
            ShapeCanvas.SetLocation(ellipse, center);
            layer.Shapes.Add(ellipse);
        }
        /// <summary>
        /// The arrow demo is uses an adaption of Charles Petzold's WPF arrow class
        /// http://charlespetzold.com/blog/2007/04/191200.html to be used as custom MapShape
        /// </summary>
        /// <param name="layer"></param>
        public void AddPinWithLabel(ShapeLayer layer)
        {
            const int radius = 1;                  // radius in degrees of latitude
            var       center = new Point(8.4, 49); // Karlsruhe

            var rand = new Random();
            Func <Point, double, Point> randomCoordinate = (c, r) =>
            {
                var angle    = rand.NextDouble() * 2 * Math.PI;
                var distance = r * Math.Sqrt(rand.NextDouble());

                return(new Point
                {
                    X = c.X + distance * Math.Cos(angle),
                    Y = c.Y + distance * Math.Sin(angle)
                });
            };

            var pin = new Pyramid();

            pin.Width = pin.Height = 10;

            pin.Measure(new Size(pin.Width, pin.Height));
            pin.Arrange(new Rect(0, 0, pin.Width, pin.Height));

            var bitmap = new RenderTargetBitmap((int)pin.Width, (int)pin.Height, 96, 96, PixelFormats.Pbgra32);

            bitmap.Render(pin);
            bitmap.Freeze();
            for (int i = 0; i < 5000; i++)
            {
                FrameworkElement symbol = new Image {
                    Source = bitmap
                };
                symbol.Width = pin.Height = 10;
                ShapeCanvas.SetLocation(symbol, randomCoordinate(center, radius));
                symbol.ToolTip = "Hello";
                layer.Shapes.Add(symbol);
            }

            Map.SetMapLocation(center, 9);
        }
示例#14
0
        private void button2_Click(object sender, EventArgs e)
        {
            // create a random geo-coordinate
            var rand = new Random();
            var lat  = rand.NextDouble() + 48.5;
            var lon  = rand.NextDouble() + 8;

            // create  a truck marker
            var marker = new Truck
            {
                Color   = Color.FromRgb((byte)(rand.NextDouble() * 256), (byte)(rand.NextDouble() * 256), (byte)(rand.NextDouble() * 256)),
                Width   = 20 + rand.NextDouble() * 20,
                ToolTip = "Hello Map"
            };

            // set position and add to map
            ShapeCanvas.SetLocation(marker, new Point(lon, lat));
            layer.Shapes.Add(marker);

            // set the location as center
            formsMap1.SetMapLocation(new Point(lon, lat), 10);
        }
示例#15
0
        /// <summary>
        /// Load local image files and add it to the map
        /// See also http://www.i-programmer.info/programming/wpf-workings/520-bitmapimage-and-local-files-.html
        /// </summary>
        /// <param name="layer"></param>
        public void AddShapes(ShapeLayer layer)
        {
            // add ptv logo
            var ptvLogo = new Image();
            var src     = new BitmapImage();

            src.BeginInit();
            src.CacheOption = BitmapCacheOption.OnLoad;
            src.UriSource   = new Uri("Icons\\Logo_PTV_Screen-mini.tif", UriKind.Relative);
            src.EndInit();
            ptvLogo.Source = src;
            ShapeCanvas.SetLocation(ptvLogo, new Point(8.428253, 49.013432));
            ptvLogo.Name = "PTV";

            // optional: set explicit size and scale factor
            ptvLogo.Height = 100;
            ShapeCanvas.SetScaleFactor(ptvLogo, .1);

            layer.Shapes.Add(ptvLogo);

            // add cas logo
            var casLogo = new Image();

            src = new BitmapImage();
            src.BeginInit();
            src.CacheOption = BitmapCacheOption.OnLoad;
            src.UriSource   = new Uri("Icons\\logoCAS-Software-AG-DE.gif", UriKind.Relative);
            src.EndInit();
            casLogo.Source = src;
            casLogo.Name   = "CAS";
            ShapeCanvas.SetLocation(casLogo, new Point(8.439220, 49.021664));

            // optional: set explicit size and scale factor
            casLogo.Height = 100;
            ShapeCanvas.SetScaleFactor(casLogo, .1);

            layer.Shapes.Add(casLogo);
        }
        public void AddBalloon(MultiCanvasShapeLayer layer, double lat, double lon, Color color, string text,
                               string tooltip)
        {
            // create and initialize balloon
            var balloon = new Balloon
            {
                Color   = color,
                Text    = text,
                ToolTip = tooltip
            };

            // set geo location
            ShapeCanvas.SetLocation(balloon, new System.Windows.Point(lon, lat));

            // optional use adaptive (zoom-dependent scaling)
            ShapeCanvas.SetScale(balloon, 2.5);
            ShapeCanvas.SetScaleFactor(balloon, 0.1);

            // don't need a z_index, use TopShapes instead.
            // Canvas.SetZIndex(balloon, 1);

            // add to map
            layer.TopShapes.Add(balloon);
        }
示例#17
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // go to Karlsruhe castle
            var myLocation = new Point(8.4044, 49.01405);

            Map.SetMapLocation(myLocation, 14);

            // add OSM tiles
            Map.Layers.Add(new TiledLayer("OSM_DE")
            {
                Caption        = "OpenStreetMap.DE",
                IsBaseMapLayer = true,
                TiledProvider  = new RemoteTiledProvider
                {
                    MinZoom = 0,
                    MaxZoom = 18,
                    RequestBuilderDelegate = (x, y, level) =>
                                             $"https://{"abc"[(x ^ y) % 3]}.tile.openstreetmap.de/tiles/osmde/{level}/{x}/{y}.png",
                },
                Copyright = $"Map © OpenStreetMap contributors",
                Icon      = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Background.png")
            });

            // add basic xServer tiles
            // Map.Layers.Add(new TiledLayer("xserver")
            // {
            //     Caption = "PTV xServer",
            //     IsBaseMapLayer = true,
            //     TiledProvider = new RemoteTiledProvider
            //     {
            //         MinZoom = 0,
            //         MaxZoom = 22,
            //         RequestBuilderDelegate = (x, y, level) =>

            //         $"https://s0{"1234"[(x ^ y) % 4]}-xserver2-test.cloud.ptvgroup.com/services/rest/XMap/tile/" +
            //         $"{level}/{x}/{y}?storedProfile=silkysand&xtok=<your-xserver-internet-token>"
            //     },
            //     Copyright = $"© PTV, HERE",
            //     Icon = ResourceHelper.LoadBitmapFromResource("Ptv.XServer.Controls.Map;component/Resources/Background.png")
            // });

            // add stuff
            var myLayer = new ShapeLayer("MyLayer")
            {
                LocalOffset = myLocation // this new property eliminates jitter at deep zoom levels
            };

            Map.Layers.Add(myLayer);

            // add push-pin
            Control pin = new Pin
            {
                Width   = 50, // regarding scale fatoring
                Height  = 50,
                ToolTip = "I am a pin!",
                Color   = Colors.Red
            };

            ShapeCanvas.SetLocation(pin, myLocation);
            ShapeCanvas.SetAnchor(pin, LocationAnchor.RightBottom);
            ShapeCanvas.SetScaleFactor(pin, 0.1);
            Panel.SetZIndex(pin, 100);
            myLayer.Shapes.Add(pin);

            // add geographic circle
            double radius      = 435;                                            // radius in meters
            double cosB        = Math.Cos(myLocation.Y / 360.0 * (2 * Math.PI)); // factor depends on latitude
            double ellipseSize = Math.Abs(1.0 / cosB * radius) * 2;              // size mercator units

            var ellipse = new Ellipse
            {
                Width           = ellipseSize,
                Height          = ellipseSize,
                Fill            = new SolidColorBrush(Color.FromArgb(128, 0, 0, 255)),
                Stroke          = new SolidColorBrush(Colors.Black),
                StrokeThickness = radius / 20,
                ToolTip         = "I am a circle!"
            };

            ShapeCanvas.SetScaleFactor(ellipse, 1); // scale linear
            ShapeCanvas.SetLocation(ellipse, myLocation);
            myLayer.Shapes.Add(ellipse);
        }
        /// <summary> Adds elements to the map. </summary>
        private void AddElements()
        {
            #region doc:the location around which the shapes are created
            // the location in Gauss-Kruger coordinates
            var location = new Point(3565913, 5935734);
            #endregion

            #region doc:create ShapeLayer
            // create a shape layer
            shapeLayer = new ShapeLayer("DifferentShapes")
            {
                SpatialReferenceId = "EPSG:31467", // set SR to Gaus s-Kruger zone 3 (default is WGS84)
                LocalOffset        = location      // the localOffset can be used to reduce jitter at deep zoom levels
            };

            shapeLayer2 = new ShapeLayer("PieCharts")
            {
                LocalOffset = new Point(10, 53) // to reduce jitter
            };
            #endregion                          //doc:create ShapeLayer

            #region doc:add layer to map
            // add layers to map
            wpfMap.Layers.Add(shapeLayer);
            wpfMap.Layers.InsertBefore(shapeLayer2, "DifferentShapes");
            #endregion //doc:add layer to map

            #region doc:animate shape
            // create a WPF element
            var triangleUp = new TriangleUp {
                Color = Colors.Blue, Stroke = Colors.Red,
                HorizontalAlignment = HorizontalAlignment.Left,
                ToolTip             = "TriangleUp", Width = 32, Height = 32
            };

            // set geo location of the element
            triangleUp.SetValue(ShapeCanvas.LocationProperty, location);

            // add some click interaction
            triangleUp.MouseDoubleClick += (o, e) => MessageBox.Show("Hello!");

            var myPointAnimation = new PointAnimation
            {
                Duration       = TimeSpan.FromSeconds(2),
                AutoReverse    = true,
                RepeatBehavior = RepeatBehavior.Forever,
                From           = location,
                To             = new Point(location.X + 960, location.Y + 960)
            };

            // add to layer
            AddToLayer(triangleUp, myPointAnimation);


            #endregion //doc:animate shape

            #region doc:add MapPolygon
            var poly = new MapPolygon
            {
                Points = new PointCollection(new[]
                {
                    (Point)(location - new Point(-100, -100)), (Point)(location - new Point(100, -100)),
                    (Point)(location - new Point(100, 100)), (Point)(location - new Point(-100, 100))
                }),
                Fill               = new SolidColorBrush(Colors.Red),
                Opacity            = .5,
                MapStrokeThickness = 5,
                Stroke             = new SolidColorBrush(Colors.Black)
            };
            Panel.SetZIndex(poly, -1);
            AddToLayer(poly);
            #endregion //doc:add MapPolygon

            #region doc:handle MapPolygon events
            poly.MouseEnter += (o, e) => poly.Fill = new SolidColorBrush(Colors.Green);
            poly.MouseLeave += (o, e) => poly.Fill = new SolidColorBrush(Colors.Red);
            #endregion //doc:handle MapPolygon events

            #region doc:create shapes
            // Create elements
            var triangleDown = CreateElement(Symbols.TriangleDown, Colors.Black, Colors.Red) as TriangleDown;
            var star         = CreateElement(Symbols.Star, Colors.Yellow, Colors.Green) as Star;
            var pentagon     = CreateElement(Symbols.Pentagon, Colors.Red, Colors.Blue) as Pentagon;
            var hexagon      = CreateElement(Symbols.Hexagon, Colors.Orange, Colors.Navy) as Hexagon;
            var diamond      = CreateElement(Symbols.Diamond, Colors.DeepPink, Colors.Navy) as Diamond;
            var pyramid      = CreateElement(Symbols.Pyramid, Colors.Yellow, Colors.Black) as Pyramid;
            var ball         = CreateElement(Symbols.Ball, Colors.Yellow, Colors.Green) as Ball;
            ball.Width = ball.Height = 100; // Varying the default size
            var pin  = CreateElement(Symbols.Pin, Colors.Green, Colors.Black) as Pin;
            var cube = CreateElement(Symbols.Cube, Colors.Blue, Colors.Red) as Cube;
            cube.Width = cube.Height = 15; // Varying the default size
            var truck = CreateElement(Symbols.Truck, Colors.Red, Colors.Black) as Truck;
            #endregion                     //doc:create shapes

            #region doc:set position
            // set position
            triangleDown.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 320, location.Y));
            Panel.SetZIndex(triangleDown, -1);
            star.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 640, location.Y));
            Panel.SetZIndex(star, -1);
            pentagon.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 960, location.Y));
            Panel.SetZIndex(pentagon, -1);
            hexagon.SetValue(ShapeCanvas.LocationProperty, new Point(location.X, location.Y + 320));
            Panel.SetZIndex(hexagon, -1);
            diamond.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 320, location.Y + 320));
            Panel.SetZIndex(diamond, -1);
            pyramid.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 640, location.Y + 320));
            Panel.SetZIndex(pyramid, -1);
            ball.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 960, location.Y + 320));
            Panel.SetZIndex(ball, -1);
            pin.SetValue(ShapeCanvas.LocationProperty, new Point(location.X, location.Y + 640));
            ShapeCanvas.SetAnchor(pin, LocationAnchor.RightBottom);
            Panel.SetZIndex(pin, -1);
            cube.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 320, location.Y + 640));
            Panel.SetZIndex(cube, -1);
            truck.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 960, location.Y + 640));
            Panel.SetZIndex(truck, -1);
            #endregion //doc:set position

            AddToLayer(triangleDown);
            AddToLayer(star);
            AddToLayer(pentagon);
            AddToLayer(hexagon);
            AddToLayer(diamond);
            AddToLayer(pyramid);
            AddToLayer(ball);
            AddToLayer(pin);
            AddToLayer(cube);
            AddToLayer(truck);


            #region doc:sample anchor
            var pinRightBottom = CreateElement(Symbols.Pin, Colors.Green, Colors.Black) as Pin;
            if (pinRightBottom != null)
            {
                pinRightBottom.SetValue(ShapeCanvas.LocationProperty, new Point(location.X - 320, location.Y));
                pinRightBottom.ToolTip = "Pin with anchor right bottom";
                ShapeCanvas.SetAnchor(pinRightBottom, LocationAnchor.RightBottom);
                Panel.SetZIndex(pinRightBottom, -1);
                AddToLayer(pinRightBottom);
            }

            var ballRightBottom = CreateElement(Symbols.Ball, Colors.Red, Colors.Black) as Ball;
            if (ballRightBottom != null)
            {
                ballRightBottom.Width   = 10;
                ballRightBottom.Height  = 10;
                ballRightBottom.ToolTip = "Ball with same coordinates like pin";
                ballRightBottom.SetValue(ShapeCanvas.LocationProperty, new Point(location.X - 320, location.Y));
                Panel.SetZIndex(ballRightBottom, -1);
                AddToLayer(ballRightBottom);
            }

            var pinCenter = CreateElement(Symbols.Pin, Colors.Green, Colors.Black) as Pin;
            if (pinCenter != null)
            {
                pinCenter.SetValue(ShapeCanvas.LocationProperty, new Point(location.X - 320, location.Y + 150));
                pinCenter.ToolTip = "Pin with default anchor";
                Panel.SetZIndex(pinCenter, -1);
                AddToLayer(pinCenter);
            }

            var ballCenter = CreateElement(Symbols.Ball, Colors.Red, Colors.Black) as Ball;
            if (ballCenter != null)
            {
                ballCenter.Width   = 10;
                ballCenter.Height  = 10;
                ballCenter.ToolTip = "Ball with same coordinates like pin";
                ballCenter.SetValue(ShapeCanvas.LocationProperty, new Point(location.X - 320, location.Y + 150));
                Panel.SetZIndex(ballCenter, -1);
                AddToLayer(ballCenter);
            }

            #endregion // doc:sample anchor


            #region doc:sample ScaleProperty
            var starStandard = CreateElement(Symbols.Star, Colors.Green, Colors.Black) as Star;
            if (starStandard != null)
            {
                starStandard.SetValue(ShapeCanvas.LocationProperty, new Point(location.X - 100, location.Y + 960));
                starStandard.Width   = starStandard.Height = 40;
                starStandard.ToolTip = "Star with size 40 and scale 1 (standard display)";
                starStandard.SetValue(ShapeCanvas.ScaleProperty, 1.0);
                Panel.SetZIndex(starStandard, -1);
                AddToLayer(starStandard);
            }

            var starBig = CreateElement(Symbols.Star, Colors.Green, Colors.Black) as Star;
            if (starBig != null)
            {
                starBig.SetValue(ShapeCanvas.LocationProperty, new Point(location.X, location.Y + 960));
                starBig.Width   = starBig.Height = 40;
                starBig.ToolTip = "Star with size 40 and scale 3 (object bigger and border thicker)";
                starBig.SetValue(ShapeCanvas.ScaleProperty, 3.0);
                Panel.SetZIndex(starBig, -1);
                AddToLayer(starBig);
            }

            #endregion // doc:sample ScaleProperty


            #region doc:sample ScaleFactor
            var starConstant = CreateElement(Symbols.Star, Colors.Red, Colors.Black) as Star;
            if (starConstant != null)
            {
                starConstant.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 320, location.Y + 960));
                starConstant.Width   = starConstant.Height = 80;
                starConstant.ToolTip = "Star with size 80 and scale factor 0 (constant object size, standard display)";
                ShapeCanvas.SetScaleFactor(starConstant, 0);
                Panel.SetZIndex(starConstant, -1);
                AddToLayer(starConstant);
            }

            var starHalfEnlarged = CreateElement(Symbols.Star, Colors.Yellow, Colors.Black) as Star;
            if (starHalfEnlarged != null)
            {
                starHalfEnlarged.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 370, location.Y + 960));
                starHalfEnlarged.Width   = starHalfEnlarged.Height = 80;
                starHalfEnlarged.ToolTip =
                    "Star with size 80 and scale factor 0.5 (object is half enlarged if the map zooms)";
                ShapeCanvas.SetScaleFactor(starHalfEnlarged, 0.5);
                Panel.SetZIndex(starHalfEnlarged, -1);
                AddToLayer(starHalfEnlarged);
            }

            var starEnlarged = CreateElement(Symbols.Star, Colors.Green, Colors.Black) as Star;
            if (starEnlarged != null)
            {
                starEnlarged.SetValue(ShapeCanvas.LocationProperty, new Point(location.X + 420, location.Y + 960));
                starEnlarged.Width   = starEnlarged.Height = 80;
                starEnlarged.ToolTip = "Star with size 80 and scale factor 1 (object is enlarged if the map zooms)";
                ShapeCanvas.SetScaleFactor(starEnlarged, 1);
                Panel.SetZIndex(starEnlarged, -1);
                AddToLayer(starEnlarged);
            }

            #endregion // doc:sample ScaleFactor

            // our demo data
            var stores = new List <Store> {
                new Store
                {
                    Name      = "HH-South",
                    Latitude  = 53.55,
                    Longitude = 10.02,
                    Sales     = new List <Sale> {
                        new Sale {
                            Type = "Food", Amount = 30
                        },
                        new Sale {
                            Type = "Non Food", Amount = 70
                        }
                    }
                },
                new Store
                {
                    Name      = "HH-North",
                    Latitude  = 53.56,
                    Longitude = 10.02,
                    Sales     = new List <Sale> {
                        new Sale {
                            Type = "Food", Amount = 40
                        },
                        new Sale {
                            Type = "Non Food", Amount = 50
                        },
                        new Sale {
                            Type = "Pet Food", Amount = 10
                        }
                    }
                }
            };

            foreach (var store in stores)
            {
                // initialize a pie chart for each element
                var chartView = new Chart();
                chartView.BeginInit();

                chartView.Width      = 300;
                chartView.Height     = 250;
                chartView.Background = new SolidColorBrush(Color.FromArgb(192, 255, 255, 255));

                var pieSeries = new PieSeries();
                chartView.Title = store.Name;
                pieSeries.IndependentValuePath = "Type";
                pieSeries.DependentValuePath   = "Amount";
                pieSeries.ItemsSource          = store.Sales;
                pieSeries.IsSelectionEnabled   = true;
                chartView.Series.Add(pieSeries);

                chartView.EndInit();

                // Add to map
                ShapeCanvas.SetLocation(chartView, new Point(store.Longitude, store.Latitude));
                ShapeCanvas.SetAnchor(chartView, LocationAnchor.Center);
                ShapeCanvas.SetScaleFactor(chartView, .1); // adopt the element to the scale factor
                shapeLayer2.Shapes.Add(chartView);
            }

            #region doc:center map to location
            // center map to location
            wpfMap.SetMapLocation(new Point(location.X + 1000, location.Y + 650), 14.7, "EPSG:31467");
            #endregion //doc:center map to location
        }
        /*/public void CalcDima(RootObject daveRequestJson)
         * {
         *  List<xDimaWSService.RouteLocation> dimaWayPointList = new List<xDimaWSService.RouteLocation>();
         *  xDimaWSService.RouteLocation[] dipw = null;
         *
         *  var violatedLocationsList = new List<xDimaWSService.OnRoadRouteLocation>();
         *  violatedIdList = new List<string>();
         *  idList = new List<string>();
         *
         *  var drr = new xDimaWSService.CreateAndGetDistanceMatrixRequest
         *  {
         *      coordinateFormat = "EPSG:4326",
         *      storedProfile = cbxStoredProfile.Text
         *  };
         *
         *  var dimaTaTheme = new xDimaWSService.Theme
         *  {
         *      id = "PTV_TruckAttributes",
         *      enabledSpecified = true
         *  };
         *
         *  dimaTaTheme.enabled = false;
         *
         *  if (cbxFLTruckAttributes.Checked == true)
         *  {
         *      dimaTaTheme.enabled = true;
         *  }
         *
         *  drr.requestProfile = new xDimaWSService.RequestProfile()
         *  {
         *      featureLayerProfile = new xDimaWSService.FeatureLayerProfile()
         *      {
         *          themes = new xDimaWSService.Theme[]
         *          {
         *              dimaTaTheme
         *          },
         *      },
         *  };
         *
         *  if (daveRequestJson.stops.Count >= 2)
         *  {
         *      foreach (var stop in daveRequestJson.stops)
         *      {
         *          var wpt = new xDimaWSService.OnRoadRouteLocation()
         *          {
         *              coordinate = new xDimaWSService.Coordinate()
         *              {
         *                  x = stop.coordinate.locationX,
         *                  y = stop.coordinate.locationY
         *              }
         *          };
         *          dimaWayPointList.Add(wpt);
         *      }
         *  }
         *  else
         *  {
         *      MessageBox.Show("Not enough waypoints!");
         *      return;
         *  }
         *
         *  foreach (var scemId in daveRequestJson.stops)
         *  {
         *      idList.Add(scemId.scemid.ToString());
         *  }
         *
         *  dipw = dimaWayPointList.ToArray();
         *  drr.startLocations = dipw;
         *  var locationsList = dipw.OfType<xDimaWSService.OnRoadRouteLocation>().ToList();
         *  drr.resultFields = new xDimaWSService.DistanceMatrixContentsResultFields()
         *  {
         *      distances = true,
         *      distancesSpecified = true,
         *      violated = true,
         *      violatedSpecified = true,
         *      estimatedByDirectDistance = true,
         *      estimatedByDirectDistanceSpecified = true
         *  };
         *
         *  try
         *  {
         *      dimaResponse = xDimaClient.createDistanceMatrix(drr);
         *  }
         *  catch (System.Web.Services.Protocols.SoapException soapException)
         *  {
         *      System.Windows.Forms.MessageBox.Show(soapException.Detail.InnerXml.Replace(">", ">\r\n"));
         *      return;
         *  }
         *  catch (System.ServiceModel.FaultException faultException)
         *  {
         *      System.Windows.Forms.MessageBox.Show("Error when trying to calculate the dima" + "\r\n" + faultException.Message);
         *      return;
         *  }
         *  catch (Exception ex)
         *  {
         *      MessageBox.Show(ex.Message);
         *      return;
         *  }
         *
         *  waypointCount = dimaResponse.summary.numberOfStartLocations;
         *  distanceMatrixResponseContents = dimaResponse.contents as xDimaWSService.DistanceMatrixContentsArrays;
         *
         *  for (int i = 0; i < dimaResponse.summary.numberOfStartLocations; i++)
         *  {
         *      var numberOfViolations = 0;
         *      for (int j = 0; j < dimaResponse.summary.numberOfStartLocations; j++)
         *      {
         *          if (distanceMatrixResponseContents.violated[i * dimaResponse.summary.numberOfStartLocations + j])
         *          {
         *              numberOfViolations++;
         *          }
         *      }
         *      if (numberOfViolations >= waypointCount - 1)
         *      {
         *          violatedLocationsList.Add(locationsList[i]);
         *      }
         *  }
         *
         *  ShowDimaInDynMap(idList, locationsList, violatedLocationsList);
         *  waypointCount = 0;
         * }
         * /*/

        public void ShowRouteInDynMap()
        {
            var mapCoordFormat = "";

            if (cbxCoordFormat.Text == "EPSG:76131")
            {
                routingLayer = new ShapeLayer("Route")
                {
                    SpatialReferenceId = "PTV_MERCATOR"
                };
                mapCoordFormat = "PTV_MERCATOR";
            }
            else if (cbxCoordFormat.Text == "EPSG:4326")
            {
                routingLayer = new ShapeLayer("Route")
                {
                    SpatialReferenceId = "EPSG:4326"
                };
                mapCoordFormat = "EPSG:4326";
            }
            else if (cbxCoordFormat.Text == "EPSG:3857")
            {
                routingLayer = new ShapeLayer("Route")
                {
                    SpatialReferenceId = "EPSG:3857"
                };
                mapCoordFormat = "EPSG:3857";
            }

            if (routeResponse.polyline != null)
            {
                var routePoly = routeResponse.polyline.plain as xRouteWSService.Polyline;

                var points = new PointCollection();

                foreach (xRouteWSService.Coordinate p in routePoly.polyline)
                {
                    points.Add(new System.Windows.Point(p.x, p.y));
                }

                MapPolyline mapPolyLine = new MapPolyline()
                {
                    Points             = points,
                    Stroke             = new SolidColorBrush(Colors.Blue),
                    MapStrokeThickness = 10,
                    Opacity            = 1.0,
                    ScaleFactor        = 0.2
                };

                (routingLayer as ShapeLayer).Shapes.Add(mapPolyLine);
                mapPolyLine.ToolTip = string.Format("{0:0,0.0}km\n{1}", Math.Round(routeResponse.distance / 1000.0, 2), TimeSpan.FromSeconds(routeResponse.travelTime));
            }
            else
            {
                MessageBox.Show("Error while calculating route");
                return;
            }

            var markerStart = new Ptv.XServer.Controls.Map.Symbols.Ball
            {
                Color = Colors.Green
            };
            var markerVia = new Ptv.XServer.Controls.Map.Symbols.Ball
            {
                Color = Colors.Yellow
            };
            var markerDest = new Ptv.XServer.Controls.Map.Symbols.Ball
            {
                Color = Colors.Red
            };

            mapCoordStart = new System.Windows.Point(double.Parse(tbxStartX.Text.Replace(".", ",")), double.Parse(tbxStartY.Text.Replace(".", ",")));
            mapCoordDest  = new System.Windows.Point(double.Parse(tbxDestX.Text.Replace(".", ",")), double.Parse(tbxDestY.Text.Replace(".", ",")));
            ShapeCanvas.SetLocation(markerStart, mapCoordStart);
            ShapeCanvas.SetLocation(markerDest, mapCoordDest);
            markerStart.Width   = markerStart.Height = markerDest.Height = markerDest.Width = markerVia.Height = markerVia.Width = 10;
            markerStart.ToolTip = "Start";
            markerDest.ToolTip  = "Destination";

            if (cbxManipulateWpt.Checked == true)
            {
                mapCoordVia = new System.Windows.Point(double.Parse(tbxViaX.Text.Replace(".", ",")), double.Parse(tbxViaY.Text.Replace(".", ",")));
                ShapeCanvas.SetLocation(markerVia, mapCoordVia);
                markerVia.ToolTip = "Via";
                routingLayer.Shapes.Add(markerVia);
            }

            routingLayer.Shapes.Add(markerStart);
            routingLayer.Shapes.Add(markerDest);

            dynMap.Layers.Add(routingLayer);

            //zoom to contain route
            MapRectangle mergedRoutesRectangle = new MapRectangle();
            var          polyLine = routeResponse.polyline.plain as xRouteWSService.Polyline;

            var winPoints = from coord in polyLine.polyline
                            select new System.Windows.Point(coord.x, coord.y);

            mergedRoutesRectangle |= new MapRectangle(winPoints);

            dynMap.SetEnvelope(mergedRoutesRectangle.Inflate(1.2), mapCoordFormat);

            routingLayer.Refresh();
        }
示例#20
0
        /// <summary> Adds a pin to the map for each way point. </summary>
        #region doc:update the way point pins
        private void UpdateWayPointPins()
        {
            // already disposed
            if (disposed)
            {
                return;
            }

            (wayPointLayer as ShapeLayer)?.Shapes.Clear();

            foreach (var wayPoint in wayPoints)
            {
                var pin = new Pin();

                if (wayPoints.IndexOf(wayPoint) == 0)
                {
                    pin.Color = Colors.Green;
                }
                else if (wayPoints.IndexOf(wayPoint) == wayPoints.Count - 1)
                {
                    pin.Color = Colors.Red;
                }
                else
                {
                    pin.Color = Colors.Blue;
                }

                #region doc:waypoint context menu
                var cmWayPoints = new ContextMenu();
                var item        = new MenuItem {
                    Header = "Remove", CommandParameter = wayPoint
                };
                item.Click += RemoveItemClick;
                cmWayPoints.Items.Add(item);
                item = new MenuItem {
                    Header = "Move up", CommandParameter = wayPoint
                };
                item.Click += MoveUpItemClick;
                cmWayPoints.Items.Add(item);
                item = new MenuItem {
                    Header = "Move down", CommandParameter = wayPoint
                };
                item.Click += MoveDownItemClick;
                cmWayPoints.Items.Add(item);
                ContextMenuService.SetContextMenu(pin, cmWayPoints);
                #endregion

                pin.Width  = 40;
                pin.Height = 40;

                // set tool tip information
                ToolTipService.SetToolTip(pin, wayPoints.IndexOf(wayPoint) == 0 ? "Start" : wayPoints.IndexOf(wayPoint) == 0 ? "End" : "Waypoint " + (wayPoints.IndexOf(wayPoint) + 1));

                pin.Name = "Waypoint" + (wayPoints.IndexOf(wayPoint) + 1);

                Panel.SetZIndex(pin, -1);

                ShapeCanvas.SetAnchor(pin, LocationAnchor.RightBottom);
                ShapeCanvas.SetLocation(pin, new System.Windows.Point(wayPoint.x, wayPoint.y));

                (wayPointLayer as ShapeLayer)?.Shapes.Add(pin);
            }

            wayPointLayer.Refresh();
        }
示例#21
0
        // Shows how to add an arbitrary controls to the map
        // As sample the pie charts series of Wpf toolkit is used
        // http://wpf.codeplex.com/releases/view/40535
        public void AddPieCharts(ShapeLayer layer)
        {
            // our demo data
            var stores = new List <Store> {
                new Store
                {
                    Name      = "KA-Center",
                    Latitude  = 48.96,
                    Longitude = 8.39,
                    Sales     = new List <Sale> {
                        new Sale {
                            Type = "Food", Amount = 30
                        },
                        new Sale {
                            Type = "Non Food", Amount = 70
                        }
                    }
                },
                new Store
                {
                    Name      = "KA-North",
                    Latitude  = 49.04,
                    Longitude = 8.41,
                    Sales     = new List <Sale> {
                        new Sale {
                            Type = "Food", Amount = 40
                        },
                        new Sale {
                            Type = "Non Food", Amount = 50
                        },
                        new Sale {
                            Type = "Pet Food", Amount = 10
                        }
                    }
                }
            };

            foreach (var store in stores)
            {
                // initialize a pie chart for each element
                var chart = new Chart();
                chart.BeginInit();

                chart.Width      = 300;
                chart.Height     = 250;
                chart.Background = new SolidColorBrush(Color.FromArgb(192, 255, 255, 255));
                var pieSeries = new PieSeries();
                chart.Title = store.Name;
                pieSeries.IndependentValuePath = "Type";
                pieSeries.DependentValuePath   = "Amount";
                pieSeries.ItemsSource          = store.Sales;
                pieSeries.IsSelectionEnabled   = true;
                chart.Series.Add(pieSeries);

                chart.EndInit();

                // Add to map
                ShapeCanvas.SetLocation(chart, new Point(store.Longitude, store.Latitude));
                ShapeCanvas.SetAnchor(chart, LocationAnchor.Center);
                ShapeCanvas.SetScale(chart, 2);
                ShapeCanvas.SetScaleFactor(chart, .25); // adopt the element to the scale factor
                layer.Shapes.Add(chart);
            }
        }
示例#22
0
        private void Form1_Load(object sender, EventArgs e)
        {
            // our test data
            var vehicles = new[]
            {
                new Vehicle {
                    Longitude = 8.3, Latitude = 49, Id = "1"
                },
                new Vehicle {
                    Longitude = 8.4, Latitude = 49.1, Id = "2"
                },
                new Vehicle {
                    Longitude = 8.5, Latitude = 49, Id = "3"
                }
            };

            // the drag&drop events for the grid
            vehicleDataGridView.DragEnter     += vehicleDataGridView_DragOver;
            vehicleDataGridView.DragOver      += vehicleDataGridView_DragOver;
            vehicleDataGridView.DragDrop      += vehicleDataGridView_DragDrop;
            vehicleDataGridView.CellMouseDown += vehicleDataGridView_CellMouseDown;

            // bind the grid to our data
            vehicleBindingSource.DataSource = vehicles;

            // initialize base map (for xServer internet)
            formsMap1.XMapUrl         = "xserver2-europe-test";
            formsMap1.XMapCredentials = "Insert your xToken here";
            formsMap1.WrappedMap.Xmap2LayerFactory.MapStyle = "blackmarble"; // TODO: implement XMapStyle for map root object

            // go to Karlsruhe
            formsMap1.SetMapLocation(new Point(8.4, 49.05), 10);

            // add a new Shape Layer
            var layer = new ShapeLayer("MyShapes");

            formsMap1.Layers.Add(layer);

            // add items for all elements
            foreach (var vehicle in vehicles)
            {
                // create  a truck marker
                var marker = new Truck
                {
                    Color     = Colors.LightBlue,
                    Width     = 50,
                    ToolTip   = "Hello Map",
                    AllowDrop = true
                };

                // events for drag&drop
                marker.MouseDown += Marker_MouseDown;
                marker.DragEnter += marker_DragOver;
                marker.DragOver  += marker_DragOver;
                marker.Drop      += marker_Drop;

                // set the vehicle data as tag
                marker.Tag = vehicle;

                // set position and add to map
                ShapeCanvas.SetLocation(marker, new Point(vehicle.Longitude, vehicle.Latitude));
                layer.Shapes.Add(marker);
            }
        }
示例#23
0
        private void DealerSearch(System.Windows.Point point)
        {
            Cursor = Cursors.Wait;
            mapControl.SetMapLocation(point, 12, srid);
            reachableObjectLayer.Shapes.Clear();
            isochroneLayer.Shapes.Clear();

            var waypoint = new WaypointDesc()
            {
                linkType      = LinkType.NEXT_SEGMENT,
                wrappedCoords = new XRoute.Point[]
                {
                    new XRoute.Point()
                    {
                        point = new PlainPoint()
                        {
                            x = point.X,
                            y = point.Y,
                        },
                    },
                },
            };

            var expansionDesc = new ExpansionDescription()
            {
                expansionType   = ExpansionType.EXP_TIME,
                wrappedHorizons = new int[] { 900 },
            };

            var options = new ReachableObjectsOptions()
            {
                expansionDesc      = expansionDesc,
                linkType           = LinkType.NEXT_SEGMENT,
                routingDirection   = RoutingDirectionType.FORWARD,
                geodatasourceLayer = XDealerSample.Properties.Settings.Default.GeoDataSource,
            };

            var cc = new CallerContext()
            {
                wrappedProperties = new CallerContextProperty[]
                {
                    new CallerContextProperty()
                    {
                        key = "CoordFormat", value = "PTV_MERCATOR"
                    },
                    new CallerContextProperty()
                    {
                        key = "Profile", value = "carfast"
                    },
                }
            };

            var isoOptions = new IsochroneOptions()
            {
                expansionDesc          = expansionDesc,
                isoDetail              = IsochroneDetail.POLYS_ONLY,
                polygonCalculationMode = PolygonCalculationMode.NODE_BASED,
            };

            ReachableObjects foundObjects = null;
            Isochrone        isochrone    = null;

            using (var xRouteClient = new XRouteWSClient())
            {
                try
                {
                    foundObjects = xRouteClient.searchForReachableObjects(waypoint, null, null, options, null, cc);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(
                        "Exception while searching for objects.\n\nException type: " + exception.GetType().ToString() +
                        "\nMessage: " + exception.Message);
                    Cursor = null;
                    return;
                }
                try
                {
                    isochrone = xRouteClient.calculateIsochrones(waypoint, null, isoOptions, cc);
                }
                catch (Exception exception)
                {
                    MessageBox.Show(
                        "Exception while calculating isochrone.\n\nException type: " + exception.GetType().ToString() +
                        "\nMessage: " + exception.Message);
                    Cursor = null;
                    return;
                }
            }

            foreach (var foundObject in foundObjects.wrappedReachableObject)
            {
                var ball = new Ball()
                {
                    Height  = 10,
                    Width   = 10,
                    Tag     = [email protected],
                    ToolTip = "",
                    Color   = Colors.Blue,
                };
                ball.ToolTipOpening += ball_ToolTipOpening;

                var winPoint = new System.Windows.Point()
                {
                    X = [email protected],
                    Y = [email protected],
                };
                ShapeCanvas.SetLocation(ball, winPoint);
                reachableObjectLayer.Shapes.Add(ball);
            }

            var linearRing = new NetTopologySuite.Geometries.LinearRing(
                isochrone.wrappedIsochrones[0].polys.lineString.wrappedPoints
                .Select(p => new GeoAPI.Geometries.Coordinate(p.x, p.y))
                .ToArray()
                );

            linearRing.Normalize();

            var geom = new NetTopologySuite.Geometries.Polygon(linearRing);

            var bufferedGeom = geom.Buffer(100);
            var polygon      = new MapPolygon()
            {
                Points  = new PointCollection(bufferedGeom.Boundary.Coordinates.Select(c => new System.Windows.Point(c.X, c.Y))),
                Fill    = new SolidColorBrush(Colors.AliceBlue),
                Opacity = 0.75,
                Stroke  = new SolidColorBrush(Colors.DarkSlateGray)
            };

            isochroneLayer.Shapes.Add(polygon);

            Cursor = null;
        }
        /// <summary>
        /// The arrow demo is uses an adaption of Charles Petzold's WPF arrow class
        /// http://charlespetzold.com/blog/2007/04/191200.html to be used as custom MapShape
        /// </summary>
        /// <param name="layer"></param>
        public void AddPinWithLabel(ShapeLayer layer)
        {
            // text and symbol as two shapes
            Control pin = new Pin();

            pin.Width = pin.Height = 30;
            ShapeCanvas.SetLocation(pin, new Point(8.4, 49));
            ShapeCanvas.SetAnchor(pin, LocationAnchor.RightBottom);
            layer.Shapes.Add(pin);

            var textBlock = new TextBlock
            {
                Text       = "Hello",
                Background = new SolidColorBrush(Colors.White),
                Foreground = new SolidColorBrush(Colors.Black)
            };

            ShapeCanvas.SetLocation(textBlock, new Point(8.4, 49));
            ShapeCanvas.SetAnchor(textBlock, LocationAnchor.LeftTop);
            layer.Shapes.Add(textBlock);


            // text with symbol in a view box
            var grid = new Grid();

            grid.RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(50)
            });
            grid.RowDefinitions.Add(new RowDefinition {
                Height = new GridLength(50)
            });
            grid.ColumnDefinitions.Add(new ColumnDefinition {
                Width = new GridLength(50)
            });

            var viewBox = new Viewbox {
                Stretch = Stretch.Uniform
            };

            pin           = new Cube();
            viewBox.Child = pin;
            Grid.SetRow(viewBox, 0);
            grid.Children.Add(viewBox);

            viewBox = new Viewbox {
                Stretch = Stretch.Uniform
            };
            textBlock = new TextBlock
            {
                Text       = "Hello",
                Background = new SolidColorBrush(Colors.White),
                Foreground = new SolidColorBrush(Colors.Black)
            };
            viewBox.Child = textBlock;
            Grid.SetRow(viewBox, 1);
            grid.Children.Add(viewBox);

            ShapeCanvas.SetLocation(grid, new Point(8.5, 49));
            ShapeCanvas.SetScaleFactor(grid, .1);
            layer.Shapes.Add(grid);
        }
        /// <summary>
        /// Adds a ShapeLayer for the markers.
        /// </summary>
        protected override void Enable()
        {
            var myLayer = new ShapeLayer("ManySymbols")
            {
                LazyUpdate = true
            };

            wpfMap.Layers.Add(myLayer);

            var       center = new Point(8.4, 49); // KA
            const int radius = 1;                  // radius in degrees of latitude

            var rand = new Random();
            Func <Point, double, Point> randomCoordinate = (c, r) =>
            {
                var angle    = rand.NextDouble() * 2 * Math.PI;
                var distance = r * Math.Sqrt(rand.NextDouble());

                return(new Point {
                    X = c.X + distance * Math.Cos(angle), Y = c.Y + distance * Math.Sin(angle)
                });
            };

            const bool useBitmapCache = true;

            var pin = new Pyramid();

            pin.Width = pin.Height = 10;

            pin.Measure(new Size(pin.Width, pin.Height));
            pin.Arrange(new Rect(0, 0, pin.Width, pin.Height));

            var bitmap = new RenderTargetBitmap((int)pin.Width, (int)pin.Height, 96, 96, PixelFormats.Pbgra32);

            bitmap.Render(pin);
            bitmap.Freeze();
            for (var i = 0; i < 500; i++)
            {
                FrameworkElement symbol;
                if (useBitmapCache)
                {
                    symbol = new Image {
                        Source = bitmap
                    }
                }
                ;
                else
                {
                    symbol = new Pyramid();
                }
                symbol.Width = pin.Height = 10;
                ShapeCanvas.SetLocation(symbol, randomCoordinate(center, radius));
                symbol.ToolTip = "Hello";
                myLayer.Shapes.Add(symbol);
            }

            wpfMap.SetMapLocation(center, 9);

            // get the map view containing the content
            var mapView = Controls.Map.Tools.MapElementExtensions.FindChild <Controls.Map.MapView>(wpfMap);

            selectInteractor = new SelectInteractor(mapView, myLayer.Shapes);
        }