Example #1
0
        public override void AddPinsToLayer()
        {
            foreach (PointOfInterest poi in Points)
            {
                MapPolygon polygon = new MapPolygon();
                polygon.Fill = new SolidColorBrush(_Colors[colorIndex++ % _Colors.Length]); 
                polygon.Opacity = 0.25;
                
                LocationCollection locCol = new LocationCollection();

                foreach( string line in  poi.Coordinates.Split('\n') )
                {
                    if (!string.IsNullOrEmpty(line))
                    {
                        string[] vals = line.Split(',');
                        locCol.Add(
                            new Location()
                            {
                                Latitude = double.Parse(vals[1]),
                                Longitude = double.Parse(vals[0]),
                                Altitude = 0
                            });
                    }
                }
                polygon.Locations = locCol;
                MapLayer.Children.Add(polygon);
            }

        }
Example #2
0
        public static TravelData ParseXMLToRoad(XmlDocument data)
        {
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(data.NameTable);
            nsmgr.AddNamespace("rest", "http://schemas.microsoft.com/search/local/ws/rest/v1");
            XmlNodeList roadElements = data.SelectNodes("//rest:Line", nsmgr);
            if (roadElements.Count == 0)
            {
                MessageBox.Show("No road found :(", "Highway to hell", MessageBoxButton.OK, MessageBoxImage.Error);
                return null;
            }
            else
            {
                LocationCollection locations = new LocationCollection();
                XmlNodeList points = roadElements[0].SelectNodes(".//rest:Point", nsmgr);
                foreach (XmlNode point in points)
                {
                    string latitude = point.SelectSingleNode(".//rest:Latitude", nsmgr).InnerText;
                    string longitude = point.SelectSingleNode(".//rest:Longitude", nsmgr).InnerText;

                    locations.Add(XML.SetGeographicInfo(latitude, longitude));
                }
                TravelData travelData = new TravelData();
                travelData.StringDistance = data.SelectSingleNode(".//rest:TravelDistance", nsmgr).InnerText;
                travelData.StringTravelTime = data.SelectSingleNode(".//rest:TravelDuration", nsmgr).InnerText;
                travelData.Locations = locations;
                return travelData;
            }
        }
Example #3
0
        // DELETE: odata/LocationCollections(5)
        public IHttpActionResult Delete([FromODataUri] int key)
        {
            string LogMsg = this.ControllerContext.RouteData.Values["controller"].ToString() + "Controller." +
                            this.ControllerContext.RouteData.Values["action"].ToString() + " :: ";

            LocationCollection locationcollection = null;

            try
            {
                locationcollection = data.LocationCollectionRepository.GetByID(key);
                if (locationcollection == null)
                {
                    NLogWriter.LogMessage(LogType.Error, LogMsg + "Locationcollection cannot be found");
                    throw new Exception("Locationcollection cannot be found");
                }
                data.LocationCollectionRepository.Delete(key);
                data.Save();
            }
            catch (Exception ex)
            {
                NLogWriter.LogMessage(LogType.Error, LogMsg + "Exception deleting locationcollection by key = '" + Convert.ToString(key) + "' :: " + ex.ToString());
                HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent("Exception deleting locationcollection by key = '" + Convert.ToString(key) + "' :: " + ex.ToString()),
                    ReasonPhrase = "Unable to delete locationcollection"
                };
                throw new HttpResponseException(resp);
            }
            return(StatusCode(HttpStatusCode.NoContent));
        }
        /// <summary>
        /// Registers the JavaScript to display the map.
        /// </summary>
        /// <param name="scriptManager">The page's script manager.</param>
        /// <param name="mapType">Type of the map.</param>
        /// <param name="mapSectionId">The ID of the section (div) on the page in which the map should be created.</param>
        /// <param name="currentLocationSpanId">The ID of the span showing the current location text.</param>
        /// <param name="noLocationSpanId">The ID of the span shown when no location is selected.</param>
        /// <param name="instructionSpanId">The ID of the span with driving directions, etc.</param>
        /// <param name="directionsLinkId">The ID of the link to driving directions.</param>
        /// <param name="directionsSectionId">The ID of the section (div) with driving directions text.</param>
        /// <param name="locations">The list of locations to display.</param>
        /// <param name="showAllLocationsOnLoad">if set to <c>true</c> shows the map with all locations on it by default.</param>
        public override void GenerateMapScriptCore(ScriptManager scriptManager, MapType mapType, string mapSectionId, string currentLocationSpanId, string noLocationSpanId, string instructionSpanId, string directionsLinkId, string directionsSectionId, LocationCollection locations, bool showAllLocationsOnLoad)
        {
            ICollection<JavaScript.Location> locationsAsJson = locations.AsJson();
            string mapParameters = String.Format(CultureInfo.InvariantCulture, "currentLocationSpan: {0}, noLocationSpan: {1}, instructionSpan: {2}, directionsLink: {3}, directionsSection: {4}, mapType: {5}, locationsArray: {6}", GetElementJavaScript(currentLocationSpanId), GetElementJavaScript(noLocationSpanId), GetElementJavaScript(instructionSpanId), GetElementJavaScript(directionsLinkId), GetElementJavaScript(directionsSectionId), ConvertMapType(mapType), new JavaScriptSerializer().Serialize(locationsAsJson));

            scriptManager.Scripts.Add(new ScriptReference(GetLoaderUrl(this.ApiKey)));
            scriptManager.Scripts.Add(new ScriptReference("Engage.Dnn.Locator.JavaScript.BaseLocator.js", "EngageLocator"));
            scriptManager.Scripts.Add(new ScriptReference("Engage.Dnn.Locator.JavaScript.GoogleLocator.js", "EngageLocator"));
            ScriptManager.RegisterStartupScript(
                    scriptManager.Page,
                    typeof(GoogleProvider),
                    "Initialize",
                    "google.setOnLoadCallback(jQuery(function(){ jQuery.noConflict(); $create(Engage.Dnn.Locator.GoogleMap, {" + mapParameters + "}, {}, {}, $get('" + mapSectionId + "')); }));",
                    true);

            if (showAllLocationsOnLoad)
            {
                ScriptManager.RegisterStartupScript(
                        scriptManager.Page,
                        typeof(GoogleProvider),
                        "showAllLocations",
                        "google.setOnLoadCallback(jQuery(function(){ $find('" + mapSectionId + "$GoogleMap').showAllLocations(); }));",
                        true);
            }
        }
        public static List <MapMultiPolygon> ReadPolygonData(XDocument xmlString)
        {
            List <MapMultiPolygon> polygonData = new List <MapMultiPolygon>();


            var collection = from nod in xmlString.Descendants("MultiPolygon") select nod;

            foreach (var multiPolygon in collection)
            {
                List <LocationCollection> points = new List <LocationCollection>();
                var Loops = from poly in multiPolygon.Descendants("Polygon") select poly;
                foreach (var polygon in Loops)
                {
                    LocationCollection locations = GetLocationData(polygon.Value);
                    points.Add(locations);
                }
                MapMultiPolygon multiP = new MapMultiPolygon();
                var             IdAtt  = multiPolygon.Attribute("ObjectId");
                multiP.ObjectId = IdAtt.Value;
                multiP.Vertices = points;
                polygonData.Add(multiP);
            }

            return(polygonData);
        }
