public double[] GetWeights(
            double minArea, double maxArea,
            double minPricePerYear, double maxPricePerYear,
            double minDistanceTowardsMetroEntrance, double maxDistanceTowardsMetroEntrance,
            double minDistanceTowardsStation, double maxDistanceTowardsStation,
            double minDistanceTowardsCenter, double maxDistanceTowardsCenter,
            double minDegreeBearingTowardsCenter, double maxDegreeBearingTowardsCenter,
            GeoJsonPoint <GeoJson2DGeographicCoordinates> moscowCenter)
        {
            var weights = new List <double>
            {
                (Area - minArea) / (maxArea - minArea),
                (PricePerYear - minPricePerYear) / (maxPricePerYear - minPricePerYear),
                (DistanceTowardsMetroEntrance - minDistanceTowardsMetroEntrance) /
                (maxDistanceTowardsMetroEntrance - minDistanceTowardsMetroEntrance),
                (DistanceTowardsStation - minDistanceTowardsStation) /
                (maxDistanceTowardsStation - minDistanceTowardsStation),
                (GeoHelpers.CalcDistance(GeoPoint, moscowCenter) - minDistanceTowardsCenter) /
                (maxDistanceTowardsCenter - minDistanceTowardsCenter),
                (GeoHelpers.DegreeBearing(GeoPoint, moscowCenter) - minDegreeBearingTowardsCenter)
                / (maxDegreeBearingTowardsCenter - minDegreeBearingTowardsCenter)
            };

            return(weights.ToArray());
        }
Пример #2
0
        // [DebuggerStepThrough]
        static async void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            await Task.Run(() =>
            {
                var loc = GeoHelpers.GetMyGeoLocation().Result;
                e.Exception.ToExceptionless().MarkAsCritical().AddTags(MetaManager.ProductName).SetUserIdentity(CurrentUser.UserName, CurrentUser.EmailAdress).SetVersion(MetaManager.CurrentVersion).SetGeo(loc.Key, loc.Value).Submit();
                DebugHelper.WriteException(e.Exception);

                if (e.Exception.GetType() == typeof(SecurityException))
                {
                    MessageBox.Show("Permission Refusée");
                }
                else if (e.Exception.GetType() == typeof(InvalidOperationException))
                {
                    MessageBox.Show(e.Exception.Message, "Not Handled Exception");
                }
                else if (e.Exception.GetType() == typeof(NullReferenceException))
                {
                    DebugHelper.WriteException(e.Exception);
                }
                //MessageBox.Show(e.Exception.Message, "Not Handled Exception");
                else if (e.Exception.GetType() == typeof(ArgumentNullException))
                {
                    DebugHelper.WriteException(e.Exception);
                }
                //MessageBox.Show(e.Exception.Message, "Not Handled Exception");
                else
                {
                    MessageBox.Show(e.Exception.Message, "Not Handled Exception");
                }

                e.Handled = true;
                //Current.Shutdown();
            });
        }
Пример #3
0
        public void UpdateCamera()
        {
            Transform cameraTransform = currentCamera.transform;
            float     y = GeoHelpers.OsmZoomLevelToMapScale(currentZoom, 0.0f, tileResolution, 72) / scaleDivider * screenScale;

            cameraTransform.position = Quaternion.Euler(new Vector3(-CameraPitch, -CameraYaw, 0.0f)) * (Vector3.up * y);
            cameraTransform.rotation = Quaternion.Euler(new Vector3(90.0f - CameraPitch, -CameraYaw, 0.0f));
        }
Пример #4
0
        /// <summary>
        /// Gets the center tile. See <see cref="UnitySlippyMap.Layers.TileLayerBehaviour.GetCenterTile"/>.
        /// </summary>
        /// <param name="tileCountOnX">Tile count on x.</param>
        /// <param name="tileCountOnY">Tile count on y.</param>
        /// <param name="tileX">Tile x.</param>
        /// <param name="tileY">Tile y.</param>
        /// <param name="offsetX">Offset x.</param>
        /// <param name="offsetZ">Offset z.</param>
        protected override void GetCenterTile(int tileCountOnX, int tileCountOnY, out int tileX, out int tileY, out float offsetX, out float offsetZ)
        {
            int[]    tileCoordinates  = GeoHelpers.WGS84ToTile(Map.CenterWGS84 [0], Map.CenterWGS84 [1], Map.RoundedZoom);
            double[] centerTile       = GeoHelpers.TileToWGS84(tileCoordinates [0], tileCoordinates [1], Map.RoundedZoom);
            double[] centerTileMeters = Map.WGS84ToEPSG900913Transform.Transform(centerTile);              //GeoHelpers.WGS84ToMeters(centerTile[0], centerTile[1]);

            tileX   = tileCoordinates [0];
            tileY   = tileCoordinates [1];
            offsetX = Map.RoundedHalfMapScale / 2.0f - (float)(Map.CenterEPSG900913 [0] - centerTileMeters [0]) * Map.RoundedScaleMultiplier;
            offsetZ = -Map.RoundedHalfMapScale / 2.0f - (float)(Map.CenterEPSG900913 [1] - centerTileMeters [1]) * Map.RoundedScaleMultiplier;
        }
