private void Update() { // force geoObjects look at camera foreach (GameObject gameObj in geoObjectsInScene.Values) { gameObj.transform.LookAt(_mainCamera.transform); } if (!IsInputLocationRunning()) { return; } LocationDataModel locInfo = GetUserLocationData(); UpdateGeoObjectsPositions(locInfo.lat, locInfo.lng); //if (Input.location.status == LocationServiceStatus.Running && // _currentTimer > LOCATION_PING) //{ // LocationData locInfo = GetUserLocationData(); // Vector3 locInfoPos = ConvertGpsLocationToUnityLocation(locInfo.latitude, locInfo.longitude); // float dist = Vector3.Distance(locInfoPos, Vector3.zero); // if (dist > 10f) // { // UpdateGeoObjectsPositions(locInfo.latitude, locInfo.longitude); // } // _currentTimer = 0f; //} }
/// <summary> /// Created By : Ashwajit Bansod /// Created For : To get location data a per location Id /// Created Date : 27-Dec-2018 /// </summary> /// <param name="LocationId"></param> /// <returns></returns> public LocationDataModel GetLocationDataByLocId(long LocationId) { var data = new LocationDataModel(); try { if (LocationId > 0) { data = _workorderems.LocationMasters.Where(x => x.LocationId == LocationId && x.IsDeleted == false).Select(a => new LocationDataModel() { LocationId = a.LocationId, LocationName = a.LocationName, QBK_Id = a.QuickBookLocId }).FirstOrDefault(); } else { return(null); } } catch (Exception ex) { Exception_B.Exception_B.exceptionHandel_Runtime(ex, "public string GetCostCodeData(long CostCodeId)", "Exception While Getting data of cost code.", null); throw; } return(data); }
public IEnumerable <LocationDataModel> GetLocations(string possibleLoggedInUserId) { var locations = this.data.Locations .All .Select(LocationDataModel.FromLocation(possibleLoggedInUserId)).ToList(); return(locations); }
static public LocationDataModel GetLatLng(int MCC, int MNC, int LAC, int CID) { LocationDataModel location = new LocationDataModel(); try { String url = "http://www.google.com/glm/mmap"; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(url)); req.Method = "POST"; byte[] pd = PostData(MCC, MNC, LAC, CID); req.ContentLength = pd.Length; req.ContentType = "application/binary"; Stream outputStream = req.GetRequestStream(); outputStream.Write(pd, 0, pd.Length); outputStream.Close(); HttpWebResponse res = (HttpWebResponse)req.GetResponse(); byte[] ps = new byte[res.ContentLength]; int totalBytesRead = 0; while (totalBytesRead < ps.Length) { totalBytesRead += res.GetResponseStream().Read(ps, totalBytesRead, ps.Length - totalBytesRead); } if (res.StatusCode == HttpStatusCode.OK) { short opcode1 = (short)(ps[0] << 8 | ps[1]); byte opcode2 = ps[2]; int ret_code = (int)((ps[3] << 24) | (ps[4] << 16) | (ps[5] << 8) | (ps[6])); if (ret_code == 0) { double lat = ((double)((ps[7] << 24) | (ps[8] << 16) | (ps[9] << 8) | (ps[10]))) / 1000000; double lon = ((double)((ps[11] << 24) | (ps[12] << 16) | (ps[13] << 8) | (ps[14]))) / 1000000; location.Latitude = lat.ToString(); location.Longitude = lon.ToString(); return(location); } return(location); } else { return(location); } } catch (Exception ex) { return(location); } }
public IHttpActionResult GetLocationDetails(string id) { int locationId = int.Parse(id); string possibleLoggedInUserId = this.User.Identity.GetUserId(); LocationDataModel location = this.locationsService.GetLocationById(locationId, possibleLoggedInUserId); return(Ok(location)); }
public LocationDataModel GetLocationById(int id, string possibleLoggedInUserId) { LocationDataModel location = this.data.Locations .All .Where(x => x.Id == id) .Select(LocationDataModel.FromLocation(possibleLoggedInUserId)) .FirstOrDefault(); return(location); }
public ActionResult AddAddress(string areaId, string address, string receiverName, string receiverPhone, bool isDefault, long?OrderId) { Area area = _areaRepository.GetAreaById(int.Parse(areaId)); City city = _cityRepository.GetCityById(area.CityId); Province province = _provinceRepository.GetProvinceById(city.ProvinceId); long customerId = (Session[Constants.SESSION_USER] as Customer).Id; if (OrderId != 0) { isDefault = true; } if (isDefault) { List <Address> addressList = _addressService.GetAddresses(customerId); Address defaultAddress = addressList.Where(x => x.IsDefault == isDefault).ToList().FirstOrDefault(); if (defaultAddress != null) { defaultAddress.IsDefault = false; _addressService.UpdateAddress(defaultAddress); } } string fullAddress = province.ProvinceName + city.CityName + area.AreaName + address; string addressParam = "&address=" + fullAddress; string ak = "&ak=" + Constants.BMAP_AK; LocationDataModel locationDataModel = JsonHelper.DeserializeJsonToObject <LocationDataModel>(WebAPIHelper.Get(Constants.BMAP_GEOCODER_BASE_URL + Constants.BMAP_OUTPUT_TYPE + addressParam + ak)); Address DeliveryAddress = new Address() { ReceiverName = receiverName, ReceiverPhone = receiverPhone, DeliveryAddress = fullAddress, IsDefault = isDefault, Latitude = locationDataModel.Result.Location.Lat, Longitude = locationDataModel.Result.Location.Lng, AreaId = int.Parse(areaId), CustomerId = customerId }; _addressService.AddAddress(DeliveryAddress); if (OrderId == 0 || OrderId == null) { return(RedirectToAction("GetAddress")); } else { return(RedirectToRoute(new { controller = "Order", action = "CheckOrder", orderId = OrderId })); } }
private void Update() { LookAtCamera(); if (!IsInputLocationRunning()) { return; } LocationDataModel locInfo = GetUserLocationData(1); UpdateGeoObjectsPositions(locInfo); }
private async Task RunGpsTracking() { if (isDebug) { currentLocation = GetUserLocationData(); _arSessionOrigin.transform.rotation = Quaternion.Euler(0, GetCompassTrueHeading(), 0); return; } if (!IsInputLocationRunning()) { StartCoroutine(FetchLocationData()); } }
public LocationDataModel GetLocationCovid19Api(string countryCode) { var locatorConfig = new LocatorConfig(); _configuration.GetSection("LocatorConfig").Bind(locatorConfig); string contentRootPath = _webHostEnvironment.ContentRootPath; var json = File.ReadAllText($"{contentRootPath}/Data/{locatorConfig.Path}"); var list = JsonConvert.DeserializeObject <List <LocationDataModel> >(json); LocationDataModel locationModel = list.Find(location => location.Country.Equals(countryCode, StringComparison.OrdinalIgnoreCase)); return(locationModel); }
private IEnumerator FetchLocationData() { // First, check if user has location service enabled if (!Input.location.isEnabledByUser) { ToastManager.Instance.DisplayToast(noLocationPermission, ToastType.Error, 3f); Debug.Log($" {DateTime.Now:HH: mm:ss tt} Location disabled"); yield break; } // Start service before querying location with accuracy 1 meter Input.location.Start(.1f, .1f); Debug.Log($"{DateTime.Now:HH: mm:ss tt} Fetching Location.."); // Wait until service initializes int maxWait = 20; while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) { yield return(new WaitForSeconds(1)); maxWait--; } // Service didn't initialize in 20 seconds if (maxWait < 1) { Debug.Log($"{DateTime.Now:HH:mm:ss tt} Location Timed out"); ToastManager.Instance.DisplayToast(failedToGetLocation, ToastType.Error, 1f); yield break; } switch (Input.location.status) { case LocationServiceStatus.Failed: ToastManager.Instance.DisplayToast(failedToGetLocation, ToastType.Error, 1f); Debug.Log($"{DateTime.Now:HH:mm:ss tt} Unable to determine device location"); break; case LocationServiceStatus.Running: Input.compass.enabled = true; int timeToFilter = 5; ToastManager.Instance.DisplayToast(waitForLocation, ToastType.Info, timeToFilter); yield return(new WaitForSeconds(timeToFilter)); currentLocation = GetUserLocationData(timeToFilter); break; } }
private async Task RunGpsTracking() { if (isDebug) { currentLocation = GetUserLocationData(1); _arSessionOrigin.transform.rotation = Quaternion.Euler(0, GetCompassTrueHeading(), 0); // Test Toast displaying for Debug mode with fake GPS. ToastManager.Instance.DisplayToast(waitForLocation, ToastType.Info, 5); return; } if (!IsInputLocationRunning()) { StartCoroutine(FetchLocationData()); } }
public void StartGettingDirection() { var existingLineRenderObject = GameObject.FindGameObjectWithTag("LineRenderObject"); if (existingLineRenderObject) { Destroy(existingLineRenderObject); } string geoObjectId = _selectedGeoObjectIdInNavigationDropDown; _userArrivedToPlace = false; _currentGpsLocation = _gpsPlacingBehaviour.GetCurrentLocationData(); StartCoroutine(GetDirection(geoObjectId, _currentGpsLocation)); }
public static double DistanceBetween2GeoobjectsInM(LocationDataModel m1, LocationDataModel m2) { double lat1 = m1.lat; double long1 = m1.lng; double lat2 = m2.lat; double long2 = m2.lng; double _eQuatorialEarthRadius = 6378.1370D; double _d2r = (Math.PI / 180D); double dlong = (long2 - long1) * _d2r; double dlat = (lat2 - lat1) * _d2r; double a = Math.Pow(Math.Sin(dlat / 2D), 2D) + Math.Cos(lat1 * _d2r) * Math.Cos(lat2 * _d2r) * Math.Pow(Math.Sin(dlong / 2D), 2D); double c = 2D * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1D - a)); double d = _eQuatorialEarthRadius * c; return(d * 1000); }
private void OnUpdateGeoLocation(string geoLocationData) { LocationDataModel searchLocation = JsonFx.Json.JsonReader.Deserialize <LocationDataModel>(geoLocationData); if (null == searchLocation) { OnFailGeoData(geoLocationData); return; } previousSearches.Remove(_searchString); previousSearches.AddFirst(_searchString); UpdateLocationCards(); if (_searchString.All(c => c >= '0' && c <= '9')) { searchLocation.zipCode = _searchString; } else { searchLocation.cityState = _searchString; } ITTDataCache.Instance.Data.UpdateDataEntry((int)DataCacheIndices.LOCATION, searchLocation, false); if (!_toolTipComplete) { ToolTipViewController.FlagViewedTooltip(); } HelperMethods.RemoveInteractionBlocker(); // TODO: clear dynamic scroll view model.mainAppViewModel.DynamicScrollView.ClearCarousel(); model.mainAppViewModel.NoActivitiesCard.SetActive(false); ITTDataCache.Instance.Data.ClearDataEntry((int)DataCacheIndices.ACTIVITY_LIST); ITTDataCache.Instance.Data.RefreshDataEntry((int)DataCacheIndices.ACTIVITY_LIST); ITTMainSceneManager.Instance.currentState = ITTMainSceneManager.ITTStates.Main; GameObject.Destroy(_loadingScreen.gameObject); }
void OnRetrievedUserFlags(DataEntryBase data) { UserFlagsEntry flags = data as UserFlagsEntry; if (null != flags || null != flags.Data) { if (flags.Data.hasToggledLocation == true) { model.LocationLabel.text = "Current Location"; } else { LocationDataModel locationData = ITTDataCache.Instance.RetrieveLocationData(); if (null == locationData) { locationData = ITTDataCache.Instance.DefaultLocationData(); } model.LocationLabel.text = (!string.IsNullOrEmpty(locationData.zipCode)) ? locationData.zipCode : (!string.IsNullOrEmpty(locationData.cityState)) ? locationData.cityState : "Austin, TX"; } } ITTDataCache.Instance.Data.RemoveCallbackFromEntry((int)DataCacheIndices.USER_FLAGS, OnRetrievedUserFlags); }
private void UpdateValues() { if (!IsInputLocationRunning()) { return; } LocationDataModel lastKnownLocation = GetUserLocationData(3); string currentLocationText; if (currentLocation != null) { currentLocationText = $"lat: {currentLocation.lat}, lng: {currentLocation.lng}\n"; } else { currentLocationText = $"lat: --------, lng: --------\n"; } currentLocationLog.text = $"Actual location is\n" + $"lat: {lastKnownLocation.lat}, lng: {lastKnownLocation.lng}\n" + $"Current location is \n" + currentLocationText + $"Compass:\n" + $"{((int)GetCompassTrueHeading()).ToString() + "° " + Calculator.DegreesToCardinalDetailed(GetCompassTrueHeading())}"; // if current location changed then update positions of all geoObjects in scene if (Calculator.DistanceBetween2GeoobjectsInM(lastKnownLocation, currentLocation) > maxGeoTextDistance) { currentLocation = lastKnownLocation; Debug.Log($" {DateTime.Now:HH: mm:ss tt} UpdateGeoObjectsPositions"); UpdateGeoObjectsPositions(currentLocation); } }
private async Task TestPlacingObjects() { if (!IsInputLocationRunning()) { return; } LocationDataModel lastKnownLocation = GetUserLocationData(); currentLocationLog.text = $"Current location is lat: {lastKnownLocation.lat}, lng: {lastKnownLocation.lng} Compass: "******"{((int) GetCompassTrueHeading()).ToString() + "° " + DegreesToCardinalDetailed(GetCompassTrueHeading())}"; // if current location changed then update positions of all geoObjects in scene if (DistanceBetween2GeoobjectsInM(lastKnownLocation.lat, lastKnownLocation.lng, currentLocation.lat, currentLocation.lng) > 20) { currentLocation = lastKnownLocation; Debug.Log($" {DateTime.Now:HH: mm:ss tt} UpdateGeoObjectsPositions"); UpdateGeoObjectsPositions(lastKnownLocation.lat, lastKnownLocation.lng); } if (!webSockets) { return; } // !IMPORTANT>DO NOT CHANGE FORM OF REQUEST STRING !!! // string for request objects to place to scene string reqString = "{ " + $"\"lat\": {currentLocation.lat}, \"lng\": {currentLocation.lng}" + "}"; string responseData = await webSockets.ReceiveObjectsFromServer(reqString); // Debug.Log(responseData); if (responseData == "" || responseData.StartsWith("{\"success\":true,\"message\":\"Connection established\"}")) { return; } // Debug.Log($"Got response: {responseData}"); // json response from server for user location request ResponseFromServerLocationDataModel response = null; try { response = JsonConvert.DeserializeObject <ResponseFromServerLocationDataModel>(responseData); } catch (Exception e) { Debug.LogError(e); } if (response == null || !response.success) { Debug.Log("Failed to load object from server"); return; } List <IGeoObjectModel> packGeoObjectsFromServer = new List <IGeoObjectModel>(); if (response.geoAudioObjectModels?.Any() == true) { packGeoObjectsFromServer.AddRange(response.geoAudioObjectModels); } if (response.poiObjectModels?.Any() == true) { packGeoObjectsFromServer.AddRange(response.poiObjectModels); } if (response.geo3dObjectModels?.Any() == true) { packGeoObjectsFromServer.AddRange(response.geo3dObjectModels); } if (!(response.geoAudioObjectModels?.Any() == true || response.poiObjectModels?.Any() == true || response.geo3dObjectModels?.Any() == true)) { Debug.Log("Objects not found in this location"); await DeleteObjectsFromScene(packGeoObjectsFromServer); return; } await DeleteObjectsFromScene(packGeoObjectsFromServer); // GPSEncoder.SetLocalOrigin(new Vector2(currentLocation.lat, currentLocation.lng)); // _arSessionOrigin.transform.localPosition = // GPSEncoder.GPSToUCS(currentLocation.lat, currentLocation.lng); // if (Input.compass.enabled) // { // _arSessionOrigin.transform.rotation = Quaternion.Euler(0, -Input.compass.magneticHeading, 0); // //Debug.Log($"True heading {((int)GetCompassTrueHeading()).ToString() + "° " + DegreesToCardinalDetailed(GetCompassTrueHeading())}"); // Debug.Log($" {DateTime.Now.ToString("HH:mm:ss tt")} Updated Magnetic heading {(-(int)Input.compass.magneticHeading).ToString() + "° " + DegreesToCardinalDetailed(Input.compass.magneticHeading)}"); // //Debug.Log($"Raw vector {Input.compass.rawVector.ToString()}"); // } // if (notInitToNorth) { _arSessionOrigin.transform.rotation = Quaternion.Euler(0, GetCompassTrueHeading(), 0); notInitToNorth = false; } await AddNewObjectsToScene(packGeoObjectsFromServer); }
private IEnumerator GetDirection(string geoObjectId, LocationDataModel location) { if (_authToken == null) { yield return(new WaitForSeconds(1)); } string requestString = _serverApiString + "direction"; var uriBuilder = new UriBuilder(requestString); NameValueCollection queryString = System.Web.HttpUtility.ParseQueryString(string.Empty); queryString.Add("lat", location.lat.ToString()); queryString.Add("lng", location.lng.ToString()); queryString.Add("objectId", geoObjectId); uriBuilder.Query = queryString.ToString(); // requestString = uriBuilder.ToString(); requestString += "?" + queryString.ToString(); UnityWebRequest www = UnityWebRequest.Get(requestString); www.SetRequestHeader("Authorization", "Bearer " + _authToken); // www.timeout = 4; var time = DateTime.Now.Second; yield return(www.SendWebRequest()); if (www.result != UnityWebRequest.Result.Success) { Debug.LogError(requestString); Debug.LogError(www.error); Debug.LogError(www.result); Debug.LogError(www.downloadHandler.text); displayDropdownMessage.text = "До данного объекта не получается проложить маршрут"; yield break; } var elapsedTime = DateTime.Now.Second - time; Debug.Log("Elapsed time " + elapsedTime.ToString()); string responseText = www.downloadHandler.text; ResponseFromServerOneToOneDirectionModel response = null; try { response = JsonConvert.DeserializeObject <ResponseFromServerOneToOneDirectionModel>(responseText); } catch (Exception e) { Debug.LogError(e); yield break; } Debug.Log(response); List <Step> steps = response.message._steps; List <Vector3> vector3Steps = new List <Vector3>(); foreach (var step in steps) { vector3Steps.Add(GPSEncoder.GPSToUCS(step.lat, step.lng)); } if (steps.Count == 1) { var gameObject = _gpsPlacingBehaviour.GetGameObjectOfGeoObjectInSceneById(geoObjectId); vector3Steps.Add(gameObject.transform.position); } vector3Steps[0] = _mainCamera.transform.position; SetupDirectionObject(vector3Steps); }
public Bootstrapper() { Initialize(); APIHelper.InitializeClient(); LocationDataModel GetLocationList = new LocationDataModel(); }
private void UpdateGeoObjectsPositions(LocationDataModel location) { foreach (var line in lines) { if (line) { Destroy(line); } } lines = new List <GameObject>(); float minDistance = float.MaxValue; foreach (var dictionary in geoObjectsInScene) { foreach (KeyValuePair <string, GameObject> geoObjectPair in dictionary) { string geoObjectId = geoObjectPair.Key; GeoObject geoObject = geoObjectPair.Value.GetComponent <GeoObject>(); Vector3 positionOfGeoObject = GPSEncoder.GPSToUCS(geoObject.GeoData.location.lat, geoObject.GeoData.location.lng); double distanceToUser = Calculator.DistanceBetween2GeoobjectsInM(location, geoObject.GeoData.location); float distanceToUserUnity = Vector3.Distance(geoObject.transform.localPosition, _mainCamera.transform.position); if (placingAccuracy <= distanceToUser && distanceToUser <= maxGeoTextDistance && placingAccuracy <= distanceToUserUnity) { geoObject.transform.localPosition = Vector3.Lerp(geoObject.transform.localPosition, positionOfGeoObject, 1f * Time.deltaTime); } if (geoObject.gameObject.TryGetComponent <GeoText>(out GeoText geoText)) { if (placingAccuracy <= distanceToUser && distanceToUser <= maxGeoTextDistance && placingAccuracy <= distanceToUserUnity) { geoObject.transform.localPosition = Vector3.Lerp(geoObject.transform.localPosition, positionOfGeoObject, 1f * Time.deltaTime); } // GeoText should be closer than maxGeoTextDistance. if (distanceToUser > maxGeoTextDistance) { Vector3 cameraLocalPosition = _mainCamera.transform.position; Vector3 newPosition = ((positionOfGeoObject - cameraLocalPosition).normalized * maxGeoTextDistance) + cameraLocalPosition; newPosition.y = cameraLocalPosition.y; geoObject.transform.localPosition = Vector3.Lerp(geoObject.transform.localPosition, newPosition, 1f * Time.deltaTime); } if (geoText) { geoText.distance.text = Convert.ToUInt32(distanceToUser).ToString() + " m"; } } if (geoObject.gameObject.TryGetComponent <GeoAudio>(out GeoAudio geoAudio)) { geoObject.GetComponent <CanvasGroup>().alpha = (distanceToUser < maxGeoAudioDistance) ? 1 : 0; if (distanceToUser > maxGeoTextDistance) { Vector3 cameraLocalPosition = _mainCamera.transform.position; Vector3 newPosition = ((positionOfGeoObject - cameraLocalPosition).normalized * maxGeoTextDistance) + cameraLocalPosition; newPosition.y = cameraLocalPosition.y; geoObject.transform.localPosition = Vector3.Lerp(geoObject.transform.localPosition, newPosition, 1f * Time.deltaTime); geoObject.GetComponent <AudioSource>().volume = 0; } else { geoObject.GetComponent <AudioSource>().volume = 1; } DrawLine(geoObject.transform.position, _mainCamera.transform.position - Vector3.up * 0.1f, Color.green); } if (geoObject.gameObject.TryGetComponent <GeoModel>(out GeoModel geoModel)) { DrawLine(geoObject.transform.position, _mainCamera.transform.position - Vector3.up * 0.1f, Color.red); } } } }