Example #6
0
        /// <summary>
        /// Maintains a cache of location static properties
        /// </summary>
        /// <param name="locationId"></param>
        /// <returns></returns>
        internal Location GetLocation(string locationId)
        {
            var locations = MemoryCache.Default[CACHE_LOCATIONS] as LocationCollection;

            if (locations == null)
            {
                locations = new LocationCollection();
                // Cache for 30 minutes
                MemoryCache.Default.Add(CACHE_LOCATIONS, locations, DateTimeOffset.UtcNow + TimeSpan.FromMinutes(30));
            }
            Location loc;

            lock (locations)
            {
                if (locations.Contains(locationId))
                {
                    // Cache hit. Saves a query
                    loc = locations[locationId];
                    _trace.Write(string.Format("Cache Hit. Location {0} found in cache", locationId));
                }
                else
                {
                    loc = _repos.GetLocation(locationId);
                    if (loc != null)
                    {
                        locations.Add(loc);
                    }
                }
            }
            return(loc);
        }
Example #7
0
        public static LocationCollection ToThreadFlowLocationCollection(this CodeFlow codeFlow, Run run, int resultId, int runIndex)
        {
            if (codeFlow == null)
            {
                return(null);
            }

            var model = new LocationCollection(codeFlow.Message.Text);

            if (codeFlow.ThreadFlows?[0]?.Locations != null)
            {
                foreach (ThreadFlowLocation location in codeFlow.ThreadFlows[0].Locations)
                {
                    // TODO we are not yet properly hardened against locationless
                    // code locations (and what this means is also in flux as
                    // far as SARIF producers). For now we skip these.
                    if (location.Location?.PhysicalLocation == null)
                    {
                        continue;
                    }

                    model.Add(location.ToLocationModel(run, resultId, runIndex));
                }
            }

            return(model);
        }
        private static LocationCollection generatePolylinePointsWithArrow(Location anchor, Location towards)
        //  Summary:
        //  This code was adapted and translated from https://rbrundritt.wordpress.com/2009/05/31/drawing-arrow-heads-on-polylines/
        {
            LocationCollection arr = new LocationCollection();

            //  last point in polyline array
            Location anchorPoint = anchor;
            //  bearing from first point to second point in pointline array
            double bearing = calculateBearing(anchorPoint, towards);
            //  length of arrow head lines in km
            double arrowLength = 0.15;
            //  angle of arrow lines relative to polyline in degrees
            double arrowAngle = 40;
            //  calculate coordinates of arrow tips
            Tuple <double, double> arrowPoint1 = calculateCoord(anchorPoint, bearing - arrowAngle, arrowLength);
            Tuple <double, double> arrowPoint2 = calculateCoord(anchorPoint, bearing + arrowAngle, arrowLength);

            //  go from last point in polyline to one arrow tip, then back to the
            //  last point then to the second arrow tip.

            arr.Add(new Location(arrowPoint1.Item1, arrowPoint1.Item2));
            arr.Add(anchorPoint);
            arr.Add(new Location(arrowPoint2.Item1, arrowPoint2.Item2));

            return(arr);
        }
Example #9
0
        public LocationCollection GetAllLocationsDynamicCollection(string whereExpression, string orderBy)
        {
            IDBManager         dbm  = new DBManager();
            LocationCollection cols = new LocationCollection();

            try
            {
                dbm.CreateParameters(2);
                dbm.AddParameters(0, "@WhereCondition", whereExpression);
                dbm.AddParameters(1, "@OrderByExpression", orderBy);
                IDataReader reader = dbm.ExecuteReader(CommandType.StoredProcedure, "SelectLocationsDynamic");
                while (reader.Read())
                {
                    Location location = new Location();
                    location.LocationID   = Int32.Parse(reader["LocationID"].ToString());
                    location.AddressID    = Int32.Parse(reader["AddressID"].ToString());
                    location.Name         = reader["Name"].ToString();
                    location.ModifiedDate = DateTime.Parse(reader["ModifiedDate"].ToString());
                    cols.Add(location);
                }
            }

            catch (Exception ex)
            {
                log.Write(ex.Message, "GetAllLocationsDynamicCollection");
                throw (ex);
            }
            finally
            {
                dbm.Dispose();
            }
            return(cols);
        }
Example #10
0
 internal IEnumerable <DoublePoint> ConvertGeographicToPixelCoordinates(LocationCollection locations)
 {
     foreach (var location in locations)
     {
         yield return(this.ConvertGeographicToPixelCoordinate(location));
     }
 }
