Ejemplo n.º 1
0
        public void TestMapCSSClosedWay()
        { // tests map css interpretation of a closed way marked as an area.
            MemoryDataSource source = new MemoryDataSource(
                Node.Create(1, 0, 0),
                Node.Create(2, 1, 0),
                Node.Create(3, 0, 1),
                Way.Create(1, new SimpleTagsCollection(
                               Tag.Create("area", "yes")), 1, 2, 3, 1));

            // test closed way.
            string css = "way[area] { " +
                         "   fill-color: black; " +
                         "} ";

            // create the projection and scene objects.
            var     mercator = new WebMercator();
            Scene2D scene    = new Scene2DSimple();

            // create the interpreter.
            MapCSSInterpreter interpreter = new MapCSSInterpreter(css,
                                                                  new MapCSSDictionaryImageSource());

            interpreter.Translate(scene, mercator, source, source.GetWay(1));

            // test the scene contents.
            Assert.AreEqual(1, scene.Count);
            List <IScene2DPrimitive> primitives = scene.Get(0);

            Assert.IsNotNull(primitives);
            Assert.AreEqual(1, primitives.Count);
            IScene2DPrimitive primitive = primitives[0];

            Assert.IsInstanceOf <Polygon2D>(primitive);
        }
Ejemplo n.º 2
0
        public void Add()
        {
            
                                                 GroupLayer gl = AppState.ViewDef.FindOrCreateGroupLayer(@"Weather/Rain");
                                                 var w = new WebMercator();
                                                 //Buienradar
                                                 var wi = new ElementLayer() { ID = "Rain Radar" };
                                                 var i = new Image
                                                 {
                                                     Source = new BitmapImage(new Uri("http://www2.buienradar.nl/euradar/latlon_0.gif")),
                                                     IsHitTestVisible = false,
                                                     Stretch = Stretch.Fill
                                                 };
                                                 //<LatLonBox><north>59.9934</north><south>41.4389</south><east>20.4106</east><west>-14.9515</west></LatLonBox>
                                                 var mpa = new MapPoint(-14.9515, 41.4389);
                                                 var mpb = new MapPoint(20.4106, 59.9934);
                                                 mpa = w.FromGeographic(mpa) as MapPoint;
                                                 mpb = w.FromGeographic(mpb) as MapPoint;
                                                 var envelope = new Envelope(mpa, mpb);
                                                 ElementLayer.SetEnvelope(i, envelope);
                                                 wi.Children.Add(i);
                                                 wi.Initialize();
                                                 wi.Visible = true;
                                                 gl.ChildLayers.Add(wi);
            
            

        }
Ejemplo n.º 3
0
        public void Add()
        {            
            GroupLayer gl = AppState.ViewDef.FindOrCreateGroupLayer(@"Environment");
            var w = new WebMercator();
            ElementLayer wi = new ElementLayer() { ID = "NO2" };
            var i = new Image
            {
                Source = new BitmapImage(new Uri("http://cool2.mooo.com/urbanfloodwebsite/images/NO2proj2.png")),
                IsHitTestVisible = false,
                Stretch = Stretch.Fill
            };
            //<LatLonBox id="khLatLonBox218"><north>90</north><south>-90</south><east>180</east><west>-180</west></LatLonBox>

            //102100
            var mpa = new MapPoint(-14.9515, 41.4389);
            var mpb = new MapPoint(20.4106, 59.9934);
            mpa = w.FromGeographic(mpa) as MapPoint;
            mpb = w.FromGeographic(mpb) as MapPoint;

            mpa = w.FromGeographic(new MapPoint(-180, -85.0511, new SpatialReference(4326))) as MapPoint;
            mpb = w.FromGeographic(new MapPoint(180, 85.0511, new SpatialReference(4326))) as MapPoint;
            var envelope = new Envelope(mpa, mpb);
            ElementLayer.SetEnvelope(i, envelope);

            wi.Children.Add(i);
            wi.Initialize();
            wi.Visible = true;
            gl.ChildLayers.Add(wi);


        }
Ejemplo n.º 4
0
        public void TestMapCSSArea()
        {
            MemoryDataSource source = new MemoryDataSource(
                Node.Create(1, 0, 0),
                Node.Create(2, 1, 0),
                Node.Create(3, 0, 1),
                Way.Create(1, new TagsCollection(
                               Tag.Create("area", "yes")), 1, 2, 3, 1));

            // test closed way.
            string css = "area { " +
                         "   fill-color: black; " +
                         "} ";

            // create the projection and scene objects.
            var     mercator = new WebMercator();
            Scene2D scene    = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), 16);

            // create the projection and scene objects.
            scene = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), 16);

            // create the interpreter.
            MapCSSInterpreter interpreter = new MapCSSInterpreter(css,
                                                                  new MapCSSDictionaryImageSource());

            interpreter.Translate(scene, mercator, source, source.GetWay(1));

            // test the scene contents.
            Assert.AreEqual(1, scene.Count);
            Primitive2D primitive = scene.Get(0);

            Assert.IsInstanceOf <Polygon2D>(primitive);
        }
