Example #1
0
        /// <summary>
        /// Calculate WGS84 coordinates from Cartesian
        /// </summary>
        /// <param name="p"> Cartesian coordenates of the object</param>
        /// <param name="SIC">SIC of the radar which detected the object, to know which radar is and where it's placed </param>
        /// <returns>Object WGS84 coordinates</returns>
        public PointLatLng ComputeWGS_84_from_Cartesian(Point p, string SIC)
        {
            PointLatLng      pos             = new PointLatLng();
            double           X               = p.X;
            double           Y               = p.Y;
            CoordinatesXYZ   ObjectCartesian = new CoordinatesXYZ(X, Y, 0);                                                                  //We pass from Point to CoordinatesXYZ to be able to work with the GeoUtils library
            PointLatLng      AirportPoint    = GetCoordenatesSMRMALT(Convert.ToInt32(SIC));                                                  //We get the Radar coordinates from its SIC
            CoordinatesWGS84 AirportGeodesic = new CoordinatesWGS84(AirportPoint.Lat * (Math.PI / 180), AirportPoint.Lng * (Math.PI / 180)); //We went from PointLatLng to Coordinates WGS84 to be able to work with GeoUtils. Coordinates must be passed from degrees to radians
            GeoUtils         geoUtils        = new GeoUtils();
            CoordinatesWGS84 MarkerGeodesic  = geoUtils.change_system_cartesian2geodesic(ObjectCartesian, AirportGeodesic);                  //We apply the change from CoordiantesXYZ to Coordinate GS83

            geoUtils = null;
            double LatitudeWGS_84_map  = MarkerGeodesic.Lat * (180 / Math.PI);
            double LongitudeWGS_84_map = MarkerGeodesic.Lon * (180 / Math.PI);

            pos.Lat = LatitudeWGS_84_map;
            pos.Lng = LongitudeWGS_84_map;
            return(pos);
        }
Example #2
0
        /// <summary>
        /// Функция выполняет формирование полигона по идентификаторам узлов
        /// </summary>
        /// <param name="nodes">Итератор над набором узлов</param>
        /// <param name="ids">Идентификаторы узлов для выборки</param>
        /// <returns></returns>
        private static DbGeography GetPolygonFromNodesIds(XPathNodeIterator nodes, IEnumerable <long> ids)
        {
            if (!nodes.MoveNext())
            {
                return(null);
            }
            var latLonPoints = new StringBuilder();
            var selectExpr   = new StringBuilder("//node[");

            var idsarr = ids as long[] ?? ids.ToArray();

            for (var i = 0; i < idsarr.Length; i++)
            {
                selectExpr.Append($"@id={idsarr[i]}");
                selectExpr.Append(i != idsarr.Length - 1 ? " or " : "]");
            }

            var selectedNodes = nodes.Current.Select(selectExpr.ToString());

            for (var i = 0; i < idsarr.Length; i++)
            {
                var node = selectedNodes.Current.SelectSingleNode($"//node[@id={idsarr[i]}]");

                if (node == null)
                {
                    continue;
                }
                if (node.HasChildren && node.InnerXml.Contains("entrance"))
                {
                    continue;
                }

                var lat = node.GetAttribute("lat", "");
                latLonPoints.Append(lat);
                latLonPoints.Append(" ");
                var lon = node.GetAttribute("lon", "");
                latLonPoints.Append(lon);
                latLonPoints.Append(" ");
            }

            return(GeoUtils.CreatePolygon(latLonPoints.ToString()));
        }
        public bool IsIntersect(ref GeoRay2 dist, ref GeoInsectPointArrayInfo insect)
        {
            bool isInsect = GeoRayUtils.IsRayInsectTriangle2(dist.mOrigin, dist.mDirection, mP1, mP2, mP3, ref insect);

            if (isInsect)
            {
                insect.mHitObject2 = this;
                float min = 1e5f;
                foreach (Vector3 v in insect.mHitGlobalPoint.mPointArray)
                {
                    float len = (GeoUtils.ToVector2(v) - dist.mOrigin).magnitude;
                    if (len < min)
                    {
                        min = len;
                    }
                }
                insect.mLength = min;
            }
            return(isInsect);
        }
        /// <inheritdoc />
        protected override string GetUri(QuadKey quadKey)
        {
            // TODO tile can cross more than one srtm cell: need load more.
            var prefix = GetFileNamePrefix(GeoUtils.QuadKeyToBoundingBox(quadKey).Center());

            foreach (var line in _fileSystemService.ReadText(_schemaPath).Split('\n'))
            {
                if (line.StartsWith(prefix))
                {
                    var parameters = line.Split(' ');
                    // NOTE some of files miss extension point between name and .hgt.zip
                    return(String.Format("{0}/{1}/{2}", _server, ContinentMap[int.Parse(parameters[1])],
                                         parameters[1].EndsWith("zip") ? "" : parameters[0] + ".hgt.zip"));
                }
            }

            _trace.Warn(TraceCategory, String.Format("Cannot find {0} on {1}", prefix, _schemaPath));

            return(null);
        }