Example #11
0
        public void AddPath(LocationCollection polyPoints, SolidColorBrush brush, PathDirectionType direction)
        {
            MapPolygon poly = new MapPolygon();
            poly.Opacity = 0.8;
            poly.StrokeThickness = 3;
            poly.Stroke = brush;
            poly.Locations = polyPoints;
            Children.Add(poly);

            int numPoints = 1;
            while (numPoints * 10 < polyPoints.Count)
                numPoints *= 2;

            for (int i = 0; i < numPoints; i++)
            {
                int j = i * (polyPoints.Count / numPoints);

                if (j < polyPoints.Count)
                {
                    Location loc = polyPoints[j];

                    BountyPushpin pin = new BountyPushpin();
                    pin.ToolTip = string.Format("{0} ({1}Path)", BountyName,
                            (direction == PathDirectionType.Invalid ? string.Empty : Enum.GetName(typeof(PathDirectionType), direction) + " "));
                    pin.PopupContent = new PopupContentFactory()
                            .AppendWikiLink(BountyName)
                            .AppendDulfyLink(BountyName)
                            .Content;
                    pin.Location = loc;
                    Children.Add(pin);
                }
            }
        }
Example #12
0
        public async Task <List <string> > GetLocationAds()
        {
            var htmlDocument         = new HtmlAgilityPack.HtmlDocument();
            var parseLocationAdsData = new List <string>();
            await Task.Run(() =>
            {
                for (int i = 0; i < ContentCollection.Count; i++)
                {
                    htmlDocument.LoadHtml(ContentCollection[i]);
                    HtmlNodeCollection nodeAds = htmlDocument.DocumentNode.SelectNodes("//p[@class='lheight16']/small[@class='breadcrumb x-normal'][1]/span");

                    if (nodeAds != null)
                    {
                        for (var k = 0; k < nodeAds.Count; k++)
                        {
                            LocationCollection.Add(nodeAds[k].InnerText);
                            parseLocationAdsData.Add(nodeAds[k].InnerText);
                            //PricesCollection.Add();
                        }
                    }
                }
            });

            return(parseLocationAdsData);
        }
