Exemple #1
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);
            
            

        }
Exemple #2
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);


        }
        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);
        }
Exemple #4
0
        private void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            int      lat  = random.Next(32, 36);
            int      lng  = random.Next(-116, -114);
            Geometry geom = webmercator.FromGeographic(new MapPoint(lng, lat));

            startAutoPan(geom);
        }
Exemple #5
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);
            }
        }
Exemple #6
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));
 }
        // 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);
                    }
                }
            }
        }
        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);
        }
Exemple #9
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
                {
                }
            });
        }
Exemple #10
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;
           });
            
        }
Exemple #11
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));
 }
Exemple #12
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
                });

            }
        }
Exemple #13
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);
            });
        }
Exemple #14
0
 public bool InsideEnvelope(Envelope env)
 {
     if (AlwaysShow) return true;
     var w = new WebMercator();
     var mCoord = w.FromGeographic(new MapPoint(Longitude, Latitude)) as MapPoint;
     return mCoord != null && mCoord.X > env.XMin && mCoord.X < env.XMax && mCoord.Y > env.YMin && mCoord.Y < env.YMax;
 }
Exemple #15
0
 private void MiZoomTap(object sender, RoutedEventArgs e)
 {
     var wm = new WebMercator();
     AppStateSettings.Instance.ViewDef.MapControl.ZoomDuration = new TimeSpan(0, 0, 0, 1);
     AppStateSettings.Instance.ViewDef.MapControl.ZoomToResolution(1, (MapPoint) wm.FromGeographic(new MapPoint(PoI.Position.Longitude, PoI.Position.Latitude)));
 }
Exemple #16
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);
            }
        }
Exemple #17
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;
        }
 private void StartButtonClicked(object parameters)
 {
     if (!PBS.Util.Utility.IsValidFilename(Output))
     {
         MessageBox.Show(App.Current.FindResource("msgOutputPathError").ToString(), App.Current.FindResource("msgError").ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
         return;
     }
     if (File.Exists(Output))
     {
         if (MessageBox.Show(App.Current.FindResource("msgOverwrite").ToString(), App.Current.FindResource("msgWarning").ToString(), MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
         {
             return;
         }
         else
         {
             try
             {
                 File.Delete(Output);
             }
             catch (Exception e)
             {
                 MessageBox.Show(e.Message, App.Current.FindResource("msgError").ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                 return;
             }
         }
     }
     try
     {
         Datasource = new DataSourceCustomOnlineMaps(SelectedDatasourceType);
         Datasource.ConvertCompleted += (s, a) =>
         {
             if (a.Successful)
             {
                 string str = App.Current.FindResource("msgConvertComplete").ToString();
                 if (DoCompact)
                 {
                     str += "\r\n" + App.Current.FindResource("msgCompactResult").ToString() + (Datasource.ConvertingStatus.SizeBeforeCompact / 1024).ToString("N0") + "KB --> " + (Datasource.ConvertingStatus.SizeAfterCompact / 1024).ToString("N0") + "KB";
                 }
                 MessageBox.Show(str, "", MessageBoxButtons.OK, MessageBoxIcon.Information);
             }
         };
         Datasource.ConvertCancelled += (s, a) =>
         {
             //try
             //{
             //    //aa.mbtiles and aa.mbtiles-journal
             //    if (File.Exists(Output))
             //    {
             //        File.Delete(Output);
             //    }
             //    if (File.Exists(Output + "-journal"))
             //    {
             //        File.Delete(Output + "-journal");
             //    }
             //}
             //catch (Exception e)
             //{
             //    throw new Exception(".mbtiles and .mbtiles-journal files could not be deleted.\r\n" + e.Message);
             //}
         };
         BackgroundWorker bw = new BackgroundWorker();
         bw.DoWork += (s, a) =>
         {
             IsIdle = false;
             App.Current.Dispatcher.Invoke(new Action(() =>
             {
                 (CMDClickStartButton as DelegateCommand).RaiseCanExecuteChanged();
             }));
             Envelope extent = (Envelope)_webMercator.FromGeographic(DownloadExtent);
             try
             {
                 PBS.Util.Geometry g = _downloadPolygon == null ? (PBS.Util.Geometry) new PBS.Util.Envelope(extent.XMin, extent.YMin, extent.XMax, extent.YMax) : _downloadPolygon;
                 if (_downloadPolygon != null)
                 {
                     MessageBox.Show(App.Current.FindResource("msgDownloadByPolygonIntro").ToString(), "", MessageBoxButtons.OK, MessageBoxIcon.Information);
                 }
                 Datasource.ConvertToMBTiles(Output, Name, Description, Attribution, Levels, g, DoCompact);
             }
             catch (Exception e)
             {
                 MessageBox.Show(e.Message, App.Current.FindResource("msgError").ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
             }
             IsIdle = true;
             App.Current.Dispatcher.Invoke(new Action(() =>
             {
                 (CMDClickStartButton as DelegateCommand).RaiseCanExecuteChanged();
             }));
         };
         bw.RunWorkerAsync();
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
     }
 }
Exemple #19
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);
            });
        }
Exemple #20
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
            {

            }
        }
        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);
            }
        }
Exemple #22
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 {}
                }
            }
        }
        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));
            }
        }
        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;
        }
Exemple #25
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);
            }
        }
Exemple #26
0
 private void RouteSolvedComplete(object sender, RouteEventArgs a)
 {
     try
     {
         routeTask.SolveCompleted -= RouteSolvedComplete;
         WebMercator webMercator = new WebMercator();
         RoutingEventArgs routingEvent = new RoutingEventArgs();
         ESRI.ArcGIS.Client.Tasks.RouteResult routeResult = a.RouteResults[0];
         routeResult.Route.Symbol = lineRouteSymbol;
         routingEvent.RoutingResult.RouteGraphic = routeResult.Route;
         SpatialReference initialSpatialReference =
         routingEvent.RoutingResult.RouteGraphic.Geometry.SpatialReference;
         routingEvent.RoutingResult.RouteGraphic.Geometry =
         webMercator.FromGeographic(routeResult.Route.Geometry);
         routingEvent.RoutingResult.RouteName = a.UserState as string;
         routingEvent.RoutingResult.RouteDirections = routeResult.Directions;
         foreach (var item in routingEvent.RoutingResult.RouteDirections)
         {
             item.Geometry.SpatialReference = initialSpatialReference;
             item.Geometry = webMercator.FromGeographic(item.Geometry);
         }
         OnRoutingCalcComplete(routingEvent);
     }
     catch (Exception ex)
     {
         messageBoxCustom.Show(String.Format("RouteSolvedComplete /{0}", ex.Message),
             GisTexts.SevereError,
             MessageBoxCustomEnum.MessageBoxButtonCustom.Ok);
     }
 }