Example #5
0
        public void CanLoadAtBirdEyeLevelOfDetails()
        {
            // ARRANGE
            int lod = 14;

            SetupMapData(TestHelper.BerlinXmlData, lod);
            var count         = 1;
            var centerQuadKey = GeoUtils.CreateQuadKey(TestHelper.WorldZeroPoint, lod);

            // ACT & ASSERT
            for (var y = 0; y < count; ++y)
            {
                for (var x = 0; x < count; ++x)
                {
                    LoadQuadKeySync(new QuadKey(centerQuadKey.TileX + x, centerQuadKey.TileY + y, lod));
                }
            }

            Assert.IsTrue(_isCalled);
        }
        public static void UpdateRouteToTarget(GeoUtils sourceLocation, GeoUtils destinationLocation)
        {
            _routeToTarget = null;

            List <PointLatLng> points = new List <PointLatLng>();

            points.Add(new PointLatLng(sourceLocation.Latitude, sourceLocation.Longitude));
            points.Add(new PointLatLng(destinationLocation.Latitude, destinationLocation.Longitude));

            if (_routeToTarget == null)
            {
                GMapOverlay polyOverlay = new GMapOverlay("RouteToTarget");

                _routeToTarget        = new GMapPolygon(points, "mypolygon");
                _routeToTarget.Fill   = new SolidBrush(Color.FromArgb(50, Color.Red));
                _routeToTarget.Stroke = new Pen(Color.Red, 3);
                polyOverlay.Polygons.Add(_routeToTarget);
                gmap.Overlays.Add(polyOverlay);
            }
        }
Example #7
0
        private void updateLocationInfo(string key, GeoLocation location)
        {
            LocationInfo oldInfo         = GeoUtils.getMapSafe(key, locationInfos);
            bool         isNew           = (oldInfo == null);
            bool         changedLocation = (oldInfo != null && !oldInfo.location.Equals(location));
            bool         wasInQuery      = (oldInfo != null && oldInfo.inGeoQuery);

            bool isInQuery = this.locationIsInQuery(location);

            if ((isNew || !wasInQuery) && isInQuery)
            {
                foreach (GeoQueryEventListener listener in this.eventListeners)
                {
                    this.geoFire.raiseEvent(() => {
                        listener.onKeyEntered(key, location);
                    });
                }
            }
            else if (!isNew && changedLocation && isInQuery)
            {
                foreach (GeoQueryEventListener listener in this.eventListeners)
                {
                    this.geoFire.raiseEvent(() => {
                        listener.onKeyMoved(key, location);
                    });
                }
            }
            else if (wasInQuery && !isInQuery)
            {
                foreach (GeoQueryEventListener listener in this.eventListeners)
                {
                    this.geoFire.raiseEvent(() => {
                        listener.onKeyExited(key);
                    });
                }
            }
            LocationInfo newInfo = new LocationInfo(location, this.locationIsInQuery(location));

            //this.locationInfos.Add(key, newInfo);
            GeoUtils.setMapSafe(key, newInfo, locationInfos);
        }
        public async Task <List <Cliente> > GetClientForPosition(Position posicion)
        {
            db.Configuration.ProxyCreationEnabled = false;
            var clientes = await db.Cliente.ToListAsync();

            List <Cliente> Clientes = new List <Cliente>();

            foreach (var cliente in clientes)
            {
                var cposition = new Position
                {
                    latitude  = cliente.Lat,
                    longitude = cliente.Lon
                };
                if (GeoUtils.EstaCercaDeMi(posicion, cposition, 0.1))
                {
                    Clientes.Add(cliente);
                }
            }
            return(Clientes);
        }