Example #13
0
        /// <summary>
        /// This function allows to clear the data stored in this object - without creating a new one
        /// </summary>
        /// <returns>True if the function was sucessful</returns>
        public bool ClearData()
        {
            try
            {
                this._xAcceleration          = new List <float>();
                this._yAcceleration          = new List <float>();
                this._zAcceleration          = new List <float>();
                this._yaw                    = new List <float>();
                this._roll                   = new List <float>();
                this._pitch                  = new List <float>();
                this._Velocity               = new List <float>();
                this._pressure               = new List <float>();
                this._height                 = new List <float>();
                this._route                  = new LocationCollection();
                this._numberOfPoints         = 0;
                this._dataPointsAngle        = new int();
                this._routeDate              = new DateTime();
                this._routeEndTime           = new DateTime();
                this._routeStartTime         = new DateTime();
                this._isValidRoute           = new bool();
                this._routeName              = null;
                this._averageSattelitesInUse = new int();
                this._dataPointsAcceleration = new int();
                this._dataPointsVelocity     = new int();

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #14
0
 /// <summary>Creates a new <see cref="Unit"/> instance.
 /// </summary>
 /// <param name="type">Type.</param>
 /// <param name="power">Power.</param>
 /// <param name="location">Location.</param>
 public Unit(UnitType type, Power power, Location location)
 {
     this.type = type;
     this.power = power;
     this.location = location;
     this.retreatLocations = new LocationCollection();
 }
Example #15
0
        public LocationCollection GetAllLocationsCollection()
        {
            IDBManager         dbm  = new DBManager();
            LocationCollection cols = new LocationCollection();

            try
            {
                IDataReader reader = dbm.ExecuteReader(CommandType.StoredProcedure, "SelectLocationsAll");
                while (reader.Read())
                {
                    Location location = new Location();
                    location.LocationID   = Int32.Parse(reader["LocationID"].ToString());
                    location.AddressID    = Int32.Parse(reader["AddressID"].ToString());
                    location.Name         = reader["Name"].ToString();
                    location.ModifiedDate = DateTime.Parse(reader["ModifiedDate"].ToString());
                    cols.Add(location);
                }
            }

            catch (Exception ex)
            {
                log.Write(ex.Message, "GetAllLocationsCollection");
                throw (ex);
            }
            finally
            {
                dbm.Dispose();
            }
            return(cols);
        }
        private static Collection <LocationCollection> GetPoints(byte[] content, ICoordinateValueConverter coordinateConverter)
        {
            int numberOfParts  = BitConverter.ToInt32(content, 36);
            int numberOfPoints = BitConverter.ToInt32(content, 40);

            int startPoints = 44 + 4 * numberOfParts;
            Collection <LocationCollection> collection = new Collection <LocationCollection>();

            int pointsCount, partFirstPointIndex, startPoint;

            for (int partIndex = 0; partIndex < numberOfParts; partIndex++)
            {
                partFirstPointIndex = BitConverter.ToInt32(content, 44 + 4 * partIndex);

                // Each point is represented by x,y double coordinates -- 16 bytes
                startPoint = startPoints + partFirstPointIndex * 16;

                if (partIndex < numberOfParts - 1)
                {
                    pointsCount = BitConverter.ToInt32(content, 44 + 4 * (partIndex + 1)) - partFirstPointIndex;
                }
                else
                {
                    pointsCount = numberOfPoints - partFirstPointIndex;
                }

                LocationCollection locations = GetPoints(content, startPoint, pointsCount, coordinateConverter);

                collection.Add(locations);
            }

            return(collection);
        }
        public void SetTreePins(List<Tree> trees, string name)
        {
            map.Children.Clear();

            foreach (Tree tree in trees)
            {
                MapPolygon point = new MapPolygon();
                point.Stroke = new SolidColorBrush(Colors.White);
                point.Fill = new SolidColorBrush(Colors.Green);
                point.Opacity = 0.7f;
                Location location1 = new Location() { Latitude = tree.Coordinates.X - 0.0001, Longitude = tree.Coordinates.Y - 0.00006 };
                Location location2 = new Location() { Latitude = tree.Coordinates.X + 0.0001, Longitude = tree.Coordinates.Y - 0.00006 };
                Location location3 = new Location() { Latitude = tree.Coordinates.X + 0.0001, Longitude = tree.Coordinates.Y + 0.00006 };
                Location location4 = new Location() { Latitude = tree.Coordinates.X - 0.0001, Longitude = tree.Coordinates.Y + 0.00006 };
                LocationCollection locations = new LocationCollection();
                locations.Add(location1);
                locations.Add(location2);
                locations.Add(location3);
                locations.Add(location4);
                point.Locations = locations;

                map.Children.Add(point);

                /*
                Pushpin pin = new Pushpin();
                pin.Location = new GeoCoordinate(tree.Coordinates.X, tree.Coordinates.Y);
                pin.Content = name;
                map.Children.Add(pin);
                 * */
            }

            NavigationService.GoBack();
        }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="locations">Locations to include in this template.</param>
 /// <param name="notes">Footnote definitions to include in this template.</param>
 /// <param name="classes">Train classes to include in this template.</param>
 /// <param name="boxes">Signalboxes to include in this template.</param>
 public DocumentTemplate(IEnumerable <Location> locations, IEnumerable <Note> notes, IEnumerable <TrainClass> classes, IEnumerable <Signalbox> boxes)
 {
     Locations       = new LocationCollection(locations ?? Array.Empty <Location>());
     NoteDefinitions = new NoteCollection(notes ?? Array.Empty <Note>());
     TrainClasses    = new TrainClassCollection(classes ?? Array.Empty <TrainClass>());
     Signalboxes     = new SignalboxCollection(boxes ?? Array.Empty <Signalbox>());
 }
Example #19
0
        private void AddCircleRadius(double meters)
        {
            if (this.myLocation != null)
            {
                this.shapeLayer.Shapes.Clear();
                var circlePoints = new LocationCollection();

                var earthRadius = 6371;
                var lat         = (this.myLocation.Latitude * Math.PI) / 180.0;  // radians
                var lon         = (this.myLocation.Longitude * Math.PI) / 180.0; // radians
                var d           = meters / 1000 / earthRadius;                   // d = angular distance covered on earths surface

                for (int x = 0; x <= 360; x++)
                {
                    var brng       = (x * Math.PI) / 180.0; // radians
                    var latRadians = Math.Asin((Math.Sin(lat) * Math.Cos(d)) + ((Math.Cos(lat) * Math.Sin(d)) * Math.Cos(brng)));
                    var lngRadians = lon + Math.Atan2((Math.Sin(brng) * Math.Sin(d)) * Math.Cos(lat), Math.Cos(d) - (Math.Sin(lat) * Math.Sin(latRadians)));

                    var pt = new Location(180.0 * latRadians / Math.PI, 180.0 * lngRadians / Math.PI);
                    circlePoints.Add(pt);
                }

                MapPolygon circlePolygon = new MapPolygon();
                circlePolygon.FillColor = Color.FromArgb(80, 20, 20, 200);
                circlePolygon.Locations = circlePoints;
                this.shapeLayer.Shapes.Add(circlePolygon);
            }
        }
        public async Task LoadTrackList()
        {
            var tracks = await TracksDataProvider.GetRaceTracks();

            Locations          = new LocationCollection(tracks.AsEnumerable());
            LocationCollection = Locations;
        }
 public JObject Get(ObjectId itemId)
 {
     try
     {
         var queryableLocation = LocationCollection.AsQueryable();
         var queryOffer        = from d in queryableLocation
                                 where d.Id.Equals(itemId)
                                 select d;
         var location = queryableLocation.First();
         return
             (JObject.FromObject(
                  new
         {
             status = "success",
             result = location
         }
                  ));
     }
     catch (Exception ex)
     {
         return
             (JObject.FromObject(
                  new
         {
             status = "Exception Thrown",
             result = false,
             message = ex.Message
         }
                  ));
     }
 }
Example #22
0
 private void OnVisualizeTrack(VisualizeTrackEvent obj)
 {
     Tracks.Clear();
     if (obj.Track != null && obj.Track.Any())
     {
         if (obj.Track.Count == 2)
         {
             Tracks.Add(obj.Track.First().CalculateGreatCircleLocations(obj.Track.Last()));
         }
         else if (obj.Track.Count > 2)
         {
             IList <LogbookLocation> filteredTrack = GetFilteredTrack(obj.Track, Length.FromMeters(10));
             int pageSize = 2000;
             int pages    = (int)Math.Ceiling(filteredTrack.Count / (double)pageSize);
             for (int i = 0; i < pages * pageSize; i += pageSize)
             {
                 LocationCollection locations = new LocationCollection();
                 foreach (LogbookLocation location in filteredTrack.Skip(i).Take(pageSize))
                 {
                     locations.Add(location);
                 }
                 Tracks.Add(locations);
             }
         }
         ZoomToTracksBounds();
     }
 }
Example #23
0
        // GET: Location
        public LocationCollection Get()
        {
            LocationCollection recs = new LocationCollection();

            string      language = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
            UserAccount user     = UserAccount.GetByPrinciple(User);

            if (user != null)
            {
                using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["CONN_STRING"]))
                {
                    //DynamicParameters args = new DynamicParameters();
                    //args.Add("@UserID", user.UserID.ToString());

                    var report = conn.Query <Location>("dbo.report_Customer_List", null, commandType: CommandType.StoredProcedure);

                    foreach (Location rec in report)
                    {
                        recs.Add(rec);
                    }
                }
            }

            return(recs);
        }