Ejemplo n.º 5
0
        private static EsriPrjFile AsEsriPrjFile(WebMercator webMercator)
        {
            EsriPrjTreeNode root = new EsriPrjTreeNode();

            root.Name = EsriPrjFile._projcs;

            root.Values = new List <string>()
            {
                string.IsNullOrWhiteSpace(webMercator.Title) ? $"{webMercator.Ellipsoid.EsriName}_Web_Mercator_Auxiliary_Sphere" : webMercator.Title
            };

            var geogcs = new EsriPrjTreeNode(webMercator.Ellipsoid, webMercator.DatumName, webMercator.Ellipsoid.Srid);

            var projection = new EsriPrjTreeNode(EsriPrjFile._projection, EsriPrjFile._esriWebMercator);

            var falseEasting = new EsriPrjTreeNode(EsriPrjFile._parameter, EsriPrjFile._falseEasting, webMercator.FalseEasting.AsExactString());

            var falseNorthing = new EsriPrjTreeNode(EsriPrjFile._parameter, EsriPrjFile._falseNorthing, webMercator.FalseNorthing.AsExactString());

            var centralMeridian = new EsriPrjTreeNode(EsriPrjFile._parameter, EsriPrjFile._centralMeridian, webMercator.CentralMeridian.AsExactString());

            var standardParallel1 = new EsriPrjTreeNode(EsriPrjFile._parameter, EsriPrjFile._standardParallel1, webMercator.StandardParallel1.AsExactString());

            var auxiliarySphereType = new EsriPrjTreeNode(EsriPrjFile._parameter, EsriPrjFile._auxiliarySphereType, webMercator.AuxiliarySphereType.AsExactString());

            var unit = EsriPrjTreeNode.MeterUnit;

            root.Children = new List <EsriPrjTreeNode>()
            {
                geogcs, projection, falseEasting, falseNorthing, centralMeridian, standardParallel1, auxiliarySphereType, unit
            };

            return(new EsriPrjFile(root));
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates a new tiles layer.
        /// </summary>
        /// <param name="tilesURL">The tiles URL.</param>
        /// <param name="tileCacheSize">The tile cache size.</param>
        public LayerTile(string tilesURL, int tileCacheSize)
        {
            _tilesURL = tilesURL;
            _cache    = new LRUCache <Tile, Image2D>(tileCacheSize);

            _projection = new WebMercator();
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Calculates measurements - length/perimeter, area, latitude, and/or longitude -
        /// for the input geometry
        /// </summary>
        /// <param name="geometry"></param>
        private void MeasureGeometry(Geometry geometry)
        {
            if (geometry is MapPoint) // Update latitude and longitude
            {
                // If necessary, transform the point to WGS 84 to get latitude
                // and longitude in decimal degrees
                MapPoint point = (MapPoint)geometry;
                if (point.SpatialReference.IsWebMercator())
                {
                    point = new WebMercator().ToGeographic(geometry) as MapPoint;
                }

                point = (MapPoint)Geometry.NormalizeCentralMeridian(point);

                Latitude  = point.Y;
                Longitude = point.X;
            }
            else if (geometry is Polyline) // Update length
            {
                Length = ((Polyline)geometry).Length();
            }
            else if (geometry is Polygon || geometry is Envelope) // Update area
            {
                // If geometry is an envelope, convert it to a polygon
                Polygon polygon = geometry is Polygon ? (Polygon)geometry :
                                  ((Envelope)geometry).ToPolygon();

                Length = polygon.Perimeter();
                Area   = polygon.Area();
            }
            else
            {
                throw new Exception(Strings.MeasureUnsupportedGeometryType);
            }
        }
Ejemplo n.º 8
0
        public void TestSimpleWebMercator()
        {
            // TODO: stabalize the webmercator projection numerically for lower zoom levels (0-9).
            var mercator = new WebMercator();

            for (int zoomLevel = 10; zoomLevel <= 25; zoomLevel++)
            {
                var tile = Tile.CreateAroundLocation(new GeoCoordinate(0, 0), zoomLevel);

                double[] topleft     = mercator.ToPixel(tile.Box.TopLeft);
                double[] bottomright = mercator.ToPixel(tile.Box.BottomRight);

                double scaleFactor = mercator.ToZoomFactor(zoomLevel);

                Assert.AreEqual(-256, (topleft[0] - bottomright[0]) * scaleFactor, 0.01);
                Assert.AreEqual(-256, (topleft[1] - bottomright[1]) * scaleFactor, 0.01);
            }

            var coordinate = new GeoCoordinate(51.26337, 4.78739);

            double[] projected   = mercator.ToPixel(coordinate);
            var      reProjected = mercator.ToGeoCoordinates(projected[0], projected[1]);

            Assert.AreEqual(coordinate.Longitude, reProjected.Longitude, 0.0001);
            Assert.AreEqual(coordinate.Latitude, reProjected.Latitude, 0.0001);
        }
Ejemplo n.º 9
0
        public void TestWebMercator()
        {
            var mercator = new WebMercator();

            double[] zerozero = mercator.ToPixel(new GeoCoordinate(0, 0));
            double[] oneone   = mercator.ToPixel(new GeoCoordinate(1, 1));
        }
Ejemplo n.º 10
0
        public static Geometry ProjectGeometryToMap(Geometry geometry, Map map)
        {
            if (geometry == null || map == null)
            {
                return(geometry);
            }

            if (geometry.SpatialReference.WKID == map.SpatialReference.WKID)
            {
                return(geometry);
            }

            WebMercator webMercator = new WebMercator();

            // convert from WGS84 to Web-Mercator
            if (IsWGS84SR(geometry.SpatialReference) && IsWebMercatorSR(map.SpatialReference))
            {
                return(webMercator.FromGeographic(geometry));
            }

            // convert from Web-Mercator to WGS84
            if (IsWebMercatorSR(geometry.SpatialReference) && IsWGS84SR(map.SpatialReference))
            {
                return(webMercator.ToGeographic(geometry));
            }

            // not supported SRs - return the non projected geometry
            return(geometry);
        }
Ejemplo n.º 11
0
 private static Models.TileCoordinates GetTileCoordinatesAtPoint(double longitude, double latitude, int zoomLevel)
 {
     return(new Models.TileCoordinates(
                (int)Math.Floor(WebMercator.TileCoordinateXAtZoom(longitude, zoomLevel)),
                (int)Math.Floor(WebMercator.TileCoordinateYAtZoom(latitude, zoomLevel)),
                zoomLevel));
 }
Ejemplo n.º 12
0
    // Use this for initialization
    void Start()
    {
        //Debug.Log((float)node.getLongitude() + " - " + (float)node.getLatitude());
        //transform.position = Quaternion.AngleAxis((float)node.getLongitude(), -Vector3.up) * Quaternion.AngleAxis((float)node.getLatitude(), -Vector3.right) * new Vector3(25, 25, 25);
        transform.position = new Vector3((float)WebMercator.ConvertLongitudeToX(node.getLongitude()) / 750, 0, (float)WebMercator.ConvertLatitudeToY(node.getLatitude()) / 750);
        //transform.position = new Vector3(0, 2, 54);

        // Rework this to account for curvature of Earth //
    }
        protected override void Invoke(object parameter)
        {
            // Reset error
            Error = null;

            try
            {
                if (Target != null && OutputSpatialReference != null)
                {
                    if (Target.SpatialReference == OutputSpatialReference ||
                        (Target.SpatialReference.IsWebMercator() && OutputSpatialReference.IsWebMercator()))
                    {
                        // Input geometry and output spatial reference define the
                        // same projection.  Assign input to output and complete.
                        OutputGeometry = Target;
                        OnCompleted();
                    }
                    else if (Target.SpatialReference.IsWebMercator() &&
                             OutputSpatialReference.WKID == 4326)
                    {
                        // Web Mercator to WGS 84 can be done client-side
                        OutputGeometry = new WebMercator().ToGeographic(Target);
                        OnCompleted();
                    }
                    else if (Target.SpatialReference.WKID == 4326 &&
                             OutputSpatialReference.IsWebMercator())
                    {
                        // WGS 84 to Web Mercator can be done client-side
                        OutputGeometry = new WebMercator().FromGeographic(Target);
                        OnCompleted();
                    }
                    else if (!string.IsNullOrEmpty(GeometryServiceUrl)) // Need to use geometry service
                    {
                        Graphic g = new Graphic()
                        {
                            Geometry = Target
                        };

                        // if a previous project operation is still running, cancel it
                        if (_geometryService.IsBusy)
                        {
                            _geometryService.CancelAsync();
                        }
                        _geometryService.ProjectAsync(new Graphic[] { g }, OutputSpatialReference);
                    }
                    else // input not valid
                    {
                        OnFailed(new Exception(Strings.ProjectInputsNotValid));
                    }
                }
            }
            catch (Exception ex)
            {
                OnFailed(ex);
            }
        }
Ejemplo n.º 14
0
        public MainWindow()
        {
            // License setting and ArcGIS Runtime initialization is done in Application.xaml.cs.

            InitializeComponent();
            webmercator = new WebMercator();
            random      = new Random();
            TimeSpan interval = new TimeSpan(0, 0, 40);

            MyMap.PanDuration = interval;
            startTimer();
        }
Ejemplo n.º 15
0
        public double GetBearing()
        {
            var w = new WebMercator();
            var p1 = w.ToGeographic(Start.Mp) as MapPoint;
            var p2 = w.ToGeographic(Finish.Mp) as MapPoint;
            var lon1 = p1.X;
            var lat1 = p1.Y;
            var lon2 = p2.X;
            var lat2 = p2.Y;

            return csShared.Utils.CoordinateUtils.Bearing(lat1, lon1, lat2, lon2);
        }
Ejemplo n.º 16
0
        public static Geometry ProjectGeometryToGeographic(Geometry geometry)
        {
            if (IsWGS84SR(geometry.SpatialReference))
            {
                return(geometry);
            }

            WebMercator webMercator = new WebMercator();

            // convert from Web-Mercator to WGS84
            return(webMercator.ToGeographic(geometry));
        }
Ejemplo n.º 17
0
        public void TestSimpleWebMercatorZoomLevel()
        {
            var mercator = new WebMercator();

            for (int orignalLevel = 0; orignalLevel < 20; orignalLevel++)
            {
                double zoomFactor = mercator.ToZoomFactor(orignalLevel);
                double zoomLevel  = mercator.ToZoomLevel(zoomFactor);

                Assert.AreEqual(orignalLevel, zoomLevel, 0.001);
            }
        }
Ejemplo n.º 18
0
 private void LatLngToPix_Click(object sender, RoutedEventArgs e)
 {
     try {
         Point pMeters = WebMercator.LatLonToMeters(Double.Parse(LatTxt.Text), Double.Parse(LngTxt.Text));
         Point pPixels = WebMercator.MetersToPixels(pMeters, int.Parse(ZoomTxt.Text));
         XPixTxt.Text = pPixels.X.ToString();
         YPixTxt.Text = pPixels.Y.ToString();
     }
     catch (Exception ex)
     {
     }
 }
Ejemplo n.º 19
0
        public MainWindow()
        {
            // License setting and ArcGIS Runtime initialization is done in Application.xaml.cs.

            InitializeComponent();
            webmercator = new WebMercator();
            random = new Random();
            TimeSpan interval = new TimeSpan(0, 0, 40);
            MyMap.PanDuration = interval;
            startTimer();
            
        }
Ejemplo n.º 20
0
        private async Task <IActionResult> GetTileAsync(string tileset, int tileCol, int tileRow, int tileMatrix, string mediaType)
        {
            var tileSource = this.tileSourceFabric.Get(tileset);

            if (!WebMercator.IsInsideBBox(tileCol, tileRow, tileMatrix, tileSource.Configuration.Srs))
            {
                return(ResponseWithNotFoundError(Identifiers.NotFound, "The requested tile is outside the bounding box of the tile map."));
            }

            var data = await tileSource.GetTileAsync(tileCol, WebMercator.FlipYCoordinate(tileRow, tileMatrix), tileMatrix); // In WMTS Y axis goes down from the top

            if (data != null && data.Length > 0)
            {
                if (String.Compare(mediaType, tileSource.Configuration.ContentType, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    return(File(data, mediaType)); // Return original source image
                }
                else
                {
                    var isFormatSupported = Utils.EntitiesConverter.IsFormatInList(
                        new[]
                    {
                        MediaTypeNames.Image.Png,
                        MediaTypeNames.Image.Jpeg,
                        MediaTypeNames.Image.Webp,
                    },
                        mediaType);

                    // Convert source image to requested output format, if possible
                    if (isFormatSupported)
                    {
                        var outputImage = ImageHelper.ConvertImageToFormat(data, mediaType, 90); // TODO: quality parameter
                        if (outputImage != null)
                        {
                            return(File(outputImage, mediaType));
                        }
                        else
                        {
                            return(ResponseWithNotFoundError(Identifiers.NotFound, "Specified tile was not found"));
                        }
                    }
                    else
                    {
                        return(File(data, mediaType)); // Conversion not possible
                    }
                }
            }
            else
            {
                return(ResponseWithNotFoundError(Identifiers.NotFound, "Specified tile was not found"));
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Creates a new tiles layer.
        /// </summary>
        /// <param name="tilesURL">The tiles URL.</param>
        /// <param name="tileCacheSize">The tile cache size.</param>
        public LayerTile(string tilesURL, int tileCacheSize)
        {
            _nativeImageCache = NativeImageCacheFactory.Create();
            _tilesURL         = tilesURL;
            _cache            = new LRUCache <Tile, Image2D>(tileCacheSize);
            _cache.OnRemove  += OnRemove;
            _stack            = new LimitedStack <Tile>(tileCacheSize, tileCacheSize);
            _timer            = new Timer(this.LoadQueuedTiles, null, System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
            _attempts         = new Dictionary <Tile, int>();
            _suspended        = false;

            _projection = new WebMercator();
        }
Ejemplo n.º 22
0
        public double GetDistance()
        {
            var w = new WebMercator();
            var p1 = w.ToGeographic(Start.Mp) as MapPoint;
            var p2 = w.ToGeographic(Finish.Mp) as MapPoint;
            var pLon1 = p1.X;
            var pLat1 = p1.Y;
            var pLon2 = p2.X;
            var pLat2 = p2.Y;

            var dist = csShared.Utils.CoordinateUtils.Distance(pLat1, pLon1, pLat2, pLon2, 'K');
            return dist;//Math.Sqrt((deltaX*deltaX) + (deltaY*deltaY));
        }
Ejemplo n.º 23
0
        private static void DrawWebMercatorTilesToRasterCanvas(
            SKCanvas outputCanvas,
            int width,
            int height,
            Models.Bounds boundingBox,
            IList <Models.TileDataset> sourceTiles,
            uint backgroundColor,
            int tileSize)
        {
            var zoom         = sourceTiles[0].Z;
            var tileMinX     = sourceTiles.Min(t => t.X);
            var tileMinY     = sourceTiles.Min(t => t.Y);
            var tilesCountX  = sourceTiles.Max(t => t.X) - tileMinX + 1;
            var tilesCountY  = sourceTiles.Max(t => t.Y) - tileMinY + 1;
            var canvasWidth  = tilesCountX * tileSize;
            var canvasHeight = tilesCountY * tileSize;

            var imageInfo = new SKImageInfo(
                width: canvasWidth,
                height: canvasHeight,
                colorType: SKColorType.Rgba8888,
                alphaType: SKAlphaType.Premul);

            using var surface = SKSurface.Create(imageInfo);
            using var canvas  = surface.Canvas;
            canvas.Clear(new SKColor(backgroundColor));

            // Draw all tiles
            foreach (var sourceTile in sourceTiles)
            {
                var offsetX = (sourceTile.X - tileMinX) * tileSize;
                var offsetY = (sourceTile.Y - tileMinY) * tileSize;
                using var sourceImage = SKImage.FromEncodedData(sourceTile.ImageData);
                canvas.DrawImage(sourceImage, SKRect.Create(offsetX, offsetY, tileSize, tileSize)); // Source tile scaled to dest rectangle, if needed
            }

            // Clip and scale to requested size of output image
            var geoBBox         = EntitiesConverter.MapRectangleToGeographicalBounds(boundingBox);
            var pixelOffsetX    = WebMercator.LongitudeToPixelXAtZoom(geoBBox.MinLongitude, zoom) - tileSize * tileMinX;
            var pixelOffsetY    = WebMercator.LatitudeToPixelYAtZoom(geoBBox.MaxLatitude, zoom) - tileSize * tileMinY;
            var pixelWidth      = WebMercator.LongitudeToPixelXAtZoom(geoBBox.MaxLongitude, zoom) - WebMercator.LongitudeToPixelXAtZoom(geoBBox.MinLongitude, zoom);
            var pixelHeight     = WebMercator.LatitudeToPixelYAtZoom(geoBBox.MinLatitude, zoom) - WebMercator.LatitudeToPixelYAtZoom(geoBBox.MaxLatitude, zoom);
            var sourceRectangle = SKRect.Create((float)pixelOffsetX, (float)pixelOffsetY, (float)pixelWidth, (float)pixelHeight);
            var destRectangle   = SKRect.Create(0, 0, width, height);

            using SKImage canvasImage = surface.Snapshot();
            outputCanvas.DrawImage(canvasImage, sourceRectangle, destRectangle, new SKPaint {
                FilterQuality = SKFilterQuality.High,
            });
        }
Ejemplo n.º 24
0
        public void TestCanvasSettingsCSS()
        {
            // create CSS.
            string css = "canvas { " +
                         "fill-color: green; " +
                         "} ";

            // create 'test' objects.
            Node node1 = new Node();

            node1.Id        = 1;
            node1.Latitude  = 1;
            node1.Longitude = 1;

            Node node2 = new Node();

            node2.Id        = 2;
            node2.Latitude  = 2;
            node2.Longitude = 2;

            Way way = new Way();

            way.Id    = 1;
            way.Nodes = new List <long>();
            way.Nodes.Add(1);
            way.Nodes.Add(2);

            // create the datasource.
            MemoryDataSource dataSource = new MemoryDataSource();

            dataSource.AddNode(node1);
            dataSource.AddNode(node2);
            dataSource.AddWay(way);

            // create the projection and scene objects.
            var     mercator = new WebMercator();
            Scene2D scene    = new Scene2D(new OsmSharp.Math.Geo.Projections.WebMercator(), 16);

            // create the interpreter.
            MapCSSInterpreter interpreter = new MapCSSInterpreter(css,
                                                                  new MapCSSDictionaryImageSource());

            interpreter.Translate(scene, mercator, dataSource, node1);
            interpreter.Translate(scene, mercator, dataSource, node2);
            interpreter.Translate(scene, mercator, dataSource, way);

            // test the scene contents.
            Assert.AreEqual(0, scene.Count);
            Assert.AreEqual(SimpleColor.FromKnownColor(KnownColor.Green).Value, scene.BackColor);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Tests rendering the given serialized scene.
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="box"></param>
        /// <param name="testCount"></param>
        /// <param name="createTarget"></param>
        /// <param name="createRenderer"></param>
        /// <param name="range"></param>
        /// <param name="minZoom"></param>
        public static void TestRenderScene(CreateTarget createTarget, CreateRenderer createRenderer,
                                           Stream stream, GeoCoordinateBox box, int testCount, int range, int minZoom)
        {
            WebMercator projection = new WebMercator();

            // build a map.
            Map map = new Map();
            TagsCollectionBase metaTags;

            map.AddLayer(new LayerScene(
                             Scene2D.Deserialize(stream, true, out metaTags)));

            // build the target and renderer.
            TTarget target = createTarget.Invoke(TargetWidth, TargetHeight);
            MapRenderer <TTarget> mapRenderer = new MapRenderer <TTarget>(
                createRenderer.Invoke());

            // render the map.
            PerformanceInfoConsumer performanceInfo = new PerformanceInfoConsumer("Scene2DLayeredRendering");

            performanceInfo.Start();
            //performanceInfo.Report("Rendering {0} random images...", testCount);

            while (testCount > 0)
            {
                // randomize view.
                int zoom = minZoom;
                if (range > 1)
                { // only randomize when range is > 1
                    zoom = OsmSharp.Math.Random.StaticRandomGenerator.Get().Generate(range) + minZoom;
                }
                GeoCoordinate center = box.GenerateRandomIn();
                View2D        view   = mapRenderer.Create(TargetWidth, TargetHeight, map,
                                                          (float)projection.ToZoomFactor(zoom), center, false, true);

                OsmSharp.Logging.Log.TraceEvent("Scene2DLayeredRendering", OsmSharp.Logging.TraceEventType.Information,
                                                string.Format("Rendering at z{0} l{1}.",
                                                              zoom, center));
                map.ViewChanged((float)projection.ToZoomFactor(zoom), center, view, view);

                mapRenderer.Render(target, map, view, (float)projection.ToZoomFactor(zoom));

                testCount--;
            }

            performanceInfo.Stop();
            stream.Seek(0, SeekOrigin.Begin);
        }
Ejemplo n.º 26
0
        public void TestEmptyCSS()
        {
            // create 'test' objects.
            Node node1 = new Node();

            node1.Id        = 1;
            node1.Latitude  = 1;
            node1.Longitude = 1;

            Node node2 = new Node();

            node2.Id        = 2;
            node2.Latitude  = 2;
            node2.Longitude = 2;

            Way way = new Way();

            way.Id    = 1;
            way.Nodes = new List <long>();
            way.Nodes.Add(1);
            way.Nodes.Add(2);

            // create the datasource.
            MemoryDataSource dataSource = new MemoryDataSource();

            dataSource.AddNode(node1);
            dataSource.AddNode(node2);
            dataSource.AddWay(way);

            // create the projection and scene objects.
            var     mercator = new WebMercator();
            Scene2D scene    = new Scene2DSimple();

            // create the interpreter.
            MapCSSInterpreter interpreter = new MapCSSInterpreter(string.Empty,
                                                                  new MapCSSDictionaryImageSource());

            interpreter.Translate(scene, mercator, dataSource, node1);
            interpreter.Translate(scene, mercator, dataSource, node2);
            interpreter.Translate(scene, mercator, dataSource, way);

            // test the scene contents.
            Assert.AreEqual(0, scene.Count);
            Assert.AreEqual(SimpleColor.FromKnownColor(KnownColor.Black).Value, scene.BackColor);
        }
Ejemplo n.º 27
0
        public void AddPoi(PoI p)
        {
            UIElement uiElement;


            ImageSource imageSource = p.NEffectiveStyle.Picture;
    
            double opacity = p.NEffectiveStyle.FillOpacity.HasValue ? p.NEffectiveStyle.FillOpacity.Value : 1.0;

            uiElement = new PoiImageOverlay
            {
                Poi = p,
                Source = imageSource,
                Stretch = Stretch.Fill,
                Opacity = opacity,
                Name = "testImage",
                Tag = "testImage"
            };
            

           

            // Set the rotation
            if (p.Orientation != 0.0)
            {
                uiElement.RenderTransformOrigin = new Point(0.5, 0.5);
                uiElement.RenderTransform = new RotateTransform { Angle = p.Orientation }; // KML rotations are specified in a counterclockwise direction
            }

            // Set the envelope
            var elementLayerEnvelopeProperty = ElementLayer.EnvelopeProperty;
            if (p.Points.Count == 2)
            {
                var envelope = new Envelope(new MapPoint(p.Points[0].X, p.Points[0].Y),
                    new MapPoint(p.Points[1].X, p.Points[1].Y));
                var projection = new WebMercator();
                envelope = (Envelope) projection.FromGeographic(envelope) as Envelope;

                uiElement.SetValue(elementLayerEnvelopeProperty, envelope);
                p.Data["Image"] = uiElement;
                p.Data["layer"] = this;
                // Add element to element layer
                this.Children.Add(uiElement);
            }
        }
Ejemplo n.º 28
0
        void RainRadarUpdate_Tick(object sender, EventArgs e)
        {

            WebMercator w = new WebMercator();
            //WebClient wc = new WebClient();
            var topleft = new KmlPoint(-14.9515, 59.9934);
            var bottomright = new KmlPoint(20.4106, 41.4389);
            var fname = "http://www2.buienradar.nl/euradar/latlon_0.gif";//"rainradar.gif";
//            File.Delete(fname);
//            wc.DownloadFile("http://www2.buienradar.nl/euradar/latlon_0.gif", fname);

//            var gwrap = new GdalWrapper();
//            var f = gwrap.WarpImage(fname, topleft.Latitude, topleft.Longitude, bottomright.Latitude, bottomright.Longitude, 4326, 3857, 5000);
//            fname = Directory.GetCurrentDirectory() + "\\" + f;
            //var f = WarpImage(fname, topleft, bottomright, 4326, 3857, 5000);
            var i = new Image
            {
                //Source = new BitmapImage(new Uri("file://" + fname)),
                Source = new BitmapImage(new Uri(fname)),
                IsHitTestVisible = false,
                Stretch = Stretch.Fill
            };

            //<LatLonBox><north>59.9934</north><south>41.4389</south><east>20.4106</east><west>-14.9515</west></LatLonBox>
            var mpa = new MapPoint(topleft.Longitude, topleft.Latitude);
            var mpb = new MapPoint(bottomright.Longitude, bottomright.Latitude);
            mpa = w.FromGeographic(mpa) as MapPoint;
            mpb = w.FromGeographic(mpb) as MapPoint;
            var envelope = new Envelope(mpa, mpb);
            ElementLayer.SetEnvelope(i, envelope);
            this.Children.Clear();
            this.Children.Add(i);

            if (Notifications)
            {
                AppStateSettings.Instance.TriggerNotification(new NotificationEventArgs()
                {
                    Duration = new TimeSpan(0, 0, 0, 3),
                    Text = "Updated Rain Radar Image at"+ ":" + DateTime.Now
                });

            }
        }
Ejemplo n.º 29
0
        private static int FindOptimalTileZoomLevel(int width, Models.GeographicalBounds geoBBox)
        {
            var mapSize     = WebMercator.MapSize(width, geoBBox.MinLongitude, geoBBox.MaxLongitude);
            var minZoom     = 0;
            var minDistance = Double.MaxValue;

            for (var zoom = 0; zoom < 24; zoom++)                                           // TODO: range?
            {
                var mapSizeAtZoom = WebMercator.MapSize(zoom, WebMercator.DefaultTileSize); // TODO: ? use tile size parameter instead of const
                var distance      = Math.Abs(mapSize - mapSizeAtZoom);
                if (distance < minDistance)
                {
                    minDistance = distance;
                    minZoom     = zoom;
                }
            }

            return(minZoom);
        }
Ejemplo n.º 30
0
        public void TestMapCSSSimpleEval()
        {
            MemoryDataSource source = new MemoryDataSource(
                Node.Create(1, 0, 0),
                Node.Create(2, 1, 0),
                Node.Create(3, 0, 1),
                Way.Create(1, new SimpleTagsCollection(
                               Tag.Create("width", "10")), 1, 2, 3, 1));

            // test closed way.
            string css = "way { " +
                         "   width:  eval(\"tag('width')\"); " +
                         "   color: green; " +
                         "} ";

            // create the projection and scene objects.
            var     mercator = new WebMercator();
            Scene2D scene    = new Scene2DSimple();

            // create the projection and scene objects.
            scene = new Scene2DSimple();

            // create the interpreter.
            MapCSSInterpreter interpreter = new MapCSSInterpreter(css,
                                                                  new MapCSSDictionaryImageSource());

            interpreter.Translate(scene, mercator, source, source.GetWay(1));

            // test the scene contents.
            Assert.AreEqual(1, scene.Count);
            List <IScene2DPrimitive> primitives = scene.Get(0);

            Assert.IsNotNull(primitives);
            Assert.AreEqual(1, primitives.Count);
            IScene2DPrimitive primitive = primitives[0];

            Assert.IsInstanceOf <Line2D>(primitive);
            Line2D line = (primitive as Line2D);

            Assert.AreEqual(10, line.Width);
        }
Ejemplo n.º 31
0
        public void ZoomToPoint(double x, double y)
        {
            _mercator = new WebMercator();
            Graphic pointGraphic = new Graphic();

            pointGraphic.Geometry = new MapPoint(x, y);

            SimpleMarkerSymbol symbol = new SimpleMarkerSymbol();

            symbol.Color = new SolidColorBrush(Colors.Red);
            symbol.Style = SimpleMarkerSymbol.SimpleMarkerStyle.Diamond;
            symbol.Size  = 20;

            pointGraphic.Symbol = symbol;

            _myLocationLayer.Graphics.Clear();
            _myLocationLayer.Graphics.Add(pointGraphic);


            _map.ZoomTo(GetCenterExtent(pointGraphic.Geometry as MapPoint));
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Renders the given data onto a 100x100 image using bounds around null-island (1,1,-1,-1) and the MapCSS definition.
        /// </summary>
        /// <param name="dataSource"></param>
        /// <param name="mapCSS"></param>
        /// <returns></returns>
        private Bitmap Render(IDataSourceReadOnly dataSource, string mapCSS)
        {
            // create projection.
            WebMercator projection = new WebMercator();

            double[] topLeft     = projection.ToPixel(new Math.Geo.GeoCoordinate(1, 1));
            double[] bottomRight = projection.ToPixel(new Math.Geo.GeoCoordinate(-1, -1));

            // create view (this comes down to (1,1,-1,-1) for a size of 100x100).
            View2D view = View2D.CreateFromBounds(bottomRight[1], topLeft[0], topLeft[1], bottomRight[0]);
            //View2D view = View2D.CreateFrom(0, 0, 100, 100, 1.0 / 200.0, false, true);

            // create graphics
            Bitmap   rendering         = new Bitmap(100, 100);
            Graphics renderingGraphics = Graphics.FromImage(rendering);

            renderingGraphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            renderingGraphics.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            renderingGraphics.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            renderingGraphics.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            // create renderer.
            GraphicsRenderer2D     graphicsRenderer = new GraphicsRenderer2D();
            MapRenderer <Graphics> renderer         = new MapRenderer <Graphics>(graphicsRenderer);

            // create map.
            OsmSharp.UI.Map.Map map = new OsmSharp.UI.Map.Map();
            map.AddLayer(new LayerOsm(dataSource, new MapCSSInterpreter(mapCSS), projection));

            // notify the map that there was a view change!
            map.ViewChanged((float)view.CalculateZoom(100, 100), new Math.Geo.GeoCoordinate(0, 0), view);

            // ... and finally do the actual rendering.
            renderer.Render(Graphics.FromImage(rendering), map, view);

            //rendering.Save(@"c:\temp\rendering.bmp");

            return(rendering);
        }
Ejemplo n.º 33
0
        public void DoRequest()
        {
            Plugin.IsLoading = true;
            var wm = new WebMercator();
           var ext = (Envelope)wm.ToGeographic(AppState.ViewDef.MapControl.Extent);
           var center = ext.GetCenter();
           var radius = (int)(AppState.ViewDef.MapControl.Resolution * AppState.ViewDef.MapControl.ActualWidth);

           ThreadPool.QueueUserWorkItem(delegate
           {
               try
               {
                   var wc = new WebClient();


                   //string uri = "https://maps.googleapis.com/maps/api/place/textsearch/xml?query=" + SearchKey + "&sensor=true&key=AIzaSyB1qBfe0nLX_46z0K7G5LS4DLp-0GxazVM";
                   string uri =
                       "https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=" + center.Y.ToString(CultureInfo.InvariantCulture) + "," + center.X.ToString(CultureInfo.InvariantCulture) + "&radius=" + radius + "&sensor=false&keyword=" + Key + "&key=AIzaSyB1qBfe0nLX_46z0K7G5LS4DLp-0GxazVM";
                   string res = wc.DownloadString(uri);

                   Application.Current.Dispatcher.Invoke(
                       delegate {
                           {
                               lock (Plugin.ServiceLock)
                               {
                                   ParseResult(res);
                               }
                               Plugin.IsLoading = false;
                           } });
               }
               catch (Exception e)
               {
                   Plugin.IsLoading = false;
                   Logger.Log("Geocoding", "Error finding location", e.Message,
                       Logger.Level.Error,true);
               }
           });
        }
Ejemplo n.º 34
0
        public static MapPoint ToEsriWebMercatorMapPoint(this MapCoord mapLocation)
        {
            if (mapLocation.ProjectionWkid == CoordinateSystems.WebMercatorProjectionWkid)
            {
                var esriMapPoint = new MapPoint(mapLocation.Longitude, mapLocation.Latitude, new SpatialReference(CoordinateSystems.WebMercatorProjectionWkid));
                return(esriMapPoint);
            }
            else
            {
                if (mapLocation.ProjectionWkid != CoordinateSystems.Wgs84ProjectionWkid)
                {
                    throw new NotSupportedException(
                              String.Format(
                                  "The WKID {0} is not supported.\nThe only supported coordinate systemas are WebMercator(102100) and WGS84 (4326))",
                                  mapLocation.ProjectionWkid));
                }

                var esriMapPoint = new MapPoint(mapLocation.Longitude, mapLocation.Latitude, new SpatialReference(CoordinateSystems.Wgs84ProjectionWkid));
                // Project from WGS84 to WebMercator
                var reprojMapPoint = new WebMercator().FromGeographic(esriMapPoint) as MapPoint;
                return(reprojMapPoint);
            }
        }
Ejemplo n.º 35
0
        public static MapPoint ToEsriWebMercatorMapPoint(this MapCoord mapLocation)
        {
            if (mapLocation.ProjectionWkid == CoordinateSystems.WebMercatorProjectionWkid)
            {
                var esriMapPoint = new MapPoint(mapLocation.Longitude, mapLocation.Latitude, new SpatialReference(CoordinateSystems.WebMercatorProjectionWkid));
                return esriMapPoint;
            }
            else
            {
                if (mapLocation.ProjectionWkid != CoordinateSystems.Wgs84ProjectionWkid)
                {
                    throw new NotSupportedException(
                        String.Format(
                            "The WKID {0} is not supported.\nThe only supported coordinate systemas are WebMercator(102100) and WGS84 (4326))",
                           mapLocation.ProjectionWkid));
                }

                var esriMapPoint = new MapPoint(mapLocation.Longitude, mapLocation.Latitude, new SpatialReference(CoordinateSystems.Wgs84ProjectionWkid));
                // Project from WGS84 to WebMercator
                var reprojMapPoint = new WebMercator().FromGeographic(esriMapPoint) as MapPoint;
                return reprojMapPoint;
            }
        }
Ejemplo n.º 36
0
        public void RemoveMapConstraint()
        {
            var wm = new WebMercator();
            var tl = new MapPoint(-280, -79, new SpatialReference(4326));
            var br = new MapPoint(280, 79, new SpatialReference(4326));
            var convertedtl = (MapPoint)wm.FromGeographic(tl);
            var convertedbr = (MapPoint)wm.FromGeographic(br);
            var e = new Envelope(convertedtl, convertedbr);

            Execute.OnUIThread(() =>
            {
                var b = System.Windows.Interactivity.Interaction.GetBehaviors(AppState.ViewDef.MapControl);
                var rems = b.OfType<ConstrainExtentBehavior>().ToList();

                foreach (var rem in rems)
                    b.Remove(rem);
                b.Add(new ConstrainExtentBehavior() { ConstrainedExtent = e });
                //SetMapMin(0.5);
               // SetMapMax(100);
            });
        }
Ejemplo n.º 37
0
        public void SetMapConstraint(double topleftX = -180, double topleftY = -90,double bottomrightX=180, double bottomrightY=90, bool setExtent=false)
        {
            if (!IsActive()) return;

            var wm = new WebMercator();
            var tl = new MapPoint(topleftX,topleftY,new SpatialReference(4326));
            var br = new MapPoint(bottomrightX, bottomrightY, new SpatialReference(4326));
            var convertedtl = (MapPoint) wm.FromGeographic(tl);
            var convertedbr = (MapPoint)wm.FromGeographic(br);
            var e = new Envelope(convertedtl, convertedbr);

            Execute.OnUIThread(() =>
           {
               var b = System.Windows.Interactivity.Interaction.GetBehaviors(AppState.ViewDef.MapControl);
               var rem = b.OfType<ConstrainExtentBehavior>().FirstOrDefault();
               if (rem != null)
                   rem.ConstrainedExtent = e;
               else
                   b.Add(new ConstrainExtentBehavior() { ConstrainedExtent = e });
               if (setExtent)
                   AppState.ViewDef.MapControl.Extent = e;
           });
            
        }
Ejemplo n.º 38
0
        private void MyDrawObjectDrawComplete(object sender, DrawEventArgs e)
        {
            AppState.TriggerDeleteNotification(drawingNotification);
            Draw.IsEnabled = false;

            var wm = new WebMercator();
            PoI newPoi = selectedPoiType.GetInstance();
            newPoi.Points = new ObservableCollection<Point>();
            newPoi.Style = new PoIStyle {StrokeColor = lineColor.Color, StrokeWidth = 3, CanDelete = true};
            //Logger.Stat("Drawing.Completed." + ((Custom) ? "Custom." + e.DrawMode : "Template." + ActiveMode.Name));
            switch (e.DrawMode)
            {
                case DrawMode.Freehand:
                case DrawMode.Polyline:
                    newPoi.DrawingMode = DrawingModes.Polyline;

                    //var polygon = e.Geometry is Polygon
                    //                      ? e.Geometry as Polygon
                    //                      : new Polygon();
                    if (e.Geometry is Polyline)
                    {
                        var source = e.Geometry as Polyline;
                        foreach (PointCollection path in source.Paths)
                        {
                            foreach (MapPoint po in path)
                            {
                                var r = wm.ToGeographic(po) as MapPoint;
                                if (r == null) continue;
                                newPoi.Points.Add(new Point(r.X, r.Y));
                                newPoi.Position = new Position(r.X, r.Y);
                            }
                        }
                    }
                    newPoi.UpdateEffectiveStyle();
                    SketchService.PoIs.Add(newPoi);
                    break;
                case DrawMode.Circle:
                case DrawMode.Polygon:
                    if (e.Geometry is Polygon)
                    {
                        var source = e.Geometry as Polygon;
                        foreach (var path in source.Rings)
                        {
                            foreach (var r in path.Select(wm.ToGeographic).OfType<MapPoint>())
                            {
                                newPoi.Points.Add(new Point(r.X, r.Y));
                                newPoi.Position = new Position(r.X, r.Y);
                            }
                        }
                    }
                    newPoi.UpdateEffectiveStyle();
                    SketchService.PoIs.Add(newPoi);
                    break;
            }
            selectedPoiType = null;
            DisableSelections();
            //UpdateMenu();
            //ActiveLayer.Graphics.Add(g);
        }
Ejemplo n.º 39
0
        public string GetWindDirection()
        {
            var w = new WebMercator();
            var p1 = w.ToGeographic(Start.Mp) as MapPoint;
            var p2 = w.ToGeographic(Finish.Mp) as MapPoint;
            var angle = GetAngle(p1, p2);

            if (angle < 22.5) return "E";
            if (angle < 67.5) return "NE";
            if (angle < 112.5) return "N";
            if (angle < 157.5) return "NW";
            if (angle < 202.5) return "W";
            if (angle < 247.5) return "SW";
            if (angle < 292.5) return "S";
            if (angle < 337.5) return "SE";
            return "E";
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Do the photo search. Show the results on the map using pushpin. Set up the photoInfos object
        /// so that we know the photo URL and its location when we want to show it
        /// </summary>
        private void SearchFlikr_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                pushpinsLayer.Graphics.Clear();

                //Add a tag to the search options
                searchOps.Tags = SeletcedTag;

                //Add the current extent to the search options
                //FlickrManager only takes latitude and longitude. We might need to transform the extent
                bool        isGeographic = _mapWidget.Map.SpatialReference.WKID == 4326;
                WebMercator wm           = new WebMercator();
                Envelope    extent       = _mapWidget.Map.Extent;
                if (!isGeographic)
                {
                    Envelope extentToGeo = wm.ToGeographic(extent) as Envelope;
                    searchOps.BoundaryBox = new BoundaryBox(extentToGeo.XMin, extentToGeo.YMin, extentToGeo.XMax, extentToGeo.YMax);
                }
                else
                {
                    searchOps.BoundaryBox = new BoundaryBox(extent.XMin, extent.YMin, extent.XMax, extent.YMax);
                }

                //Do the search asynchronously
                flickr.PhotosSearchAsync(searchOps, (FlickrResult <PhotoCollection> photoColResult) =>
                {
                    //Searh is finished. Manipulate the search results here
                    if (photoColResult.Error != null)
                    {
                        throw new Exception("Error in search results");
                    }

                    PhotoCollection photoCol           = photoColResult.Result;
                    List <FlickrNet.Photo> pCollPublic = photoCol.Where(p => p.IsPublic && !string.IsNullOrEmpty(p.LargeUrl)).ToList();
                    if (pCollPublic.Count == 0)
                    {
                        MessageBox.Show("No photos were found");
                        return;
                    }
                    foreach (FlickrNet.Photo photo in pCollPublic)
                    {
                        //Show a pushpin at the location of the photo. Transformation might be required depending on the map spatial reference
                        MapPoint photoLocation;
                        if (!isGeographic)
                        {
                            photoLocation = wm.FromGeographic(new MapPoint(photo.Longitude, photo.Latitude)) as MapPoint;
                        }
                        else
                        {
                            photoLocation = new MapPoint(photo.Longitude, photo.Latitude);
                        }

                        //Create the pushpin graphic with a symbol and the photo location
                        client.Graphic pushpin = new client.Graphic()
                        {
                            Symbol   = FlickrPushpinSymbol.CreatePushpinSymbol(),
                            Geometry = photoLocation
                        };

                        //Add the graphic to the layer
                        pushpinsLayer.Graphics.Add(pushpin);

                        //Add the photo info to the photoInfos list
                        //To avoid copy right infringement, we only pass the placeholder image's path instead of the photo's actual URL to PhotoInfo
                        photoInfos.Add(new PhotoInfo(@"pack://application:,,,/OperationsDashboardAddIns;component/Images/PhotoPlaceHolder.png", photoLocation));
                    }
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error searching for photos. " + ex.Message);
            }
        }
Ejemplo n.º 41
0
        void locatorTask_AddressToLocationsCompleted(object sender, AddressToLocationsEventArgs e)
        {
            try
            {
                locatorTask.AddressToLocationsCompleted -=
                locatorTask_AddressToLocationsCompleted;
                IList<GeoLocatorDetail> result = new List<GeoLocatorDetail>();
                WebMercator webMercator = new WebMercator();
                if (e.Results.Count > 0)
                {
                    foreach (var item in e.Results)
                    {
                        result.Add(new GeoLocatorDetail()
                        {
                            Location = webMercator.FromGeographic(item.Location) as MapPoint,
                            Match = System.Convert.ToDouble(item.Score),
                            Title = item.Address
                        });
                    }
                }
                else
                {
                }
                ResultsGeoLocatorEventArgs resultEventArgs = new ResultsGeoLocatorEventArgs(result);
                OnGeoLocatorSearchComplete(resultEventArgs);

            }
            catch (Exception ex)
            {
                messageBoxCustom.Show(String.Format("locatorTask_AddressToLocationsCompleted /{0}", ex.Message),
                    GisTexts.SevereError,
                    MessageBoxCustomEnum.MessageBoxButtonCustom.Ok);
            }
        }
        // Raised when a property of the map changes.  Used to check whether map units have changed.
        private void Map_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            Map map = ((Map)sender);

            if (map.SpatialReference.WKID != _spatialRefWKID)
            {
                _gotMapUnits = false;
                _spatialRefWKID = map.SpatialReference.WKID;

                // Spatial reference has changed, so determine map units
                if (map.Layers.Count > 0)
                {
                    map.GetMapUnitsAsync(OnGetMapUnitsCompleted, OnGetMapUnitsFailed);
                }
                else
                {
                    NotifyCollectionChangedEventHandler collectionChanged = null;
                    collectionChanged = (o, args) =>
                    {
                        if (map.Layers.Count > 0)
                        {
                            map.Layers.CollectionChanged -= collectionChanged;
                            map.GetMapUnitsAsync(OnGetMapUnitsCompleted, OnGetMapUnitsFailed);
                        }
                    };
                    map.Layers.CollectionChanged += collectionChanged;
                }

                // handle case where map's spatial reference has changed while there are results.  Projection
                // of results will need to be changed to match that of the map.
                if (_results.Count > 0)                
                {
                    SpatialReference oldSRef = new SpatialReference(_spatialRefWKID);
                    if (oldSRef.IsWebMercator() && map.SpatialReference.IsGeographic())
                    {
                        // Transform result extents from Web Mercator to Geographic WGS 84
                        WebMercator mercator = new WebMercator();
                        foreach (LocatorResultViewModel result in _results)
                        {
                            result.Extent = (Envelope)mercator.ToGeographic(result.Extent);
                            AddressCandidate oldCandidate = result.Candidate;
                            MapPoint newLocation = (MapPoint)mercator.ToGeographic(result.Candidate.Location);
                            result.Candidate = new AddressCandidate(oldCandidate.Address, newLocation,
                                oldCandidate.Score, oldCandidate.Attributes);
                        }
                    }
                    else if (oldSRef.IsGeographic() && map.SpatialReference.IsWebMercator())
                    {
                        // Transform result exstents from Geographic WGS 84 to Web Mercator
                        WebMercator mercator = new WebMercator();
                        foreach (LocatorResultViewModel result in _results)
                        {
                            result.Extent = (Envelope)mercator.FromGeographic(result.Extent);
                            AddressCandidate oldCandidate = result.Candidate;
                            MapPoint newLocation = (MapPoint)mercator.FromGeographic(result.Candidate.Location);
                            result.Candidate = new AddressCandidate(oldCandidate.Address, newLocation,
                                oldCandidate.Score, oldCandidate.Attributes);
                        }
                    }
                    else if (!string.IsNullOrEmpty(GeometryServiceUrl))
                    {
                        // Use a geometry service to project the result extents                        

                        List<LocatorResultViewModel> resultsToProject = new List<LocatorResultViewModel>();
                        List<Graphic> extentsToProject = new List<Graphic>();
                        List<Graphic> locationsToProject = new List<Graphic>();
                        foreach (LocatorResultViewModel result in _results)
                        {
                            // Copy the results to a new collection (list) - necessary because the results
                            // could change during the project operation, so maintaining these in a separate
                            // collection ensures that the updated extents are applied to the proper results
                            resultsToProject.Add(result);
                            // Get the geometries to project.  Both extent and candidate location must be re-projected.
                            extentsToProject.Add(new Graphic() { Geometry = result.Extent });
                            locationsToProject.Add(new Graphic() { Geometry = result.Candidate.Location });
                        }

                        GeometryService geomService = new GeometryService(GeometryServiceUrl);
                        GeometryService geomService2 = new GeometryService(GeometryServiceUrl);
                        EventHandler<GraphicsEventArgs> projectExtentsCompleted = null;
                        EventHandler<GraphicsEventArgs> projectLocationsCompleted = null;
                        EventHandler<TaskFailedEventArgs> projectFailed = null;

                        // Update the result extents when the projection completes
                        projectExtentsCompleted = (o, args) =>
                        {
                            geomService.ProjectCompleted -= projectExtentsCompleted;
                            geomService.Failed -= projectFailed;

                            int count = args.Results.Count;
                            for (int i = 0; i < count; i++)
                                resultsToProject[i].Extent = (Envelope)args.Results[i].Geometry;
                        };

                        // Update the result locations when the projection completes
                        projectLocationsCompleted = (o, args) =>
                        {
                            geomService2.ProjectCompleted -= projectLocationsCompleted;
                            geomService2.Failed -= projectFailed;

                            int count = args.Results.Count;
                            LocatorResultViewModel result = null;
                            for (int i = 0; i < count; i++)
                            {
                                result = resultsToProject[i];
                                AddressCandidate oldCandidate = result.Candidate;
                                MapPoint newLocation = (MapPoint)args.Results[i].Geometry;
                                result.Candidate = new AddressCandidate(oldCandidate.Address, newLocation,
                                    oldCandidate.Score, oldCandidate.Attributes);
                            }
                        };

                        // Just clear the results and remove handlers if the projection fails
                        projectFailed = (o, args) =>
                        {
                            geomService.ProjectCompleted -= projectExtentsCompleted;
                            geomService.Failed -= projectFailed;

                            geomService2.ProjectCompleted -= projectLocationsCompleted;
                            geomService2.Failed -= projectFailed;

                            _results.Clear();
                        };

                        geomService.ProjectCompleted += projectExtentsCompleted;
                        geomService.Failed += projectFailed;

                        geomService2.ProjectCompleted += projectLocationsCompleted;
                        geomService2.Failed += projectFailed;

                        geomService.ProjectAsync(extentsToProject, map.SpatialReference);
                        geomService2.ProjectAsync(locationsToProject, map.SpatialReference);
                    }
                }
            }
        }
Ejemplo n.º 43
0
        public void Find(GeoCodeSearchResult item)
        {
            //var c = new Point(item.Location.Longitude, item.Location.Latitude);
            //double dis = Distance(item.Box.North, item.Box.East, item.Box.North, itemwm.Box.West, 'K');
            var wm = new WebMercator();

            var e = (Envelope) wm.FromGeographic(new Envelope(item.Box.West, item.Box.North, item.Box.East, item.Box.South));
            //var e = new Envelope(item.Box.West, item.Box.North, item.Box.East, item.Box.South);
            //e.SpatialReference = new SpatialReference(4326);

            AppState.ViewDef.NextEffect = true;
            AppState.ViewDef.MapControl.Extent = e;
            SelectedLocation = item.Name;
            //AppState.ViewDef.ZoomTo(new KmlPoint(c.X, c.Y), dis*1000);
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Zoom to extent
        /// </summary>
        /// <param name="xmin"></param>
        /// <param name="ymin"></param>
        /// <param name="xmax"></param>
        /// <param name="ymax"></param>
        public void ZoomTo(double xmin, double ymin, double xmax, double ymax, int animTime = 1000, bool effect = false, bool webMercator = false)
        {
            if (!IsActive()) return;

            var e = new Envelope(new MapPoint(xmin, ymin), new MapPoint(xmax, ymax));
            if (webMercator)
            {
                var wm = new WebMercator();
                var tl = new MapPoint(xmin, ymin, new SpatialReference(4326));
                var br = new MapPoint(xmax, ymax, new SpatialReference(4326));
                var convertedtl = (MapPoint) wm.FromGeographic(tl);
                var convertedbr = (MapPoint) wm.FromGeographic(br);
                e = new Envelope(convertedtl, convertedbr);
                //                                       DemoScript.ZoomTo(-19913273.2361002, -16885380.7637054, 20161743.4494782,
                //                                                         15174632.5847574, effect: true);
            }


            // TODO animate zoom to next place
            Execute.OnUIThread(() =>
            {
                try
                {
                    var b = System.Windows.Interactivity.Interaction.GetBehaviors(AppState.ViewDef.MapControl);
                    var rems = b.OfType<ConstrainExtentBehavior>().ToList();

                    foreach (var rem in rems)
                        b.Remove(rem);

                    if (effect) 
                        {AppState.ViewDef.StartTransition();}
                    else
                    {
                        AppState.ViewDef.MapControl.ZoomDuration = new TimeSpan(0, 0, 0, 0,250);
                        //AppState.ViewDef.MapControl.PanDuration = new TimeSpan(0, 0, 0, 0, animTime);    
                    }
                    AppState.ViewDef.MapControl.MinimumResolution = 0.1;
                    AppState.ViewDef.MapControl.MaximumResolution = 1000000;

                    AppState.TriggerScriptCommand(null,"disableextentchanged");
                    AppState.ViewDef.MapControl.ZoomTo(e);
                    AppState.TriggerScriptCommand(null, "enableextentchanged");
                }
                catch
                {
                }
            });
        }
Ejemplo n.º 45
0
 private void s_PingReceived(Service s, BaseContent b)
 {
     var wm = new WebMercator();
     var pos = (MapPoint)wm.FromGeographic(new MapPoint(b.Position.Longitude, b.Position.Latitude));
     var pcov = new PingCallOutViewModel { Ping = b };
     var callOut = new MapCallOutViewModel
     {
         Width = 250,
         TimeOut = new TimeSpan(0, 0, 0, 5),
         CanClose = false,
         ForegroundBrush = Brushes.White,
         BackgroundBrush = Brushes.Red,
         ViewModel = pcov,
         Point = pos
     };
     AppState.Popups.Add(callOut);
     //AppState.TriggerNotification();
     AppState.ViewDef.ZoomAndPoint(new Point(b.Position.Longitude, b.Position.Latitude));
 }
Ejemplo n.º 46
0
        private void UpdateModelShape()
        {
            var rdCenter = new MapPoint(5.387206, 52.155174);
//            var rdCenter = new MapPoint(155000,  463000);
            var start = new WebMercator().ToGeographic(Start.Mp) as MapPoint;
//            rdCenter = new WebMercator().FromGeographic(rdCenter) as MapPoint;

            var srcSr = new SpatialReference(28992);
            var targetSr = new SpatialReference(4326);
            var src = ProjectionInfo.FromEpsgCode(srcSr.WKID);
            var dest = ProjectionInfo.FromEpsgCode(targetSr.WKID);
            var radAngle = (float)(GetAngle(Start.Mp, Finish.Mp) * (Math.PI / 180f));
            
            foreach (var graphic in EffectsModelShapes)
            {
                graphic.SetZIndex(0);
                var baseGraphic = graphic.Attributes["base"] as Graphic;
                var basePoly = baseGraphic.Geometry as Polygon;
                var clone = basePoly.Clone();
                clone.SpatialReference = targetSr;

                List<PointCollection> newRings = new List<PointCollection>();
                foreach (var linestring in clone.Rings)
                {

                    foreach (var point in linestring)
                    {
//                        RotatePoint(point, rdCenter, radAngle);
                        RotatePoint(point, new MapPoint(0,0), radAngle);
                    }

                    var projectedPoints = linestring.SelectMany(c => new double[2] { c.X + 155000, c.Y + 463000 }).ToArray();
                    Reproject.ReprojectPoints(projectedPoints, null, src, dest, 0, projectedPoints.Length / 2);
                    var projectedLineString = new PointCollection(Enumerable.Range(0, projectedPoints.Length / 2).Select(i => new MapPoint(projectedPoints[i * 2], projectedPoints[(i * 2) + 1] , targetSr)));
                    newRings.Add(projectedLineString);
                }
                clone.Rings = new ObservableCollection<PointCollection>(newRings);

                clone.Offset(start.X - rdCenter.X, start.Y - rdCenter.Y);

                graphic.Geometry = clone;
            }
        }
Ejemplo n.º 47
0
        //public string BaseUrl = "http://cool2.sensorlab.tno.nl:8000/BuienRadarService/RainImage/eu/warped/";
        //public string BaseUrl = "http://cool2.sensorlab.tno.nl:8000/BuienRadarService/RainImage/nl/warped/";
        //public string BaseUrl = "http://*****:*****@"Weather/Rain");
            var w = new WebMercator();
            //Buienradar
            var wi = new RainRadarLayer {ID = Name};
            i = new Image {
                IsHitTestVisible = false,
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch
            };
            UpdateImage(AppState.TimelineManager.FocusTime);
            var mpa = new MapPoint(tlLat, tlLon);
            var mpb = new MapPoint(brLat, brLon);
          
            mpa = w.FromGeographic(mpa) as MapPoint;
            mpb = w.FromGeographic(mpb) as MapPoint;
            var envelope = new Envelope(mpa, mpb);
            ElementLayer.SetEnvelope(i, envelope);

            wi.Children.Add(i);
            wi.Initialize();
            wi.Visible = true;
            gl.ChildLayers.Add(wi);

            AppState.TimelineManager.TimeChanged += TimelineManager_TimeChanged;

            AppState.CreateCache += AppState_CreateCache;
        }
Ejemplo n.º 48
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void locatorTask_LocationToAddressCompleted(object sender, AddressEventArgs e)
 {
     try
     {
         locatorTask.LocationToAddressCompleted -= locatorTask_LocationToAddressCompleted;
         Address address = e.Address;
         Dictionary<string, object> attributes = e.Address.Attributes;
         IList<GeoLocatorDetail> result = new List<GeoLocatorDetail>();
         WebMercator webMercator = new WebMercator();
         result.Add(new GeoLocatorDetail()
         {
             Location = address.Location,
             Match = 100.0,
             Title = string.Format("{0} {1},{2}", attributes["Address"], attributes["City"], attributes["Postcode"]),
             Attributes = attributes
         });
         ResultsGeoLocatorEventArgs resultEventArgs = new ResultsGeoLocatorEventArgs(result);
         OnGeoLocatorSearchComplete(resultEventArgs);
     }
     catch (Exception ex)
     {
         messageBoxCustom.Show(String.Format("locatorTask_LocationToAddressCompleted /{0}", ex.Message),
             GisTexts.SevereError,
             MessageBoxCustomEnum.MessageBoxButtonCustom.Ok);
     }
 }
        protected async override void OnAttached()
        {
            try
            {
                base.OnAttached();

                // Verify that the behavior is attached to a map with a valid WKID and that a
                // query string is present
                if (AssociatedObject != null &&
                    AssociatedObject.SpatialReference != null &&
                    AssociatedObject.SpatialReference.WKID > 0 &&
                    HtmlPage.Document != null &&
                    HtmlPage.Document.QueryString != null)
                {
                    // Put query string values in a case-insensitive dictionary
                    var queryString = new Dictionary <string, string>(HtmlPage.Document.QueryString, StringComparer.InvariantCultureIgnoreCase);

                    // Check whether query string contains center
                    if (queryString.ContainsKey("center"))
                    {
                        // get the center string
                        string centerString = queryString["center"];

                        // get the list delimiter for the current culture (making sure to account for cultures that use delimiters other than comma)
                        char listDelimiter = CultureInfo.CurrentCulture.TextInfo.ListSeparator[0];

                        // Split extent string into discrete values
                        string[] centerPointVals = centerString.Split(listDelimiter);
                        double   x, y;

                        // Verify that the expected number of values are present, that they are numeric, and convert the values to doubles
                        IFormatProvider numericFormat = CultureInfo.CurrentCulture.NumberFormat;
                        if ((centerPointVals.Length == 2 || centerPointVals.Length == 3) &&
                            double.TryParse(centerPointVals[0], NumberStyles.Number, numericFormat, out x) &&
                            double.TryParse(centerPointVals[1], NumberStyles.Number, numericFormat, out y))
                        {
                            // get WKID from the map attached to the behavior
                            int currentWkid     = AssociatedObject.Extent.SpatialReference.WKID;
                            int queryStringWkid = currentWkid;

                            // Check whether a WKID was specified (will be the 3rd parameter if present) and grab it if so
                            if (centerPointVals.Length == 3 && !int.TryParse(centerPointVals[2], out queryStringWkid))
                            {
                                // invalid WKID specified, fire InitializationFailed and exit
                                OnInitializationFailed(new Exception(Strings.InvalidWkid));
                                return;
                            }

                            // Initialize a point with the same spatial reference as the attached map
                            MapPoint queryStringPoint = new MapPoint(x, y)
                            {
                                SpatialReference = new SpatialReference(queryStringWkid)
                            };

                            // check whether the specified WKID is different than that of the attached map, meaning the point needs to be projected
                            if (queryStringWkid != currentWkid)
                            {
                                WebMercator wm = new WebMercator();

                                // Use convenience methods to convert between WGS 84 and Web Mercator if possible
                                if (isWebMercator(queryStringWkid) && isWgs84(currentWkid))
                                {
                                    queryStringPoint = (MapPoint)wm.ToGeographic(queryStringPoint);
                                }
                                else if (isWgs84(queryStringWkid) && isWgs84(currentWkid))
                                {
                                    queryStringPoint = (MapPoint)wm.FromGeographic(queryStringPoint);
                                }
                                else if (!string.IsNullOrEmpty(MapApplication.Current.Urls.GeometryServiceUrl))
                                {
                                    // Conversion is not between WGS 84 and Web Mercator, so a call to a geometry service is necessary to perform
                                    // the projection
                                    try
                                    {
                                        GeometryService gs = new GeometryService(MapApplication.Current.Urls.GeometryServiceUrl);
                                        var             g  = new Graphic()
                                        {
                                            Geometry = queryStringPoint
                                        };
                                        var sr     = new SpatialReference(currentWkid);
                                        var result = await gs.ProjectTaskAsync(new Graphic[] { g }, sr);

                                        queryStringPoint = (MapPoint)result.Results[0].Geometry;
                                    }
                                    catch (Exception ex)
                                    {
                                        // Projection failed.  Fire InitializationFailed event and return.
                                        OnInitializationFailed(ex);
                                        return;
                                    }
                                }
                            }

                            var panDuration = AssociatedObject.PanDuration;
                            AssociatedObject.PanDuration = TimeSpan.FromSeconds(0);
                            AssociatedObject.PanTo(queryStringPoint);
                            AssociatedObject.PanDuration = panDuration;
                        }
                    }
                }

                // Fire Initialized event
                OnInitialized();
            }
            catch (Exception ex)
            {
                // Raise InitializationFailed event
                OnInitializationFailed(ex);
            }
        }
Ejemplo n.º 50
0
        public static Geometry ProjectGeometryToMap(Geometry geometry, Map map)
        {
            if (geometry == null || map == null)
            return geometry;

              if (geometry.SpatialReference.WKID == map.SpatialReference.WKID)
            return geometry;

              WebMercator webMercator = new WebMercator();

              // convert from WGS84 to Web-Mercator
              if (IsWGS84SR(geometry.SpatialReference) && IsWebMercatorSR(map.SpatialReference))
            return webMercator.FromGeographic(geometry);

              // convert from Web-Mercator to WGS84
              if (IsWebMercatorSR(geometry.SpatialReference) && IsWGS84SR(map.SpatialReference))
            return webMercator.ToGeographic(geometry);

              // not supported SRs - return the non projected geometry
              return geometry;
        }
        private void handleGeographicResults(List<LocatorResultViewModel> results)
        {
            WebMercator mercator = new WebMercator();
            MapPoint extentCenter = null;
            double extentHeight = _extentWidthInMapUnits / 3;

            if (results[0].Candidate.Location.SpatialReference.IsGeographic())
            {
                foreach (LocatorResultViewModel result in results)
                {
                    extentCenter = (MapPoint)mercator.FromGeographic(result.Candidate.Location);
                    Envelope extentInMeters = extentCenter.ToEnvelope(_extentWidthInMapUnits, extentHeight);
                    result.Extent = (Envelope)mercator.ToGeographic(extentInMeters);
                    _results.Add(result);
                }

                // Refresh paged collection to update pagination
                PagedResults.Refresh();

                IsSearching = false; // Reset busy state
                OnSearchCompleted(); // Raise completed event
            }
            else if (!string.IsNullOrEmpty(GeometryServiceUrl))
            {
                GeometryService geomService = new GeometryService(GeometryServiceUrl);
                List<Graphic> graphicsToProject = new List<Graphic>();
                foreach (LocatorResultViewModel result in results)
                    graphicsToProject.Add(new Graphic() { Geometry = result.Candidate.Location });

                EventHandler<GraphicsEventArgs> projectCompleted = null;
                EventHandler<TaskFailedEventArgs> projectFailed = null;
                projectCompleted = (o, e) =>
                {
                    geomService.ProjectCompleted -= projectCompleted;
                    graphicsToProject.Clear();

                    foreach (Graphic g in e.Results)
                    {
                        extentCenter = (MapPoint)g.Geometry;
                        Envelope extentInMeters = extentCenter.ToEnvelope(_extentWidthInMapUnits, extentHeight);
                        graphicsToProject.Add(new Graphic() { Geometry = extentInMeters });
                    }

                    projectCompleted = (s, a) =>
                    {
                        geomService.ProjectCompleted -= projectCompleted;
                        geomService.Failed -= projectFailed;

                        for (int i = 0; i < a.Results.Count; i++)
                        {
                            LocatorResultViewModel result = results[i];
                            result.Extent = (Envelope)a.Results[i].Geometry;
                            _results.Add(result);
                        }

                        // Refresh paged collection to update pagination
                        PagedResults.Refresh();

                        IsSearching = false; // Reset busy state
                        OnSearchCompleted(); // Raise completed event
                    };

                    geomService.ProjectCompleted += projectCompleted;

                    // Project extents into map spatial reference
                    geomService.ProjectAsync(graphicsToProject, _map.SpatialReference);
                };

                projectFailed = (o, e) =>
                {
                    geomService.ProjectCompleted -= projectCompleted;
                    geomService.Failed -= projectFailed;

                    // Refresh paged collection to update pagination
                    PagedResults.Refresh();

                    IsSearching = false; // Reset busy state
                    OnSearchCompleted(); // Raise completed event
                };

                geomService.ProjectCompleted += projectCompleted;
                geomService.Failed += projectFailed;

                // Project result locations to web mercator
                geomService.ProjectAsync(graphicsToProject, new SpatialReference(3857));
            }
        }
Ejemplo n.º 52
0
        public static Geometry ProjectGeometryToGeographic(Geometry geometry)
        {
            if (IsWGS84SR(geometry.SpatialReference))
            return geometry;

              WebMercator webMercator = new WebMercator();

              // convert from Web-Mercator to WGS84
              return webMercator.ToGeographic(geometry);
        }
Ejemplo n.º 53
0
        internal void UpdateLine(GoogleDirections gd)
        {
            Execute.OnUIThread(() =>
            {
                var m = new WebMercator();

                var ps = DecodeLatLong(gd.Directions.Polyline.points);

                var pl = new ESRI.ArcGIS.Client.Geometry.Polyline {Paths = new ObservableCollection<PointCollection>()};
                var pc = new PointCollection();
                foreach (var p in ps)
                {
                    pc.Add((MapPoint) m.FromGeographic(new MapPoint(p.Longitude, p.Latitude)));
                }

                pl.Paths.Add(pc);
                _line.Geometry = pl;
                _line.SetZIndex(0);
            });
        }
Ejemplo n.º 54
0
        //private bool _fullLayer = false;

        private void UpdateLayer()
        {
            
            fi = new FileInfo(LayerFile);

            ImageSource ims = null;
            var defaultImage = fi.Directory + @"\_" + fi.Name.Substring(0,fi.Name.Length-4) + ".png";
            if (!File.Exists(defaultImage)) {
                defaultImage = "";
            }
            else {
                ims = new BitmapImage(new Uri(defaultImage));
            }

            double iconsize = 30;
            el.Children.Clear();

            Explorer.HasFullLayer = false;
            foreach (var a in File.ReadAllLines(LayerFile))
            {
                if (a.StartsWith("~"))
                {
                    var s = a.Remove(0, 1);
                    var ss = s.Split(',');
                    if (ss.Length <= 0) continue;
                    switch (ss[0])
                    {
                        case "iconsize":
                            iconsize = Convert.ToDouble(ss[1]);
                            break;
                        case "fulllayer":
                            try {                                    
                                Explorer.HasFullLayer = true;
                                var image = ss[1];
                                var width = Convert.ToDouble(ss[2], CultureInfo.InvariantCulture);
                                var height = Convert.ToDouble(ss[3], CultureInfo.InvariantCulture);

                                var u = new Uri(fi.Directory + "/" + image);
                                var i = new Image {
                                    Source = new BitmapImage(u),
                                    Width = double.NaN,
                                    Height = double.NaN,
                                    HorizontalAlignment = HorizontalAlignment.Stretch,
                                    VerticalAlignment = VerticalAlignment.Stretch,
                                    Stretch = Stretch.Fill
                                };
                                el.Children.Add(i);

                                var w = new WebMercator();
                                var mpa = w.FromGeographic(new MapPoint(0, 0, new SpatialReference(4326))) as MapPoint;
                                var mpb = w.FromGeographic(new MapPoint(width, height, new SpatialReference(4326))) as MapPoint;
                                envelope = new Envelope(mpa, mpb);
                                ElementLayer.SetEnvelope(i, envelope);

                                //this.ChildLayers.Add(el);

                                i.MouseDown += i_PreviewMouseDown;
                                i.PreviewMouseWheel += i_PreviewMouseWheel;
                                i.PreviewTouchDown += i_PreviewTouchDown;
                                el.Initialize();
                                AppStateSettings.Instance.ViewDef.MapControl.Extent = envelope;
                                //AppStateSettings.Instance.ViewDef.CanMove = false;
                                AppStateSettings.Instance.ViewDef.BaseLayer.Opacity = 0;
                                break;
                            }
                            catch (SystemException e) {
                                break;
                            }
                    }
                }
                else
                {
                    try {
                        var l1 = a.IndexOf(',');
                        var lon = Convert.ToDouble(a.Substring(0, l1), CultureInfo.InvariantCulture);
                        var l2 = a.IndexOf(',', l1 + 1);
                        var lat = Convert.ToDouble(a.Substring(l1 + 1, l2 - l1 - 1), CultureInfo.InvariantCulture);
                        var l3 = a.IndexOf(',', l2 + 1);
                        var path = a.Substring(l2 + 1, l3 - l2 - 1);
                        //var l4 = a.IndexOf(',', l3 + 1);
                        //var image = a.Substring(l3 + 1, l4 - l3 - 1);
                        //if (string.IsNullOrEmpty(image)) image = defaultImage;

                        var title = a.Substring(l3 + 1).Trim('"');

                        path = fi.Directory.FullName + @"\" + path;

                        var g = new Graphic();
                        g.Attributes["id"]        = title;
                        g.Attributes["path"]      = path;
                        g.Attributes["size"]      = iconsize;
                        g.Attributes["explorer"]  = Explorer;
                        g.Attributes["image"]     = ims;
                        g.Attributes["fulllayer"] = Explorer.HasFullLayer;

                        var mp = new MapPoint(lon, lat);
                        g.Geometry = _mercator.FromGeographic(mp);

                        //g.Symbol = new PictureMarkerSymbol() { Source = ims, Width = iconsize, Height = iconsize, OffsetX = iconsize / 2, OffsetY = iconsize/2 };
                        var pd = new ResourceDictionary { Source = new Uri("/csCommon;component/Resources/Styles/PresenterDictionary.xaml", UriKind.Relative) };
                        g.Symbol = pd["FeatureSymbol"] as MarkerSymbol;

                        //g.MouseLeftButtonDown += (e, s) =>
                        //{
                        //    //Explorer.SelectFolder(path);
                        //    //s.Handled = true;
                        //};

                        Graphics.Graphics.Add(g);
                    }
                    catch {}
                }
            }
        }
Ejemplo n.º 55
0
        public void GoTo(Bookmark bm)
        {
            try
            {
                var mvd = AppStateSettings.Instance.ViewDef;
                mvd.StartTransition();
                //mvd.ZoomTo(new KmlPoint(bm.Location.X, bm.Location.Y), bm.Resolution);
                //mvd.MapControl.Extent = bm.Extent;
                //mvd.MapControl.ZoomDuration = new TimeSpan(0,0,0,0,500);

                switch (bm.Extent.SpatialReference.WKID)
                {
                    case 4326:
                    {
                        var wm = new WebMercator();
                        var extent = (Envelope) wm.FromGeographic(bm.Extent);
                        mvd.MapControl.ZoomTo(extent);
                        break;
                    }
                    case 102100:
                        mvd.MapControl.ZoomTo(bm.Extent);
                        break;
                }
                Logger.Stat("BookmarkSelected");
            }
            catch
            {

            }
        }
Ejemplo n.º 56
0
        public void Send3DMessage()
        {
            var wm = new WebMercator();
            var p = new Pos3D();
            var mpC = (MapPoint)wm.ToGeographic(finishPoint.Mp);
            var mpD = (MapPoint)wm.ToGeographic(startPoint.Mp);
            if (AutoHeight)
            {
                var d = SphericalMercator.Distance(mpC.Y, mpC.X, mpD.Y, mpD.X, 'K') * 100; // distance in km times 10.

                finishPoint.Altitude = 2 + d * d * 0.15;
                //finishPoint.Altitude = Math.Max(res*res*100, 0);
                startPoint.Altitude = 0;
            }

            p.Camera = new Point3D(mpC.X, mpC.Y, finishPoint.Altitude);
            p.Destination = new Point3D(mpD.X, mpD.Y, startPoint.Altitude);
            _lastMes = p.ToString();
        }
Ejemplo n.º 57
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            this.sampleControl1.Center = new double[] { 534463.21f, 6633094.69f };
            //this.sampleControl1.Center = new float[] { 0f, 0f };
            this.sampleControl1.ZoomFactor = 1;

            // initialize a test-scene.
            var scene2D = new Scene2DSimple();

            scene2D.BackColor = Color.White.ToArgb();
            scene2D.AddPoint(float.MinValue, float.MaxValue, 0, 0, Color.Blue.ToArgb(), 1);

            bool fill  = false;
            int  color = Color.White.ToArgb();
            int  width = 1;

            scene2D.AddPolygon(float.MinValue, float.MaxValue,
                               new double[] { 50, -80, 70 }, new double[] { 20, -10, -70 }, color, width, fill);

            // load test osm file.
            Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(
                "OsmSharp.WinForms.UI.Sample.test.osm");
            var xmlDataProcessorSource   = new XmlOsmStreamSource(stream);
            ICollection <OsmGeo> osmList = xmlDataProcessorSource.PullToCollection();

            // build a scene using spherical mercator.
            IProjection sphericalMercator = new WebMercator();
            var         nodes             = new Dictionary <long, GeoCoordinate>();

            foreach (OsmGeo simpleOsmGeo in osmList)
            {
                if (simpleOsmGeo is Node)
                {
                    var      simplenode = (simpleOsmGeo as Node);
                    double[] point      = sphericalMercator.ToPixel(
                        simplenode.Latitude.Value, simplenode.Longitude.Value);
                    nodes.Add(simplenode.Id.Value,
                              new GeoCoordinate(simplenode.Latitude.Value, simplenode.Longitude.Value));
                    scene2D.AddPoint(float.MinValue, float.MaxValue, (float)point[0], (float)point[1],
                                     Color.Yellow.ToArgb(),
                                     2);
                }
                else if (simpleOsmGeo is Way)
                {
                    var way = (simpleOsmGeo as Way);
                    var x   = new List <double>();
                    var y   = new List <double>();
                    if (way.Nodes != null)
                    {
                        for (int idx = 0; idx < way.Nodes.Count; idx++)
                        {
                            GeoCoordinate nodeCoords;
                            if (nodes.TryGetValue(way.Nodes[idx], out nodeCoords))
                            {
                                x.Add((float)sphericalMercator.LongitudeToX(nodeCoords.Longitude));
                                y.Add((float)sphericalMercator.LatitudeToY(nodeCoords.Latitude));
                            }
                        }
                    }

                    if (x.Count > 0)
                    {
                        scene2D.AddLine(float.MinValue, float.MaxValue, x.ToArray(), y.ToArray(),
                                        Color.Blue.ToArgb(), 2);
                    }
                }
            }

            this.sampleControl1.Scene = scene2D;

            this.sampleControl1.Invalidate();
        }
Ejemplo n.º 58
0
 private void TriggerGeoPointer(Point pos)
 {
     var p = AppState.ViewDef.ViewToWorld(pos.X, pos.Y);
     var wm = new WebMercator();
     var p2 = (MapPoint)wm.FromGeographic(new MapPoint(p.Y, p.X));
     AppState.ViewDef.AddGeoPointer(new GeoPointerArgs { Position = p2, Duration = TimeSpan.FromSeconds(2) });
     AppState.Imb.SendMessage(CommandsChannelName, string.Format("point|{0}|{1}|{2}",
         p2.Y.ToString(CultureInfo.InvariantCulture),
         p2.X.ToString(CultureInfo.InvariantCulture),
         AppState.Imb.Imb.ClientHandle));
 }
        public void Scene2DSimpleSerializeDeserializeTest()
        {
            // create the MapCSS image source.
            var imageSource = new MapCSSDictionaryImageSource();

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

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

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

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

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

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

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

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

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

            scene.Serialize(stream, false);

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

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

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

                    //Assert.AreEqual(resultReference.Count, resultIndex.Count);
                    //foreach (var data in resultIndex)
                    //{
                    //    Assert.IsTrue(resultReference.Contains(data));
                    //}
                    //foreach (var data in resultReference)
                    //{
                    //    Assert.IsTrue(resultIndex.Contains(data));
                    //}
                    counter--;
                }
            }
        }
Ejemplo n.º 60
0
 private void StreetViewTap(object sender, RoutedEventArgs e)
 {
     var wm = new WebMercator();
     MapPoint mp = null;
     switch (_state)
     {
         case "start":
             mp = fov.StartPoint.Mp;
             break;
         case "finish":
             mp = fov.FinishPoint.Mp;
             break;
     }
     var m = wm.ToGeographic(mp) as MapPoint;
     var angle = (int)Angle(fov.StartPoint.Mp.X, fov.StartPoint.Mp.Y, fov.FinishPoint.Mp.X, fov.FinishPoint.Mp.Y);
     var l = m.Y.ToString(CultureInfo.InvariantCulture) + "," + m.X.ToString(CultureInfo.InvariantCulture);
     var url = "http://maps.googleapis.com/maps/api/streetview?size=640x480&location=" + l + "&heading=" + angle + "&fov=90&pitch=0&sensor=false";
     var fe = FloatingHelpers.CreateFloatingElement(new Document
     {
         Location = url,
         OriginalUrl = url,
         FileType = FileTypes.image
     });
     AppState.FloatingItems.AddFloatingElement(fe);
 }