Example #9
0
        private HashSet <string> GetCodesFromGeo(string bbox)
        {
            var envelope = GeoUtils.ToEnvelope(bbox);

            var codesFromPoints    = _kdTree.Query(envelope);
            var codesFromEnvelopes = _stRtree.Query(envelope);

            HashSet <string> codesFromGeo = new HashSet <string>();

            foreach (var code in codesFromPoints)
            {
                codesFromGeo.Add(code.Data);
            }

            foreach (var code in codesFromEnvelopes)
            {
                codesFromGeo.Add(code);
            }

            return(codesFromGeo);
        }
        private void TrySearchButton_Click(object sender, RoutedEventArgs e)
        {
            var button = sender as System.Windows.Controls.Button;

            button.IsEnabled = false;
            //Thread.Sleep(100);
            var admName            = TrySearchAdmAreaName.Text;
            var lonlatExtentString = GeoUtils.GetLonLatExtentStringFromAdministrativeByTdt(admName);

            if (ProjectionSelect.SelectedItem == WebMctCbi)
            {
                var webMctExtentString = GeoUtils.LonLatExtentStringToWebMctExtentString(lonlatExtentString);
                ExtentInputTextBox.Text = webMctExtentString;
            }
            else
            {
                ExtentInputTextBox.Text = lonlatExtentString;
            }

            button.IsEnabled = true;
        }
Example #11
0
        public async Task <List <Cliente> > GetClientForPosition(NearClientRequest posicion)
        {
            db.Configuration.ProxyCreationEnabled = false;
            var clientes = await db.Cliente.Where(x => x.IdVendedor == posicion.myId).ToListAsync();

            List <Cliente> Clientes = new List <Cliente>();

            foreach (var cliente in clientes)
            {
                var cposition = new Position
                {
                    latitude  = cliente.Latitud,
                    longitude = cliente.Longitud
                };
                if (GeoUtils.EstaCercaDeMi(posicion.Position, cposition, posicion.radio))
                {
                    Clientes.Add(cliente);
                }
            }
            return(Clientes);
        }
Example #12
0
        public void ParseDataset(string datasetDirectory, Dictionary <string, BreastCancerSampleItem> sampleMap)
        {
            var files = GeoUtils.GetGsmNameFileMap(datasetDirectory);

            var dirname = Path.GetFileName(datasetDirectory);

            var map = new RawSampleInfoReader().ReadDescriptionFromDirectory(datasetDirectory);

            foreach (var key in map.Keys)
            {
                if (files.ContainsKey(key.ToLower()))
                {
                    if (!sampleMap.ContainsKey(key))
                    {
                        sampleMap[key] = new BreastCancerSampleItem(dirname, key);
                    }

                    var sample = sampleMap[key];

                    var qsMap = map[key];

                    //parse information
                    foreach (var question in qsMap.Keys)
                    {
                        if (converters.ContainsKey(question))
                        {
                            var converter = converters[question];
                            var answer    = qsMap[question].First();
                            converter.SetProperty(sample, answer);
                        }
                    }

                    //set defaultvalue
                    foreach (var dfConverter in defaultConverters)
                    {
                        dfConverter.Key.SetProperty(sample, dfConverter.Value);
                    }
                }
            }
        }
        public void DisplayFeatures(SharpMap.Geometries.Point point, List <FeatureDataRowLayerPair> rows)
        {
            lblPosition.Content = String.Format("Info at: {0} - {1}", GeoUtils.DecDegToDMS(point.X, CoordinateType.Longitude), GeoUtils.DecDegToDMS(point.Y, CoordinateType.Latitude));

            _model = new ObservableCollection <FeatureDataElement>();
            foreach (FeatureDataRowLayerPair info in rows)
            {
                foreach (DataColumn col in info.FeatureDataRow.Table.Columns)
                {
                    var item = new FeatureDataElement {
                        Name = col.ColumnName, Value = info.FeatureDataRow[col.ColumnName].ToString(), LayerName = info.Layer.LayerName
                    };
                    _model.Add(item);
                }
            }

            lvw.ItemsSource = _model;

            CollectionView myView = (CollectionView)CollectionViewSource.GetDefaultView(lvw.ItemsSource);

            myView.GroupDescriptions.Add(new PropertyGroupDescription("LayerName"));
        }