Example #24
0
        /// <summary>
        /// Change the polylines on the map.
        /// </summary>
        private static void ShapesChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
        {
            MapControl mapControl = (MapControl)dependencyObject;

            if (args.OldValue != null)
            {
                // remove all old polylines from the map:
                mapControl.map.ShapeLayers.Clear();
            }

            if (args.NewValue != null)
            {
                MapShapeLayer routeLayer = new MapShapeLayer();

                List <Shape> shapes = (List <Shape>)args.NewValue;
                foreach (var shape in shapes)
                {
                    MapPolyline polyline = new MapPolyline();
                    polyline.Color = Color.FromArgb(255, 0x4f, 0x64, 0xba);
                    polyline.Width = 6;

                    LocationCollection locations = new LocationCollection();
                    foreach (var point in shape.Points)
                    {
                        locations.Add(new Location(point.Latitude, point.Longitude));
                    }

                    polyline.Locations = locations;
                    routeLayer.Shapes.Add(polyline);
                }

                mapControl.map.ShapeLayers.Add(routeLayer);
            }
        }
        private static bool DetermineIfPolygonIsOuter(LocationCollection poly, List <LocationCollection> LoopList, int currentIndex)
        {
            //Assumption is that all points are inside.
            //therefore it is necessary to only test one point
            bool     IsInside = false;
            bool     FoundPolyOutsideThisOne = false;
            Location point = poly[0];

            for (int i = 0; i < LoopList.Count; i++)
            {
                if (i != currentIndex) // make sure to exclude current loop from checking
                {
                    LocationCollection loop = LoopList[i];
                    IsInside = PolygonLocationChecking.IsLocationInComplexPolygon(loop, null, point);
                    if (IsInside == true)
                    {
                        FoundPolyOutsideThisOne = true;
                        break;
                    }
                }
            }
            if (FoundPolyOutsideThisOne == true)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Example #26
0
        // POST: odata/LocationCollections
        public IHttpActionResult Post(LocationCollection locationCollection)
        {
            string LogMsg = this.ControllerContext.RouteData.Values["controller"].ToString() + "Controller." +
                            this.ControllerContext.RouteData.Values["action"].ToString() + " :: ";

            try
            {
                if (!ModelState.IsValid)
                {
                    NLogWriter.LogMessage(LogType.Error, LogMsg + "Invalid ModelState");
                    throw new Exception("Invalid modelstate");
                }

                data.LocationCollectionRepository.Insert(locationCollection);
                data.Save();
            }
            catch (Exception ex)
            {
                NLogWriter.LogMessage(LogType.Error, LogMsg + "Exception creating locationcollection :: " + ex.ToString());
                HttpResponseMessage resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content      = new StringContent("Exception creating locationcollection :: " + ex.ToString()),
                    ReasonPhrase = "Unable to create locationcollection"
                };
                throw new HttpResponseException(resp);
            }

            return(Created(locationCollection));
        }
        private static LocationCollection GetPoints(byte[] content, int startPoint, int count, ICoordinateValueConverter coordinateConverter)
        {
            int      point;
            double   longitude, latitude;
            Location location;

            LocationCollection locations = new LocationCollection();

            for (int pointIndex = 0; pointIndex < count; pointIndex++)
            {
                point     = startPoint + pointIndex * 16;
                longitude = BitConverter.ToDouble(content, point);
                latitude  = BitConverter.ToDouble(content, point + 8);
                location  = new Location()
                {
                    Latitude = latitude, Longitude = longitude
                };

                // NOTE: Optionally allow the user to re-project coordinates to different system.
                if (coordinateConverter != null)
                {
                    location = coordinateConverter.Convert(location);
                }

                locations.Add(location);
            }

            return(locations);
        }
Example #28
0
        void CreateHex()
        {
            if (_hexa.Equals(""))
            {
                return;
            }
            GeoHex.Zone  zone      = GeoHex.GeoHex.Decode(_hexa);
            GeoHex.Loc[] locations = zone.getHexCoords();
            if (locations == null || locations.Count() != 6)
            {
                return;
            }

            map1.Center = new GeoCoordinate(zone.lat, zone.lon);

            var collection = new LocationCollection();

            foreach (var location in locations)
            {
                var geo = new GeoCoordinate(location.lat, location.lon);
                collection.Add(geo);
            }
            mapPolygon.Locations = collection;

            PolygonLayer.Visibility = Visibility.Visible;
        }
Example #29
0
        public static void DrawSquare(this Map MyMap, DataModel.Localization startLocal, DataModel.Localization endLocal)
        {
            MapPolyline polyline = new MapPolyline();

            polyline.Stroke          = new SolidColorBrush(Colors.Blue);
            polyline.StrokeThickness = 2;
            polyline.Opacity         = 0.7;
            LocationCollection locations = new LocationCollection();

            locations.Add(new Location()
            {
                Latitude = double.Parse(startLocal.latitude), Longitude = double.Parse(startLocal.longitude)
            });
            locations.Add(new Location()
            {
                Latitude = double.Parse(endLocal.latitude), Longitude = double.Parse(startLocal.longitude)
            });
            locations.Add(new Location()
            {
                Latitude = double.Parse(endLocal.latitude), Longitude = double.Parse(endLocal.longitude)
            });
            locations.Add(new Location()
            {
                Latitude = double.Parse(startLocal.latitude), Longitude = double.Parse(endLocal.longitude)
            });
            locations.Add(new Location()
            {
                Latitude = double.Parse(startLocal.latitude), Longitude = double.Parse(startLocal.longitude)
            });
            polyline.Locations = locations;
            MyMap.Children.Add(polyline);
        }
 public JObject Get()
 {
     try
     {
         List <Location> collection = LocationCollection.Find(new BsonDocument()).ToList();
         JObject         returnJson = JObject.FromObject(
             new
         {
             status = "success",
             result = collection
         }
             );
         return(returnJson);
     }
     catch (Exception ex)
     {
         return
             (JObject.FromObject(
                  new
         {
             status = "Exception Thrown",
             result = false,
             message = ex.Message
         }
                  ));
     }
 }
        public async Task <JObject> Create(Location item)
        {
            try
            {
                await LocationCollection.InsertOneAsync(item);

                return
                    (JObject.FromObject(
                         new
                {
                    status = "success",
                    result = item
                }
                         ));
            }
            catch (Exception ex)
            {
                return
                    (JObject.FromObject(
                         new
                {
                    status = "Exception Thrown",
                    result = false,
                    message = ex.Message
                }
                         ));
            }
        }
Example #32
0
        public void start(MainPage mainPage)
        {
            mainPage.drawALineButton.Content = "Turn off drawing line mode";
            this.locationCollection = new LocationCollection();

            Debug.WriteLine("Start drawing a line");
        }
Example #33
0
        public static LocationEntity GetByUid(string locationUid)
        {
            LocationCollection locations = new LocationCollection();

            locations.GetMulti(new PredicateExpression(LocationFields.UniqueIdentifier == locationUid));
            return(locations.Count > 0 ? locations[0] : null);
        }