Пример #5
0
        public Task <List <Covid19Summary> > GetSummaryAsync()
        {
            var tsk = Task <List <Covid19Summary> > .Factory.StartNew(() =>
            {
                Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("EN-us");
                var datas = new List <Covid19Summary>();
                if (File.Exists(CsvDataPath))
                {
                    try
                    {
                        CsvParserOptions csvParserOptions = new CsvParserOptions(true, ',');
                        Covid19InfoMapping csvMapper      = new Covid19InfoMapping();
                        CsvParser <Covid19Info> csvParser = new CsvParser <Covid19Info>(csvParserOptions, csvMapper);
                        var result = new List <Covid19Info>();
                        csvParser.ReadFromFile(CsvDataPath, Encoding.UTF8).ToList().ForEach(x => result.Add(x.Result));

                        var Provinces = (from x in result
                                         select x.Province).Distinct().ToList();
                        int counter = 0;
                        foreach (var province in Provinces)
                        {
                            counter++;
                            var sumData = result.Where(x => x.Province == province);
                            var loc     = GeoHelpers.GetLocationFromAddress($"{province}, {sumData.FirstOrDefault().Country}");
                            var newItem = new Covid19Summary()
                            {
                                No         = counter,
                                Confirmed  = sumData.Sum(x => x.Confirmed),
                                Death      = sumData.Sum(x => x.Death),
                                Recovered  = sumData.Sum(x => x.Recovered),
                                LastUpdate = sumData.OrderByDescending(x => x.LastUpdate).FirstOrDefault().LastUpdate,
                                Country    = sumData.FirstOrDefault().Country,
                                Province   = province,
                                Lat        = loc.lat,
                                Lon        = loc.lon
                            };
                            datas.Add(newItem);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex);
                        return(datas);
                    }
                }
                else
                {
                    throw new Exception("there is no csv file in the path");
                }
                return(datas);
            });

            return(tsk);
        }
Пример #6
0
    protected override string GetTileURL(int tileX, int tileY, int roundedZoom)
    {
        double[] tile       = GeoHelpers.TileToWGS84(tileX, tileY, roundedZoom);
        double[] tileMeters = Map.WGS84ToEPSG900913Transform.Transform(tile); //GeoHelpers.WGS84ToMeters(tile[0], tile[1]);
        float    tileSize   = Map.TileResolution * Map.RoundedMetersPerPixel;

        double[] min = Map.EPSG900913ToWGS84Transform.Transform(new double[2] {
            tileMeters[0], tileMeters[1] - tileSize
        });                                                                                                                 //GeoHelpers.MetersToWGS84(xmin, ymin);
        double[] max = Map.EPSG900913ToWGS84Transform.Transform(new double[2] {
            tileMeters[0] + tileSize, tileMeters[1]
        });                                                                                                                 //GeoHelpers.MetersToWGS84(xmax, ymax);
        return(baseURL + (baseURL.EndsWith("?") ? "" : "?") + "SERVICE=WMS&REQUEST=GetMap&VERSION=1.1.1&LAYERS=" + layers + "&STYLES=&SRS=" + srsName + "&BBOX=" + min[0] + "," + min[1] + "," + max[0] + "," + max[1] + "&WIDTH=" + Map.TileResolution + "&HEIGHT=" + Map.TileResolution + "&FORMAT=" + format);
    }