Example #14
0
        private Poi ChoosePoi(
            GeoPoint center,
            double distance,
            List <Poi> pois,
            User user,
            List <IdFoundRecord> lastCategories,
            List <IdFoundRecord> lastTags
            )
        {
            if (pois.Count == 0)
            {
                return(null);
            }

            // filter poi by visited
            pois = pois.Where(p => !user.PoiSaved.ContainsKey(p.Id) || !user.PoiSaved[p.Id].Visited).ToList();

            // store categories and tagsweights
            // var catWeights = ConvertToWeights(lastCategories);
            var tagWeights = ConvertToWeights(lastTags);

            double GetThreshold(Poi p)
            {
                var actualDist = GeoUtils.Distance(p.Coordinates, center);
                var diff       = actualDist - distance;
                var coeff      = diff > 0 ? FurtherToCloserRatio : 1.0;
                var rawValue   = coeff * Math.Sqrt(Math.Abs(diff));
                var savedValue = user.SavedPoiScore(p.Id);
                // var categoryDuplicateValue = catWeights.ContainsKey(p.CategoryId) ? catWeights[p.CategoryId] : 0;
                var tagDuplicateValue = tagWeights.ContainsKey(p.FullTagId) ? tagWeights[p.FullTagId] : 0;

                return(rawValue
                       + SavedToRawRatio * savedValue
                       // + CategoryDuplicateRatio * categoryDuplicateValue
                       + TagDuplicateRatio * tagDuplicateValue);
            }

            return(pois.MinBy(GetThreshold));
        }
Example #15
0
        public async Task <IHttpActionResult> Register(AddBusinessRequest addBusinessRequest)
        {
            try
            {
                ApplicationDbContext context = new ApplicationDbContext();

                var wm = context.Users.FirstOrDefault(user => user.Email == "*****@*****.**");


                PostcodesIOClient client = new PostcodesIOClient();

                var t = client.Random();

                var bt = context.BusinessTypes.OrderBy(r => Guid.NewGuid()).Take(1).FirstOrDefault();

                Business business = new Business();

                business.Postcode = t.Postcode;
                business.Location = GeoUtils.CreatePoint(t.Latitude, t.Longitude);

                business.Users.Add(new BusinessUser()
                {
                    User = wm
                });
                business.BusinessType = bt;
                business.Name         = "Webmaster's " + bt.Name + " [" + t.Postcode + "]";

                context.Businesses.Add(business);

                context.SaveChanges();
            }
            catch (Exception exception)
            {
                return(BadRequest(exception.Message));
            }


            return(Ok());
        }
Example #16
0
        static void CopyBuildings()
        {
            using (var dgis = new DGisContext("Томск"))
            {
                using (var transportCtx = new TransportContext())
                {
                    Console.Write("Копирование зданий... ");

                    var dgisBuildings = dgis.Buildings.GetAll();

                    foreach (var dgisBuilding in dgisBuildings)
                    {
                        var building = new Building
                        {
                            Location  = GeoUtils.CreatePoint(dgisBuilding.PosY, dgisBuilding.PosX),
                            Levels    = dgisBuilding.Levels,
                            PostIndex = dgisBuilding.PostIndex,
                            Purpose   = dgisBuilding.Purpose,
                        };

                        foreach (var addressesId in dgisBuilding.AddressesIds)
                        {
                            var dgisAddress = dgis.Addresses.GetById(addressesId);
                            building.Addresses.Add(new Address
                            {
                                Number   = dgisAddress.Number,
                                Street   = dgisAddress.Street,
                                Building = building
                            });
                        }
                        transportCtx.Buildings.Add(building);
                    }

                    transportCtx.SaveChanges();

                    Console.WriteLine("завершено");
                }
            }
        }