Example #34
0
        public ViewModel()
        {
            var timer = new DispatcherTimer();

            _boundary         = null;
            _windowBackground = new SolidColorBrush(Color.FromArgb(0x01, 0, 0, 0));
            ctrl    = false;
            shift   = false;
            alt     = false;
            SetMode = true;

            KListener.KeyDown += new RawKeyEventHandler(KListener_KeyDown);
            KListener.KeyUp   += new RawKeyEventHandler(KListener_KeyUp);
            Brite              = 0.5;

            SystemType = new NexradTileLayer
            {
                SourceName  = "ERAM",
                Description = "© [Srinath Nandakumar & Iowa State University](http://mesonet.agron.iastate.edu/)",
                TileSource  = new TileSource {
                    UriFormat = "https://web.ics.purdue.edu/~snandaku/atc/processor.php?x={x}&y={y}&z={z}"
                },
                UpdateWhileViewportChanging = true,
                MinZoomLevel = 7,
                MaxZoomLevel = 11
            };
            //https://wms.chartbundle.com/tms/1.0.0/sec/{z}/{x}/{y}.png?origin=nw
            timer.Interval = TimeSpan.FromSeconds(300);
            timer.Tick    += timer_Tick;
            timer.Start();

            Orientation = 0;

            State = WindowState.Maximized;
        }
Example #35
0
        private void SetPolylinePoints(D2DPolyline polyline, LocationCollection locations)
        {
            // materialize the list to skip managed-to-unmanaged marshaling on every iteration
            var list = this.Owner.ConvertGeographicToPixelCoordinates(locations).ToList();

            polyline.SetPoints(list);
        }
        public void drawCircle(Microsoft.Maps.MapControl.WPF.Location Loc, double dRadius, Color fillColor)
        {
            var locCollection = new LocationCollection();
            var EarthRadius   = 6367; // Earth Radius in Kilometers

            //Convert location to radians based on
            var latitude  = (Math.PI / 180) * (Loc.Latitude);
            var longitude = (Math.PI / 180) * (Loc.Longitude);

            var d = dRadius / EarthRadius;

            for (int x = 0; x < 360; x++)
            {
                var angle      = x * (Math.PI / 180); //radians
                var latRadians = Math.Asin(Math.Sin(latitude) * Math.Cos(d) + Math.Cos(latitude) * Math.Sin(d) * Math.Cos(angle));
                var lngRadians = longitude + Math.Atan2(Math.Sin(angle) * Math.Sin(d) * Math.Cos(latitude), Math.Cos(d) - Math.Sin(latitude) * Math.Sin(latRadians));

                //Get location of the point
                var pt = new Microsoft.Maps.MapControl.WPF.Location(180.0 * latRadians / Math.PI, 180.0 * lngRadians / Math.PI);

                //Add the new calculatied poitn to the collection
                locCollection.Add(pt);
            }

            MapPolygon polygon = new MapPolygon();

            polygon.Fill            = new SolidColorBrush(fillColor);
            polygon.Stroke          = new SolidColorBrush(Colors.Black);
            polygon.StrokeThickness = 1;
            polygon.Opacity         = 0.65;
            polygon.Locations       = locCollection;

            myMap.Children.Add(polygon);
        }
        public static LocationCollection GetCollection(int gymId)
        {
            LocationCollection myCollection = null;
            {
                using (SqlConnection myConnection = new SqlConnection(AppConfiguration.ConnectionString))
                {
                    using (SqlCommand myCommand = new SqlCommand("usp_GetLocation", myConnection))
                    {
                        myCommand.CommandType = CommandType.StoredProcedure;

                        myCommand.Parameters.AddWithValue("@QueryId", SelectTypeEnum.GetCollectionById);
                        myCommand.Parameters.AddWithValue("@GymId", gymId);

                        myConnection.Open();

                        using (SqlDataReader myReader = myCommand.ExecuteReader())
                        {
                            if (myReader.HasRows)
                            {
                                myCollection = new LocationCollection();
                                while (myReader.Read())
                                {
                                    myCollection.Add(FillDataRecord(myReader));
                                }
                            }
                            myReader.Close();
                        }
                    }
                }
                return(myCollection);
            }
        }
Example #38
0
 public MoveToShipAtRange(Ship targetShip, int range, LocationCollection locations)
 {
     this.OrderValues = new object[3];
     this.OrderValues[0] = targetShip;
     this.OrderValues[1] = range;
     this.OrderValues[2] = locations;
 }
 /// <summary>
 /// Initializes a new instance of this type.
 /// </summary>
 /// <param name="locations">A collection of locations.</param>
 public RouteModel(ICollection<Location> locations)
 {
     _locations = new LocationCollection();
     foreach (Location location in locations)
     {
         _locations.Add(location);
     }
 }
Example #40
0
 public RouteModel(IEnumerable<GeoCoordinate> locations)
 {
     _locations = new LocationCollection();
     foreach (var location in locations)
     {
         _locations.Add(location);
     }
 }
