Exemplo n.º 1
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);
        }
Exemplo n.º 2
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));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Prepares a <see cref="ESRI.ArcGIS.Client.Geometry.Polygon"/> instance for
        /// client-side geometric operations
        /// </summary>
        internal static Polygon PrepareForClientOps(this Polygon polygon)
        {
            validateProjectionForClientOps(polygon);

            Euclidian.Densify(polygon, 10000);

            if (polygon.SpatialReference.IsWebMercator())
            {
                polygon = (Polygon)_webMercator.ToGeographic(polygon);
            }

            polygon = (Polygon)Geometry.NormalizeCentralMeridian(polygon);

            return(polygon);
        }
        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);
        }
 void MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
 {
     if (_isRightMouseButtonDown && IsIdle)
     {
         //draw download extent
         Graphic  g        = _graphicsLayer.Graphics[0];
         MapPoint endPoint = _map.ScreenToMap(e.GetPosition(_map));
         g.Geometry = new Envelope(_startPoint.X, endPoint.Y, endPoint.X, _startPoint.Y);
         //tiles count
         if (Levels != null && Levels.Length > 0)
         {
             TilesCount = AppUtility.CalculateTileCount(Levels, (Envelope)g.Geometry);
         }
         DownloadExtent = (Envelope)_webMercator.ToGeographic(g.Geometry);
         NotifyPropertyChanged(p => p.DownloadExtent);
         NotifyPropertyChanged(p => p.IsDrawExtentTipVisible);
     }
 }
        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));
        }
Exemplo n.º 7
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);
               }
           });
        }
        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));
            }
        }
        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);
            }
        }
Exemplo n.º 10
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);
        }
Exemplo n.º 11
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";
        }
Exemplo n.º 12
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;
        }
Exemplo n.º 13
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);
        }
Exemplo n.º 14
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();
        }
Exemplo n.º 15
0
        void GeoTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var web = new WebMercator();
            var mps = web.ToGeographic(_start.Geometry) as MapPoint;
            var mpf = web.ToGeographic(_finish.Geometry) as MapPoint;
            if (
                (Moved &&
                lastUpdated.AddSeconds(1) < DateTime.Now) &&
                (startTime.AddSeconds(3) < DateTime.Now) &&

                (start == null || end == null || start.X != mps.X || start.Y != mps.Y || end.X != mpf.X || end.Y != mpf.Y))
            {
                start = mps;
                end = mpf;
                lastUpdated = DateTime.Now;

                var gd = DirectionsUtils.GetDirections(mps.Y.ToString(CultureInfo.InvariantCulture) + "," + mps.X.ToString(CultureInfo.InvariantCulture),
                    mpf.Y.ToString(CultureInfo.InvariantCulture) + "," + mpf.X.ToString(CultureInfo.InvariantCulture), mode = Mode);
                if (gd != null)
                {
                    if (gd.Directions != null)
                    {
                        UpdateLine(gd);
                    }

                    Directions = gd;
                }
                Moved = false;


            }

            if (Moved && lastDirection != null)
            {
                //UpdateLine(lastDirection);

            }
        }
        // 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);
                    }
                }
            }
        }
Exemplo n.º 17
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);
            }
        }
Exemplo n.º 18
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);
 }