Example #17
0
        public Pdv Closest()
        {
            Pdv result = null;

            //Read data from querystring
            string latitude  = Request.Query["lat"];
            string longitude = Request.Query["lon"];

            if (string.IsNullOrEmpty(latitude) || string.IsNullOrEmpty(longitude))
            {
                return(result);                                                                   //TODO: better error handling
            }
            double lat, lon;

            lat = double.Parse(latitude);
            lon = double.Parse(longitude);
            var testPoint = new Point(new Position(lat, lon));

            //Query PDV's to find the closest
            var pdvs = CachedGetPdvs();

            foreach (var pdv in pdvs)
            {
                var address  = JsonConvert.DeserializeObject <Point>(pdv.Address);
                var distance = GeoUtils.GetDistance(address, testPoint);
                if (result == null || result.Distance > distance)
                {
                    var coverageArea = JsonConvert.DeserializeObject <MultiPolygon>(pdv.CoverageArea);
                    if (GeoUtils.IsPointInMultiPolygon(testPoint, coverageArea))
                    {
                        pdv.Distance = distance;
                        result       = pdv;
                    }
                }
            }

            return(result);
        }
Example #18
0
        public double[] GetWGS84Coordinates()
        {
            if (!Double.IsNaN(wgs84latitude))
            {
                double[] wgs84 = { wgs84latitude, wgs84longitude };
                return(wgs84);
            }

            else
            {
                if (GetTypeOfMessage() == "SMR")
                {
                    GeoUtils         geoUtils         = new GeoUtils();
                    Coordinates      radarCoordinates = utilities.GetCoordinatesOfRadar("SMRLebl");
                    CoordinatesWGS84 radarWGS84       = new CoordinatesWGS84(radarCoordinates.GetLatitude() * (Math.PI / 180.0), radarCoordinates.GetLongitude() * (Math.PI / 180.0));
                    CoordinatesXYZ   objectCartesian  = new CoordinatesXYZ(cartesianX, cartesianY, 0);
                    CoordinatesXYZ   objectGeocentric = geoUtils.change_radar_cartesian2geocentric(radarWGS84, objectCartesian);
                    CoordinatesWGS84 objectWGS84      = geoUtils.change_geocentric2geodesic(objectGeocentric);
                    double[]         wgs84            = { objectWGS84.Lat *(180.0 / Math.PI), objectWGS84.Lon *(180.0 / Math.PI) };
                    return(wgs84);
                }
                else if (GetTypeOfMessage() == "MLAT")
                {
                    GeoUtils         geoUtils         = new GeoUtils();
                    Coordinates      radarCoordinates = utilities.GetCoordinatesOfRadar("ARPLebl");
                    CoordinatesWGS84 radarWGS84       = new CoordinatesWGS84(radarCoordinates.GetLatitude() * (Math.PI / 180.0), radarCoordinates.GetLongitude() * (Math.PI / 180.0));
                    CoordinatesXYZ   objectCartesian  = new CoordinatesXYZ(cartesianX, cartesianY, 0);
                    CoordinatesXYZ   objectGeocentric = geoUtils.change_radar_cartesian2geocentric(radarWGS84, objectCartesian);
                    CoordinatesWGS84 objectWGS84      = geoUtils.change_geocentric2geodesic(objectGeocentric);
                    double[]         wgs84            = { objectWGS84.Lat *(180.0 / Math.PI), objectWGS84.Lon *(180.0 / Math.PI) };
                    return(wgs84);
                }
                else
                {
                    return(null);
                }
            }
        }
 /// <summary>
 /// 简单多边形或者三角面点数组
 /// </summary>
 /// <param name="tries"></param>
 /// <param name="isPolygon">是否为简单多边形</param>
 /// <param name="vert"></param>
 /// <returns></returns>
 public static List <List <int> > Decompose(List <Vector2> tries, bool isPolygon, ref List <Vector2> vert)
 {
     if (isPolygon)
     {
         EarPolygon poly = new EarPolygon();
         foreach (Vector2 v in tries)
         {
             poly.AddPoint(v.x, v.y);
         }
         EarClipping.Clip(poly);
         List <Vector2> triangles = new List <Vector2>();
         GeoUtils.FlatList(poly.mResults, ref triangles);
         List <int> indices = new List <int>();
         GeoUtils.MeshVertexPrimitiveType(triangles, ref vert, ref indices);
         return(HMDecompose(vert, indices));
     }
     else
     {
         List <int> indices = new List <int>();
         GeoUtils.MeshVertexPrimitiveType(tries, ref vert, ref indices);
         return(HMDecompose(vert, indices));
     }
 }
        private void ShowOnMap()
        {
            var map = PluginManager.Instance.GetMap();

            if (map != null)
            {
                if (lstResults.ItemsSource != null)
                {
                    var label = GeoUtils.FormatCoordinates(ctlPosition.Latitude, ctlPosition.Longitude);
                    map.Show();
                    var set = new ListMapPointSet("Named places near " + label);
                    foreach (PlaceNameViewModel vm in lstResults.ItemsSource)
                    {
                        set.Add(new MapPoint {
                            Label = vm.Name, Latitude = vm.Latitude, Longitude = vm.Longitude
                        });
                    }

                    map.PlotPoints(set);
                    map.DropAnchor(ctlPosition.Longitude, ctlPosition.Latitude, "");
                }
            }
        }