Example #41
0
 public Game(SerializationInfo info, StreamingContext context)
 {
     CombatLocations = (LocationCollection)info.GetValue("CombatLocations", typeof(LocationCollection));
     StarSystems = (StarSystemCollection)info.GetValue("StarSystems", typeof(StarSystemCollection));
     Players = (PlayerCollection)info.GetValue("Players", typeof(PlayerCollection));
     ExistingHulls = (List<ShipHull>)info.GetValue("ExistingHulls", typeof(List<ShipHull>));
     ExistingParts = (List<EidosPart>)info.GetValue("ExistingParts", typeof(List<EidosPart>));
     ExistingShips = (List<Ship>)info.GetValue("ExistingShips", typeof(List<Ship>));
 }
 public static ICoordinate[] LocationCollectionToCoordinates(LocationCollection locations)
 {
     var coordinates = new Coordinate[locations.Count];
     for (var x = 0; x < locations.Count; x++)
     {
         coordinates[x] = (Coordinate)Convert(locations[x]);
     }
     return (ICoordinate[])coordinates;
 }
 public static LocationCollection CoordinatesToLocationCollection(ICoordinate[] coordinates)
 {
     var locations = new LocationCollection();
     foreach (var coordinate in coordinates)
     {
         locations.Add(ConvertBack(coordinate));
     }
     return locations;
 }
 public static LocationCollection ToLocationCollection (this IList<BasicGeoposition>PointList)
 {
     var locations = new LocationCollection();
     foreach (var p in PointList)
    	{
    		   locations.Add(p.ToLocation());                             
    	}
     return locations;
 }
        //public static Route AsRoute(this GoogleApisLib.GoogleMapsApi.DirectionsRoute googleRoute)
        //{
        //    var route = new Route();
        //    route.OverviewPath = googleRoute.overview_path.AsLocationCollection();
        //    route.Directions = new ObservableCollection<Direction>();
        //    foreach (var leg in googleRoute.legs)
        //    {
        //        route.Directions.Add(leg.AsDirection());
        //    }
        //    return route;
        //}
        //public static Direction AsDirection(this GoogleApisLib.GoogleMapsApi.DirectionsLeg googleLeg)
        //{
        //    var direction = new Direction
        //        {
        //            Distance = googleLeg.distance.value,
        //            Duration = TimeSpan.FromSeconds(googleLeg.duration.value),
        //            StartLocation = googleLeg.start_location.AsGeoCoordinate(),
        //            EndLocation = googleLeg.end_location.AsGeoCoordinate(),
        //            StartAddress = googleLeg.start_address,
        //            EndAddress = googleLeg.end_address,
        //            ////StartTime = DateTime.Parse(googleLeg.departure_time.value),
        //            ////EndTime = DateTime.Parse(googleLeg.arrival_time.value)
        //        };
        //    if (googleLeg.steps != null)
        //    {
        //        direction.Steps = new ObservableCollection<DirectionStep>();
        //        foreach (var googleStep in googleLeg.steps)
        //        {
        //            direction.Steps.Add(googleStep.AsDirectionStep());
        //        }
        //    }
        //    return direction;
        //}
        //public static DirectionStep AsDirectionStep(this GoogleApisLib.GoogleMapsApi.DirectionsStep googleStep)
        //{
        //    var directionStep = new DirectionStep
        //        {
        //            Instructions = googleStep.instructions,
        //            Distance = googleStep.distance.value,
        //            Duration = TimeSpan.FromSeconds(googleStep.duration.value),
        //            StartLocation = googleStep.start_location.AsGeoCoordinate(),
        //            EndLocation = googleStep.end_location.AsGeoCoordinate(),
        //            Mode = googleStep.travel_mode.ToString(),
        //            OverviewPath = googleStep.path.AsLocationCollection()
        //        };
        //    if (googleStep.steps != null)
        //    {
        //        directionStep.Steps = new ObservableCollection<DirectionStep>();
        //        foreach (var innerStep in googleStep.steps)
        //        {
        //            directionStep.Steps.Add(innerStep.AsDirectionStep());
        //        }
        //    }
        //    return directionStep;
        //}
        public static LocationCollection AsLocationCollection(this GoogleApisLib.GoogleMapsApi.LatLng[] coordinates)
        {
            var collection = new LocationCollection();
            foreach (var coordinate in coordinates)
            {
                collection.Add(coordinate.AsGeoCoordinate());
            }

            return collection;
        }
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     if (!(value is IEnumerable<Location>))
     {
         return null;
     }
     var collection = new LocationCollection();
     collection.AddRange(((IEnumerable<Location>) value).Select(l => l.ToGeoCoordinate()));
     return collection;
 }
Example #47
0
        public static LocationCollection MapPointsToLocations(IEnumerable<MapPoint> mapPoints)
        {
            var locations = new LocationCollection();

            foreach (var mapPoint in mapPoints)
            {
                locations.Add(new Location(mapPoint.Lat, mapPoint.Lng));
            }
            return locations;
        }