Пример #7
0
    private void UpdateInternals()
    {
        // FIXME: the half map scale is a value used throughout the implementation to rule the camera elevation
        // and the size/scale of the tiles, it depends on fixed tile size and resolution (here 256 and 72) so I am not
        // sure it would work for a tile layer with different values...
        // maybe there is a way to take the values out of the calculations and reintroduce them on Layer level...
        // FIXME: the 'division by 20000' helps the values to be kept in range for the Unity3D engine, not sure
        // this is the right approach either, feels kinda voodooish...
        halfMapScale        = GeoHelpers.OsmZoomLevelToMapScale(currentZoom, /*(float)centerWGS84[1]*/ 0.0f, tileResolution, 72) / scaleDivider;
        roundedHalfMapScale = GeoHelpers.OsmZoomLevelToMapScale(roundedZoom, (float)/*(float)centerWGS84[1]*/ 0.0f, tileResolution, 72) / scaleDivider;

        metersPerPixel        = GeoHelpers.MetersPerPixel(0.0f, (float)currentZoom);
        roundedMetersPerPixel = GeoHelpers.MetersPerPixel(0.0f, (float)roundedZoom);

        // FIXME: another voodoish value to help converting meters (EPSG 900913) to Unity3D world coordinates
        scaleMultiplier        = halfMapScale / (metersPerPixel * tileResolution);
        roundedScaleMultiplier = roundedHalfMapScale / (roundedMetersPerPixel * tileResolution);
    }
        /// <summary>
        /// Zooms the map at the specified zoomSpeed.
        /// </summary>
        /// <param name="zoomSpeed">Zoom speed.</param>
        public void Zoom(float zoomSpeed)
        {
            // apply the zoom
            CurrentZoom += 4.0f * zoomSpeed * Time.deltaTime;

            // move the camera
            // FIXME: the camera jumps on the first zoom when tilted, because the cam altitude and zoom value are unsynced by the rotation
            Transform cameraTransform = currentCamera.transform;
            float     y = GeoHelpers.OsmZoomLevelToMapScale(currentZoom, 0.0f, tileResolution, 72) / scaleDivider * screenScale;
            float     t = y / cameraTransform.forward.y;

            cameraTransform.position = new Vector3(
                t * cameraTransform.forward.x,
                y,
                t * cameraTransform.forward.z);

            // set the update flag to tell the behaviour the user is manipulating the map
            hasMoved = true;
            IsDirty  = true;
        }
        // - Implementation of: https://github.com/mapbox/utfgrid-spec by [email protected]

        /// <summary>
        /// Gets utf grid data from the layer .mbtiles file representing the tile > pixel location directly below the mouse pointer.
        /// </summary>
        /// <value>JSON formatted string from the mbtiles file's utf grid data.</value>
        public string UtfGridJsonString()
        {
            if (Map.CurrentZoom > maxZoom ||
                Map.CurrentZoom < minZoom)
            {
                return(null);
            }

            RaycastHit[] _raycastHits;
            Ray          _ray = Map.CurrentCamera.ScreenPointToRay(UnityEngine.Input.mousePosition);

            _raycastHits = Physics.RaycastAll(_ray);

            RaycastHit _tileHit   = new RaycastHit();
            bool       _tileFound = false; // RaycastHit is not nullable so we need a flag to check against

            foreach (RaycastHit _rch in _raycastHits)
            {
                // make sure it's a tile
                if (_rch.transform.GetComponent <TileBehaviour>() != null)
                {
                    // don't bother if the renderer is off
                    if (_rch.transform.GetComponent <MeshRenderer>().enabled == true)
                    {
                        _tileHit = _rch;

                        _tileFound = true;

#if DEBUG_LOG
                        Debug.Log("Using tile: " + _tileHit.transform.name);
#endif

                        break;
                    }
                }
            }

            if (!_tileFound)
            {
#if DEBUG_LOG
                Debug.LogWarning("No suitable tile found.");
#endif
                return(null);
            }

            double[] _locWgs84 = GeoHelpers.RaycastHitToWGS84(Map, _tileHit);

            // there's no sensible way to resolve _raycastHits[_hitIndex] to a tile location (z,x,y) so we'll get it here using WGS84ToTile
            int[] _tileLoc = UnitySlippyMap.Helpers.GeoHelpers.WGS84ToTile(_locWgs84[0], -_locWgs84[1], Map.RoundedZoom);

            _tileLoc = new int[3] {
                _tileLoc[0], _tileLoc[1], Map.RoundedZoom
            };

            // Use the tile location to get the grid blob containing the utf keys
            DataTable dt;

            string _query = string.Format("SELECT grid FROM grids WHERE zoom_level={0} AND tile_column={1} AND tile_row={2}", _tileLoc[2], _tileLoc[0], _tileLoc[1]);

#if DEBUG_LOG
            Debug.Log("Executing query: " + _query);
#endif

            try
            {
                dt = db.ExecuteQuery(_query);
            }
            catch (Exception e)
            {
#if DEBUG_LOG
                Debug.LogWarning("No utf data? " + e);
#endif

                // make sure the sql shiznit can continue to be used for getting tile images
                Close(); Open();

                return(null);
            }

            if (dt.Rows.Count == 0)
            {
#if DEBUG_LOG
                Debug.LogWarning(String.Format("No utf grid blob data returned for tile: x={0}, y={1}, zoom={2}.", _tileLoc[2], _tileLoc[0], _tileLoc[1]));
#endif
            }

            byte[] _gridBlobBytes = (byte[])dt.Rows[0]["grid"];

            // decompress the bytes to a json string
            string _jsonString = Zip.DecompressGzipJsonBytes(_gridBlobBytes);

#if DEBUG_LOG
            Debug.Log("JSON char key string exctracted:\n" + _jsonString);
#endif

            // - NOTE: I'd prefer to use Newtonsoft.Json.dll for this and deserialise it to a class
            // object, but the lib is ~500KB of additional data. So, I'm using SimpleJson as it is tiny
            // at only 33KB and can be found here: http://wiki.unity3d.com/index.php/SimpleJSON
            SimpleJSON.JSONNode _jsonData = SimpleJSON.JSON.Parse(_jsonString);

            string _tileKey = TileBehaviour.GetTileKey(_tileLoc[2], _tileLoc[0], _tileLoc[1]);

            if (!tiles.ContainsKey(_tileKey))
            {
#if DEBUG_LOG
                Debug.LogWarning("No tile found for key: " + _tileKey);
#endif

                return(null);
            }
            else
            {
                TileBehaviour _tile = tiles[_tileKey];

                int _res      = _jsonData["grid"].Count;
                int _tileSize = 256; // pixel resolution of the tile image

                Vector3 _invPt = _tileHit.transform.InverseTransformPoint(_tileHit.point);

                int _px = Mathf.FloorToInt(256 * (_invPt.x + 0.5f));
                int _py = Mathf.FloorToInt(256 * (_invPt.z + 0.5f));

                int _x = Mathf.FloorToInt(_px / (_tileSize / _res));
                int _y = Mathf.FloorToInt(_py / (_tileSize / _res));

                // the y order is top down, reverse it
                _y = (_res - _y) - 1;
                _x--;

#if DEBUG_LOG
                Debug.Log(string.Format("Finding utf data for pixel {0}, {1}...", _x, _y));
#endif

                // try to get the key from the json data
                char _charKey;
                try
                {
                    _charKey = ((string)_jsonData["grid"][_y])[_x];
                }
                catch (Exception e)
                {
#if DEBUG_LOG
                    Debug.LogWarning(string.Format("Could not retrive char key {0}, {1} - {2}", _x, _y, e));
#endif

                    return(null);
                }

                string _hexValue = Convert.ToInt32(_charKey).ToString("X");

                //if (_charKey == ' ')
                //return null;

                int _resolvedkey = ResolveCode(int.Parse(_hexValue, System.Globalization.NumberStyles.HexNumber));

                _resolvedkey--; // ?!?

                string _gridDataKey = _jsonData["keys"][_resolvedkey].ToString().Replace("\"", "");

                if (_gridDataKey != null)
                {
                    _query = string.Format("SELECT key_json FROM grid_data WHERE key_name=\"{0}\" AND zoom_level={1} AND tile_column={2} AND tile_row={3}", _gridDataKey, _tileLoc[2], _tileLoc[0], _tileLoc[1]);

#if DEBUG_LOG
                    Debug.Log("Executing sql query: " + _query);
#endif

                    try
                    {
                        dt = db.ExecuteQuery(_query);
                    }
                    catch (Exception e)
                    {
#if DEBUG_LOG
                        Debug.LogWarning("Could not resolve key: " + _gridDataKey + ". - " + e);
#endif

                        // make sure the sql shiznit can continue to be used for getting tile images
                        Close(); Open();

                        return(null);
                    }

                    if (dt.Rows.Count != 0)
                    {
                        string _returnString = (string)dt.Rows[0]["key_json"];

#if DEBUG_LOG
                        Debug.Log("Successfully retrieved json data from utf grid: " + _returnString);
#endif

                        return(_returnString);
                    }
                    else
                    {
#if DEBUG_LOG
                        Debug.LogWarning("UTF data table contained no rows.");
#endif

                        return(null);
                    }
                }
                else
                {
#if DEBUG_LOG
                    Debug.LogWarning("The returned char key was null or invalid");
#endif

                    return(null);
                }
            }
        }
        private void RenderDuplicatesList(OrganizationServiceContext context, Guid viewId, string latitudeFieldName, string longitudeFieldName, double latitude, double longitude, double distance)
        {
            var savedQueryView = new SavedQueryView(context, viewId, LanguageCode);

            var angularDistance        = distance / GeoHelpers.EarthRadiusInKilometers;
            var originLatitudeRadians  = GeoHelpers.DegreesToRadians(latitude);
            var originLongitudeRadians = GeoHelpers.DegreesToRadians(longitude);
            var minLatitudeRadians     = originLatitudeRadians - angularDistance;
            var maxLatitudeRadians     = originLatitudeRadians + angularDistance;
            var deltaLongitude         = Math.Asin(Math.Sin(angularDistance) / Math.Cos(originLatitudeRadians));
            var minLongitudeRadians    = originLongitudeRadians - deltaLongitude;
            var maxLongitudeRadians    = originLongitudeRadians + deltaLongitude;
            var minLatitude            = GeoHelpers.RadiansToDegrees(minLatitudeRadians);
            var maxLatitude            = GeoHelpers.RadiansToDegrees(maxLatitudeRadians);
            var minLongitude           = GeoHelpers.RadiansToDegrees(minLongitudeRadians);
            var maxLongitude           = GeoHelpers.RadiansToDegrees(maxLongitudeRadians);

            var minLatitudeCondition = new XElement("condition",
                                                    new XAttribute("attribute", latitudeFieldName),
                                                    new XAttribute("operator", "ge"),
                                                    new XAttribute("value", minLatitude));

            var maxLatitudeCondition = new XElement("condition",
                                                    new XAttribute("attribute", latitudeFieldName),
                                                    new XAttribute("operator", "le"),
                                                    new XAttribute("value", maxLatitude));

            var minLongitudeCondition = new XElement("condition",
                                                     new XAttribute("attribute", longitudeFieldName),
                                                     new XAttribute("operator", "ge"),
                                                     new XAttribute("value", minLongitude));

            var maxLongitudeCondition = new XElement("condition",
                                                     new XAttribute("attribute", longitudeFieldName),
                                                     new XAttribute("operator", "le"),
                                                     new XAttribute("value", maxLongitude));

            var notCurrentServiceRequest = new XElement("condition",
                                                        new XAttribute("attribute", PreviousStepEntityPrimaryKeyLogicalName),
                                                        new XAttribute("operator", "ne"),
                                                        new XAttribute("value", PreviousStepEntityID));

            savedQueryView.FetchXml.Element("entity").Add(new XElement("filter", new XAttribute("type", "and"), notCurrentServiceRequest,
                                                                       minLatitudeCondition, maxLatitudeCondition, minLongitudeCondition, maxLongitudeCondition));

            var viewConfiguration = new ViewConfiguration(savedQueryView)
            {
                DataPagerEnabled = false,
                FetchXml         = savedQueryView.FetchXml.ToString(),
                LanguageCode     = LanguageCode,
                PortalName       = PortalName
            };

            var response = context.Execute(new RetrieveMultipleRequest {
                Query = new FetchExpression(viewConfiguration.FetchXml.ToString())
            }) as RetrieveMultipleResponse;

            if (!response.EntityCollection.Entities.Any())
            {
                _isUnique = true;
                MoveToNextStep(PreviousStepEntityID);
                return;
            }

            var crmEntityListView = new CrmEntityListView
            {
                ID                 = "DuplicateList",
                LanguageCode       = LanguageCode,
                PortalName         = PortalName,
                ViewConfigurations = new List <ViewConfiguration> {
                    viewConfiguration
                },
                ListCssClass = "table table-striped",
                SelectMode   = EntityGridExtensions.GridSelectMode.Single
            };

            DuplicateListPlaceholder.Controls.Add(crmEntityListView);
        }
Пример #11
0
 public float GetRoundedHalfMapScale(int zoom)
 {
     return(GeoHelpers.OsmZoomLevelToMapScale(zoom, 0.0f, tileResolution, 72) / scaleDivider);
 }