Example #21
0
        /// <summary>
        /// 省
        /// </summary>
        private void HandleProvinceData()
        {
            var result = _geographyMongoRepository.GetProvinceList();
            List <ProvinceInfo> list = new List <ProvinceInfo>();

            result.ForEach(item =>
            {
                var spell = GetSpell(item.ProvinceName);
                list.Add(new ProvinceInfo
                {
                    ProvinceCode = item.ProvinceCode,
                    ProvinceName = item.ProvinceName,
                    ShorName     = GeoUtils.GetShortName(item.ProvinceName),
                    Spell        = spell,
                    FirstLetter  = spell[0].ToString()
                });
                HandleCityData(item.ProvinceCode);
            });
            if (list.Count > 0)
            {
                _geographyRepository.Insert(list);
            }
        }
Example #22
0
    GameObject DrawTroncon(Feature feature)
    {
        MultiLineString itineraire         = feature.Geometry as MultiLineString;
        string          id_itineraire      = feature.Properties["ID"].ToString();
        double          largeur_itineraire = (double)feature.Properties["LARGEUR"];

        GameObject  road        = new GameObject(id_itineraire);
        RoadCreator roadCreator = road.AddComponent <RoadCreator>();

        roadCreator.spacing   = 1f;
        roadCreator.roadWidth = (float)largeur_itineraire;
        roadCreator.material  = material;
        roadCreator.tiling    = 2;
        Path path = road.GetComponent <Path>();

        //path.AutoSetControlPoints = true;
        path.points = new List <Vector3>();

        foreach (LineString troncon in itineraire.Coordinates)
        {
            foreach (IPosition position in troncon.Coordinates)
            {
                if (position.Altitude.HasValue)
                {
                    if (position.Altitude.Value < 250)
                    {
                        altitude = position.Altitude.Value;
                    }
                }

                path.AddSegment(GeoUtils.GeoToWorldPosition(position.Latitude, position.Longitude,
                                                            altitude, refPoint, scale));
            }
        }

        return(road);
    }