Example #48
0
 /// <summary>
 /// Converts a value.
 /// </summary>
 /// <param name="value">The value produced by the binding source.</param>
 /// <param name="targetType">The type of the binding target property.</param>
 /// <param name="parameter">The converter parameter to use.</param>
 /// <param name="culture">The culture to use in the converter.</param>
 /// <returns>
 /// A converted value. If the method returns null, the valid null value is used.
 /// </returns>
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     List<Coordinate> coordinates = value as List<Coordinate>;
       LocationCollection collection = new LocationCollection();
       foreach (Coordinate coord in coordinates)
       {
     collection.Add(new GeoCoordinate(coord.Latitude,coord.Longitude));
       }
       return collection;
 }
        //LocationCollection
        //public static bool IsLocationInComplexPolygon(List<Location> mainPolygon, List<List<Location>> holes, Location checkPoint)
        public static bool IsLocationInComplexPolygon(LocationCollection mainPolygon, List<LocationCollection> holes, Location checkPoint)
        {
            if (checkPoint != null)
            {
                // check if point is inside boundary box
                double minX = mainPolygon[0].Latitude;
                double maxX = mainPolygon[0].Latitude;
                double minY = mainPolygon[0].Longitude;
                double maxY = mainPolygon[0].Longitude;

                foreach (var q in mainPolygon)
                {
                    minX = Math.Min(q.Latitude, minX);
                    maxX = Math.Max(q.Latitude, maxX);
                    minY = Math.Min(q.Longitude, minY);
                    maxY = Math.Max(q.Longitude, maxY);
                }

                if (checkPoint.Latitude < minX || checkPoint.Latitude > maxX || checkPoint.Longitude < minY || checkPoint.Longitude > maxY)
                {
                    // point is not inside boundary box, do not continue
                    return false;
                }

                // check if point is inside main polygon
                var result = IsLocationInPolygon(mainPolygon, checkPoint);

                // point is not inside main polygon, do not continue
                if (result == false) return false;

                // check if point is not inside of any hole
                if (holes != null)
                {
                    foreach (var holePolygon in holes)
                    {
                        var holeResult = IsLocationInPolygon(holePolygon, checkPoint);

                        if (holeResult)
                        {
                            // point is inside hole, that means it doesn't belong to complex polygon, return false
                            return false;
                        }
                    }
                }

                // if all tests passed then point is inside Polygon.
                return true;

            }
            else
            {
                return false;
            }
        }
 public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
 {
     if (value is IEnumerable<Location>)
     {
         var collection = new LocationCollection();
         foreach (var l in ((IEnumerable<Location>)value))
             collection.Add(l);
         return collection;
     }
     return null;
 }
		/// <summary>
		/// Gets a LocationCollection representing an enumeration of points.
		/// </summary>
		/// <param name="ezp"></param>
		/// <returns></returns>
		public static LocationCollection ToLocationCollection(this IEnumerable<ZonePoint> ezp)
		{
			LocationCollection coll = new LocationCollection();

			foreach (ZonePoint p in ezp)
			{
				coll.Add(p.ToGeoCoordinate());
			}

			return coll;
		}
        public Favorites()
        {
            InitializeComponent();
            LoadWatcher();
            map1.LogoVisibility = Visibility.Collapsed;
            map1.CopyrightVisibility = Visibility.Collapsed;
            map1.Mode = new AerialMode();
            map1.ZoomLevel = 5;
            map1.ZoomBarVisibility = System.Windows.Visibility.Visible;

            var settings = IsolatedStorageSettings.ApplicationSettings;
            if (settings.Contains("favorites"))
            {
                var location = settings["favorites"].ToString();
                latitude = double.Parse(location.Substring(0, location.IndexOf(",") - 1));
                longtitude =  double.Parse(location.Substring(location.IndexOf(",") + 1));
                var locationsList = new LocationCollection();
                //locationsList.Add(new GeoCoordinate(56.5845698,40.5489514));
                //locationsList.Add(new GeoCoordinate(60.4885213, 80.785426));
                locationsList.Add(new GeoCoordinate(latitude,longtitude));
                locationsList.Add(new GeoCoordinate(latitude+0.85412, longtitude+0.12564));
                MapPolyline polyline = new MapPolyline();
                polyline.Stroke = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Colors.Black);
                polyline.StrokeThickness = 5;
                polyline.Opacity = 0.8;
                polyline.Locations = locationsList;

                //Pushpin pin = new Pushpin();

                //MessageBox.Show(location.Substring(0, location.IndexOf(",") - 1) + " \n  " + location.Substring(location.IndexOf(",") + 1));
                ////---set the location for the pushpin---
                //pin.Location = new GeoCoordinate(double.Parse(location.Substring(0, location.IndexOf(",") - 1)), double.Parse(location.Substring(location.IndexOf(",") + 1)));
                //pin.Name = "tmp";

                ////---add the pushpin to the map---

                //pin.Content = new Ellipse()
                //{
                //    //Fill = image,

                //    StrokeThickness = 10,
                //    Height = 100,
                //    Width = 100
                //};
                //pin.MouseLeftButtonUp += new MouseButtonEventHandler(Pushpin_MouseLeftButtonUp);

                //---add the pushpin to the map---
                map1.Children.Add(polyline);

                MessageBox.Show(location.ToString());
            }

            // settings["myemail"] = "*****@*****.**";
        }
Example #53
0
        public Edge(ListeningStation from, ListeningStation to, double value)
        {
            ID = from.ID + " - " + to.ID;
            Name = from.Name + " - " + to.Name;

            LocationCollection vertices = new LocationCollection();
            vertices.Add(from.Location);
            vertices.Add(to.Location);
            Vertices = vertices;

            Value = value;
        }
        public static void yolIstek (LocationCollection locations)
        {

            RouteRequest routeRequest = new RouteRequest();
            routeRequest.Culture = new System.Globalization.CultureInfo("en-US");
            routeRequest.Options.RoutePathType = RoutePathType.Points;
            for (int i = 0; i < locations.Count;i++)
            {
                routeRequest.Waypoints.Add(locations[i]);
            }
            yolAniProvider.CalculateRouteAsync(routeRequest);
        }
        public object Convert(object value, System.Type targetType, object parameter, CultureInfo culture)
        {
            var pathPoints = (Point[])value;

            var locations = new LocationCollection();
            foreach (var pathPoint in pathPoints)
            {
                locations.Add(pathPoint.AsGeoCoordinate());
            }

            return locations;
        }
 public static LocationCollection LocationRectToLocationCollection(LocationRect locationRect)
 {
     var locations = new LocationCollection
                         {
                             locationRect.Northwest,
                             locationRect.Southwest,
                             locationRect.Southeast,
                             locationRect.Northeast,
                             locationRect.Northwest
                         };
     return locations;
 }
Example #57
0
        public void NullValueIfRandomPointWithinPolygonWithTwoVertices()
        {
            var twoVertices = new LocationCollection
                               {
                                   new Location(1, 2),
                                   new Location(3, 4)
                               };

            var actual = GeoUtilities.RandomLocationWithinPolygon(twoVertices);

            Assert.Null(actual);
        }
        public static LocationCollection ToCoordinates(this IEnumerable<Location> points)
        {
            var locations = new LocationCollection();

            if (points != null)
            {
                foreach (var point in points)
                {
                    locations.Add(point.ToCoordinate());
                }
            }

            return locations;
        }
Example #59
0
        /// <summary>
        /// Creates the star points.
        /// </summary>
        /// <param name="center">The center.</param>
        /// <returns>The star points.</returns>
        private LocationCollection CreateStarPoints(Location center )
        {
            var locations = new LocationCollection();
              var ir = InnerRadius / 200000;
              var or = OuterRadius / 200000;
              var angle = Math.PI / Arms;

              for (var i = 0; i <= 2 * Arms; i++)
              {
            var r = (i & 1) == 0 ? or : ir;
            locations.Add(new Location(center.Latitude + ((Math.Cos(i * angle) * r) * NorthCompressionFactor), center.Longitude + (Math.Sin(i * angle) * r)));
              }

              return locations;
        }
Example #60
0
        private void BuildPolyline()
        {
            LocationCollection points = new LocationCollection();
            points.Add(new Location(40, -100));
            points.Add(new Location(41, -101));
            points.Add(new Location(40, -102));
            points.Add(new Location(43, -103));
            points.Add(new Location(45, -97));

            MapPolyline polyline = new MapPolyline();
            polyline.Points = points;

            this.polylineLayer.Items.Add(polyline);
            this.BuildPoints(polyline);
        }