Example #23
0
        public void ParseDataset(string datasetDirectory, Dictionary <string, BreastCancerSampleItem> sampleMap)
        {
            var files = GeoUtils.GetGsmNameFileMap(datasetDirectory);

            var dirname = Path.GetFileName(datasetDirectory);

            //The status of ER, PR is on the sample title
            var samples = new GseSeriesMatrixReader().ReadFromDirectory(datasetDirectory);

            foreach (var a in samples)
            {
                var filename = a.Key.ToLower();
                if (files.ContainsKey(filename.ToLower()))
                {
                    var title = a.Value[GsmConsts.SampleTitle];
                    var m     = r.Match(title.First());
                    var er    = m.Groups[1].Value.Equals("p") ? "pos" : "neg";
                    var pr    = m.Groups[2].Value.Equals("p") ? "pos" : "neg";
                    var ts    = m.Groups[3].Value;
                    var n     = m.Groups[4].Value;
                    var grade = m.Groups[5].Value;

                    var key = filename.ToUpper();
                    if (!sampleMap.ContainsKey(key))
                    {
                        sampleMap[key] = new BreastCancerSampleItem(dirname, filename.ToUpper());
                    }

                    BreastCancerSampleItem item = sampleMap[key];

                    item.ER          = er;
                    item.PR          = pr;
                    item.TumorStatus = ts;
                    item.Grade       = grade;
                }
            }
        }
Example #24
0
        private void RecalculateValue()
        {
            double newValue = 0;

            switch (Mode)
            {
            case LatLongMode.DecimalDegrees:
                newValue = SafeParseDouble(txtDegrees.Text);
                break;

            case LatLongMode.DegreesDecimalMinutes:
                var deg     = SafeParse(txtDegrees.Text);
                var minutes = SafeParseDouble(txtMinutes.Text);
                newValue = GeoUtils.DDecMToDecDeg(deg, minutes);
                break;

            case LatLongMode.DegreesDecimalMinutesDirection:
                deg      = SafeParse(txtDegrees.Text);
                minutes  = SafeParseDouble(txtMinutes.Text);
                newValue = GeoUtils.DDecMDirToDecDeg(deg, minutes, cmbDirection.Text);
                break;

            case LatLongMode.DegreesMinutesSeconds:
                deg = SafeParse(txtDegrees.Text);
                int    min     = SafeParse(txtMinutes.Text);
                double seconds = SafeParseDouble(txtSeconds.Text);
                newValue = GeoUtils.DMSToDecDeg(deg, min, seconds, cmbDirection.SelectedItem as string);
                break;

            default:
                throw new Exception("Recalculate: Mode not handled: " + Mode.ToString());
            }
            _selfChanged = true;
            this.Value   = newValue;
            _selfChanged = false;
        }
Example #25
0
        //获取列表
        public IEnumerable <BusStation> _GetStationList()
        {
            HYMSDTEntities context = new HYMSDTEntities();
            var            list    = from bs in context.T_BusLine_Station
                                     join s in context.T_Station
                                     on bs.Sta_Id equals s.Sta_Id
                                     join b in context.T_BusLine
                                     on bs.BL_Id equals b.BL_Id
                                     select new BusStation
            {
                Sta_Guid         = s.Sta_Guid,
                Sta_Geo          = GeoUtils.ToGeoJson(s.Sta_Geo),
                Sta_Name         = s.Sta_Name,
                BL_Name          = b.BL_Name,
                BL_Geo           = GeoUtils.ToGeoJson(b.BL_Geo),
                BL_S_Guid        = bs.BL_S_Guid,
                BL_DownEndTime   = b.BL_DownEndTime,
                BL_DownStartTime = b.BL_DownStartTime,
                BL_UpEndTime     = b.BL_UpEndTime,
                BL_UpStartTime   = b.BL_UpStartTime
            };

            return(list);
        }
Example #26
0
        public ActionResult EditService(Service SV)
        {
            HYMSDTEntities context = new HYMSDTEntities();
            ReturnModel1   reModel = new ReturnModel1();

            reModel.status = false;
            try
            {
                var model = context.T_Service.First(i => i.S_Guid == SV.S_Guid);
                model.S_Address   = SV.S_Address;
                model.S_Cost      = SV.S_Cost;
                model.S_Introduce = SV.S_Introduce;
                model.S_Name      = SV.S_Name;
                //model.S_PhotoList = SV.S_PhotoList;
                model.S_QH   = SV.S_QH;
                model.S_Star = SV.S_Star;
                model.S_Type = SV.S_Type;

                //转WKT
                if (!string.IsNullOrEmpty(SV.S_Geo))
                {
                    string wktStr = string.Format("POINT ({0})", SV.S_Geo);
                    model.S_Geo = GeoUtils.FromWkt("point", wktStr, 0);
                }

                context.SaveChanges();

                reModel.status = true;
            }
            catch (Exception ex)
            {
                reModel.message = ex.ToString();
            }

            return(Json(reModel));
        }
Example #27
0
        public JObject Closest()
        {
            var     req    = Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
            JObject result = null;

            //Read data from querystring
            if (!(req.ContainsKey("lat") && req.ContainsKey("lon")))
            {
                return(result);                                                     //TODO: better error handling
            }
            double lat, lon;

            lat = double.Parse(req["lat"]);
            lon = double.Parse(req["lon"]);
            var testPoint = new Point(new Position(lat, lon));

            //Query PDV's to find the closest
            var pdvs = GetPdvs();

            foreach (JObject pdv in pdvs)
            {
                var address  = JsonConvert.DeserializeObject <Point>(pdv["address"]?.ToString());
                var distance = GeoUtils.GetDistance(address, testPoint);
                if (result == null || (double)result["distance"] > distance)
                {
                    var coverageArea = JsonConvert.DeserializeObject <MultiPolygon>(pdv["coverageArea"]?.ToString());
                    if (GeoUtils.IsPointInMultiPolygon(testPoint, coverageArea))
                    {
                        pdv["distance"] = distance;
                        result          = pdv;
                    }
                }
            }

            return(result);
        }
Example #28
0
        /// <summary> Controls tiles on map. </summary>
        /// <param name="parent"> Parent of tiles. </param>
        /// <param name="position"> Current position. </param>
        public void Update(Transform parent, Vector3 position)
        {
            if (Vector3.Distance(position, _position) < float.Epsilon)
            {
                return;
            }

            _position = position;

            var currentPosition = GeoUtils.ToGeoCoordinate(_geoOrigin, new Vector2(_position.x, _position.z));
            var currentQuadKey  = GeoUtils.CreateQuadKey(currentPosition, _levelOfDetail);

            var quadKeys            = new HashSet <QuadKey>(GetNeighbours(currentQuadKey));
            var newlyLoadedQuadKeys = new Dictionary <QuadKey, Tile>();

            foreach (var quadKey in quadKeys)
            {
                newlyLoadedQuadKeys.Add(quadKey, _loadedQuadKeys.ContainsKey(quadKey)
                    ? _loadedQuadKeys[quadKey]
                    : BuildQuadKey(parent, quadKey));
            }

            int tilesDisposed = 0;

            foreach (var quadKeyPair in _loadedQuadKeys)
            {
                if (!quadKeys.Contains(quadKeyPair.Key))
                {
                    ++tilesDisposed;
                    quadKeyPair.Value.Dispose();
                }
            }

            UnloadAssets(tilesDisposed);
            _loadedQuadKeys = newlyLoadedQuadKeys;
        }
Example #29
0
        /// <summary> Gets quadkey for position. </summary>
        private QuadKey GetQuadKey(int lod)
        {
            var currentPosition = GeoUtils.ToGeoCoordinate(_geoOrigin, new Vector2(_position.x, _position.z) / _scale);

            return(GeoUtils.CreateQuadKey(currentPosition, lod));
        }
Example #30
0
        // TODO call this method when tile is moved too far.
        /// <summary> Moves geo origin to specific world position. </summary>
        private void MoveWorldOrigin(Vector3 position)
        {
            var geoOrigin = GeoUtils.ToGeoCoordinate(_geoOrigin, new Vector2(position.x, position.z) / _scale);

            MoveGeoOrigin(geoOrigin);
        }