public static Dictionary <string, double> GetCityLongLat(string cityName, string countryName) { try { //if (countryName == "Australia") //{ // cityName = "New South Wales"; //} var address = cityName + ", " + countryName; var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(address); if (cityName == "N/A" || point == null) { return(new Dictionary <string, double>() { { "Lat", 0 }, { "Long", 0 }, }); } var latitude = point.Latitude; var longitude = point.Longitude; return(new Dictionary <string, double>() { { "Lat", latitude }, { "Long", longitude }, }); } catch (Exception ex) { throw; } }
protected void btnSearch_Click(object sender, EventArgs e) { DataTable dt = SqlObject.FetchDataTable("select * from seller join review on seller.sellerid = review.sellerid join facility on facility.sellerid=seller.sellerid where review.rating = '" + ddlRating.SelectedValue.ToString() + "' and facility.bed = '" + chkFacilities.Items[0].Selected + "' or facility.parking = '" + chkFacilities.Items[1].Selected + "' or facility.transport = '" + chkFacilities.Items[2].Selected + "' or facility.wifi = '" + chkFacilities.Items[3].Selected + "' or facility.tv = '" + chkFacilities.Items[4].Selected + "' or facility.laundry = '" + chkFacilities.Items[5].Selected + "' or facility.heater = '" + chkFacilities.Items[6].Selected + "' or facility.breakfast = '" + chkFacilities.Items[7].Selected + "' and seller.availableroom = '" + ddlRooms.SelectedValue.ToString() + "' and seller.rent > '" + ddlPriceFrom.SelectedValue.ToString() + "' and seller.rent < '" + ddlPriceTo.SelectedValue.ToString() + "'"); if (dt.Rows.Count != 0) { for (int i = 0; i < dt.Rows.Count; i++) { var address = dt.Rows[i]["location"].ToString(); var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(address); var latitude = point.Latitude; var longitude = point.Longitude; String htmltext = " <div class='col - md - 3 top - deal - top'><div class='top-deal'>" + "<a href = 'details.aspx' class='mask'>" + "<iframe src = 'https://maps.google.com/maps?q=" + latitude + "," + longitude + "&hl=es;z=14&output=embed'></iframe></ a >" + "<div class='deal-bottom'>" + "<div class='top-deal1'>" + "<h5><a href = 'details.aspx' > " + dt.Rows[i]["location"].ToString() + " </ a ></ h5 >" + "<p> Available Rooms : " + dt.Rows[i]["availableroom"].ToString() + "</p>" + "<p>Rent : $ " + dt.Rows[i]["rent"].ToString() + "</p>" + "</div>" + "<div class='top-deal2'>" + "<a href = 'details.aspx?id=" + dt.Rows[i]["sellerid"].ToString() + "' class='hvr-sweep-to-right more'>More</a>" + "</div>" + "<div class='clearfix'></div>" + "</div>" + "</div>" + "</div>"; LiteralControl div1 = new LiteralControl(htmltext); divAllRooms.Controls.Add(div1); } } }
public RedirectToRouteResult UpdateAllLateLong() { foreach (var landlord in db.LandLords) { try { System.Threading.Thread.Sleep(500); var gls = new GoogleLocationService(); var latlong = gls.GetLatLongFromAddress(landlord.City + " " + landlord.ZipCode); landlord.Latitude = latlong.Latitude; landlord.Longitude = latlong.Longitude; db.Entry(landlord).State = EntityState.Modified; } catch (SystemException ex) { System.Threading.Thread.Sleep(5000); var gls = new GoogleLocationService(); var latlong = gls.GetLatLongFromAddress(landlord.City + " " + landlord.ZipCode); landlord.Latitude = latlong.Latitude; landlord.Longitude = latlong.Longitude; db.Entry(landlord).State = EntityState.Modified; } } db.SaveChanges(); return(RedirectToAction("Index")); }
public List <string> ShowHotels([FromBody] string city) { var hotelName = new List <string>(); using (var client = new WebClient()) { //Autocomplete Predictions string autocomplete = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + city + "&types=geocode&language=fr&key=AIzaSyAfSismyG_AnFnMGsr6kJ75Fnv8HC4JkF4"; var jsonPrediction = client.DownloadString(autocomplete); var jsonObjectPrediction = JsonConvert.DeserializeObject <RootObjectPrediction>(jsonPrediction); var cityName = jsonObjectPrediction.Predictions.Select(c => c.Description).ToList(); //Get Latitude and Longitude of location var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(cityName[0]); var latitude = point.Latitude; var longitude = point.Longitude; //Find Hotels in 20Km Radius string uri = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + 18.5204 + "," + 73.8567 + "&radius=20000&type=hotel&&key=AIzaSyAfSismyG_AnFnMGsr6kJ75Fnv8HC4JkF4"; var json = client.DownloadString(uri).ToString(); var jsonObject = JsonConvert.DeserializeObject <RootObject>(json); hotelName = jsonObject.Results.Select(h => h.Name).ToList(); } return(hotelName); }
public IEnumerable <string> asearch_test(double lon, double lan) { var address = "منطقة اللاذقية" + "," + "اللاذقية"; // string s_address = "," + "اللاذقية"; var locationService = new GoogleLocationService(); // GoogleMaps.LocationServices.GoogleLocationService r = locationService.GetRegionFromLatLong(lat, lon); // LocationServices r = new GoogleMaps.LocationServices(); // r= locationService.GetRegionFromLatLong(lat, lon); var g = new GeocodingRequest(); var address_gps = g.Address = address; // g.Region = r.Name; g.Sensor = false; g.Language = "ar"; var response = new GeocodingService().GetResponse(g); var point = locationService.GetLatLongFromAddress(address); AddressData a = locationService.GetAddressFromLatLang(lon, lan); // Directions dir= locationService.GetDirections(point.Latitude, point.Longitude); var s = _ClassifyService.search_test(lon.ToString() + "," + lan.ToString()); //yield return response.Results[0].PlaceId; return(s); // yield return locationService.GetAddressFromLatLang(5 , lon).Address; // return "s"; // return _ClassifyService.search_test(town); }
private void btnCreateCabinet_Click(object sender, EventArgs e) { String rue = textBoxRueCabinet.Text.ToString(); String CP = Passerelle.Passerelle.checkValueIsCorrectNumber(textBoxCPCabinet.Text.ToString()); String ville = Passerelle.Passerelle.checkValueIsCorrect(textBoxVilleCabinet.Text.ToString()); if (rue != "" && CP != "" && ville != "") { var address = rue + CP + " , " + ville; try { var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(address); var latitude = point.Latitude; var longitude = point.Longitude; Cabinet unCabinet = new Cabinet(rue, CP, ville, longitude, latitude); Passerelle.Passerelle.addCabinet(unCabinet); } catch (Exception exeCabinet) { MessageBox.Show("Il ne n'existe pas d'adresse au : " + address); } } else { MessageBox.Show("Les valeurs ne sont pas valides"); } }
protected void LoadGoogleMAP(Int64 locationID) { MaterialRT _materialRT = new MaterialRT(); try { List <ProgramAddresses> AddressList = new List <ProgramAddresses>(); string FullAddress = _materialRT.GetLocationByIID(locationID); // string FullAddress=null; ProgramAddresses MapAddress = new ProgramAddresses(); MapAddress.description = FullAddress; var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(FullAddress); MapAddress.lat = point.Latitude; MapAddress.lng = point.Longitude; AddressList.Add(MapAddress); string jsonString = new JavaScriptSerializer().Serialize(AddressList); //JsonSerializer<List<ProgramAddresses>>(AddressList); ScriptManager.RegisterArrayDeclaration(Page, "markers", jsonString); ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), "GoogleMap();", true); } catch (Exception ex) { LogFileWritten(ex.Message, ex.StackTrace); } }
//public MapPoint GetLatLongFromAddress(string strAddress) //{ // var locationService = new GoogleLocationService(this.Options.ApiKey); // var point = locationService.GetLatLongFromAddress(strAddress); // return point; //} public GeographyPoint GetLatLongFromAddress(string strAddress) { var locationService = new GoogleLocationService(this.Options.ApiKey); var point = locationService.GetLatLongFromAddress(strAddress); return(GeographyPoint.Create(point.Latitude, point.Longitude)); }
public string Define(double latitude, double longitude) { var locationService = new GoogleLocationService(); Region region = locationService.GetRegionFromLatLong(latitude, longitude); return($"{region.ShortCode} {region.Name}"); }
public List <Latitude> Get([FromUri] string add) { Latitude HD = new Latitude(); List <Latitude> latLongList = new List <Latitude>(); string sURL = "https://maps.googleapis.com/maps/api/place/autocomplete/xml?input=" + add + "&types=geocode&language=en&key=AIzaSyAFAfIYYn-j8qsBgk8j4f3RWXEvlJZIhvI"; // var address = "pune"; XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(sURL); XmlNodeList elementList = xmldoc.GetElementsByTagName("description"); for (int i = 0; i < 4; i++) { HD.address = elementList[i].InnerXml; var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(HD.address); HD.latitude = point.Latitude; HD.longitude = point.Longitude; double lat = Convert.ToDouble(HD.latitude); double longi = Convert.ToDouble(HD.longitude); latLongList.Add(HD); } // HotelController h1 = new HotelController(); // return h1.Gethotels(lat,longi); // HotelController.GetDetails(HD); return(latLongList); }
public ActionResult UserProfileEdit(UserProfileModel model) { var user = UserManager.FindById(model.UserId); if (user != null) { var point = new GoogleLocationService().GetLatLongFromAddress((!string.IsNullOrEmpty(model.Address)) ? model.Address : ""); user.Name = model.Name; user.Address = model.Address; user.ConnectEmail = model.ConnectEmail; user.PhoneNumber = model.Phone; user.WeChat = model.WeChat; if (point != null) { user.Location = DbGeography.FromText($"POINT({point.Longitude} {point.Latitude})"); } var result = UserManager.Update(user); if (result.Succeeded) { return(RedirectToAction("UserProfile")); } } return(View(model)); }
private MapPoint FindCityCoordinates(string address) { var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(address); return(point); }
public Customer LongLat(Customer customer) { var gls = new GoogleLocationService("AIzaSyD54AJcNoaVgygF0IQ4oK6Kh7W9d17yrc8"); AddressData[] address = new AddressData[] { new AddressData { Address = customer.Address, City = customer.City, State = customer.State, Country = "USA", Zip = customer.ZipCode } }; try { var latlong = gls.GetLatLongFromAddress(address[0]); var Latitude = latlong.Latitude; var Longitude = latlong.Longitude; customer.Latitude = Latitude; customer.Longtitude = Longitude; } catch (System.Net.WebException ex) { System.Console.WriteLine("Google Maps API Error {0}", ex.Message); } return(customer); }
protected void btnSearchAll_Click(object sender, EventArgs e) { DataTable dt = SqlObject.FetchDataTable("select * from seller"); if (dt.Rows.Count != 0) { for (int i = 0; i < dt.Rows.Count; i++) { var address = dt.Rows[i]["location"].ToString(); var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(address); var latitude = point.Latitude; var longitude = point.Longitude; String htmltext = " <div class='col - md - 3 top - deal - top'><div class='top-deal'>" + "<a href = 'details.aspx' class='mask'>" + "<iframe src = 'https://maps.google.com/maps?q=" + latitude + "," + longitude + "&hl=es;z=14&output=embed'></iframe></ a >" + "<div class='deal-bottom'>" + "<div class='top-deal1'>" + "<h5><a href = 'details.aspx' > " + dt.Rows[i]["location"].ToString() + " </ a ></ h5 >" + "<p> Available Rooms : " + dt.Rows[i]["availableroom"].ToString() + "</p>" + "<p>Rent : $ " + dt.Rows[i]["rent"].ToString() + "</p>" + "</div>" + "<div class='top-deal2'>" + "<a href = 'details.aspx?id=" + dt.Rows[i]["sellerid"].ToString() + "' class='hvr-sweep-to-right more'>More</a>" + "</div>" + "<div class='clearfix'></div>" + "</div>" + "</div>" + "</div>"; LiteralControl div1 = new LiteralControl(htmltext); divAllRooms.Controls.Add(div1); } } }
public static GoogleServiceInfo GetGoogleServiceInfo(string destinationName, string countryName) { var address = $"{destinationName}, {countryName}"; var locationService = new GoogleLocationService(apikey: GoogleUtilitiess.ApiKey); var point = locationService.GetLatLongFromAddress(address); var latitude = point.Latitude; var longitude = point.Longitude; var client = new RestClient(GoogleUtilitiess.BaseUrl); var requestTime = new RestRequest(GoogleUtilitiess.TimeZoneResource, Method.GET); requestTime.AddParameter("location", $"{latitude},{longitude}"); requestTime.AddParameter("timestamp", GoogleUtilitiess.TimeStamp); requestTime.AddParameter("key", GoogleUtilitiess.ApiKey); var responseTime = client.Execute <GoogleTimeZone>(requestTime); var rawOffsetInSeconds = responseTime.Data.RawOffset; var googleServiceInfo = new GoogleServiceInfo { Latitude = latitude, Longitude = longitude, UtcRawOffset = rawOffsetInSeconds, }; return(googleServiceInfo); }
public ActionResult Register(shuli_blog.DAL.BloggingContext.RegisterModel model) { // Attempt to register the user try { var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(model.Address); Address a = new Address(); a.addressName = model.Address; a.lat = point.Latitude; a.len = point.Longitude; db.Addresses.Add(a); db.SaveChanges(); WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Address_ID = a.ID, Role_ID = 2 }); WebSecurity.Login(model.UserName, model.Password); return(RedirectToAction("Index", "")); } catch (MembershipCreateUserException e) { ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)); } // If we got this far, something failed, redisplay form return(View(model)); }
public PartialViewResult ajax_store_products(string storeID, string productname, decimal?fromprice, decimal?toprice, int?page, string lat, string lng) { //instantiate new client and model var client = new HttpClient(); var model = new List <Product>(); var address = db.Users.Find(User.Identity.GetUserId()).Address; var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(address); ViewBag.mylat = point.Latitude; ViewBag.mylng = point.Longitude; if (!String.IsNullOrEmpty(productname)) { ViewBag.userproducts = db.Products.Where(a => a.Name.Contains(productname) && a.Price >= fromprice && a.Price <= toprice); ViewBag.prodcount = db.Products.Where(b => b.Name.Contains(productname)).Count(); var task = client.GetAsync("http://api.goodzer.com/products/v0.1/search_in_store/?storeId=" + storeID + "&query=" + productname + "&priceRange=" + fromprice + ":" + toprice + "&apiKey=f7d93213c281896d44c093a36a4f544a") .ContinueWith((taskwithmsg) => { var response = taskwithmsg.Result; //process content var jsonTask = response.Content.ReadAsAsync <JObject>(); jsonTask.Wait(); var jsonObject = jsonTask.Result; model.AddRange((from JObject jo in (JArray)jsonObject["products"] select new Product { id = jo["id"].ToString(), title = jo["title"].ToString(), url = jo["url"].ToString(), image = jo["image"].ToString(), Price = Convert.ToDecimal(jo["price"]) } )); }); if (Request.HttpMethod != "GET") { page = 1; } int pageSize = 2; int pageNumber = (page ?? 1); ViewBag.pageSize = pageSize; ViewBag.pageNumber = pageNumber; task.Wait(); ViewBag.myModel = model.OrderBy(a => a.Name).ToPagedList(pageNumber, pageSize); ViewBag.pagecount = model.OrderBy(a => a.Name).ToPagedList(pageNumber, pageSize).PageCount; ViewBag.prevpage = model.OrderBy(a => a.Name).ToPagedList(pageNumber, pageSize).HasPreviousPage; ViewBag.nextpage = model.OrderBy(a => a.Name).ToPagedList(pageNumber, pageSize).HasNextPage; ViewBag.modelcount = model.Count(); ViewBag.storelat = lat; ViewBag.storelng = lng; ViewBag.productname = productname; ViewBag.storeID = storeID; ViewBag.fromprice = fromprice; ViewBag.toprice = toprice; } //send get request to specified Uri as an asynchorous operation return(PartialView(model)); }
public async Task <Response> Handle(Request request, CancellationToken cancellationToken) { var locationService = new GoogleLocationService("AIzaSyCNSEn1UjPshpFTg55dn8IsJimWQbDbdao"); List <CarLocation> carLocations = new List <CarLocation>(); var cars = await _session.Query <Car>() .ToListAsync(); foreach (var car in cars) { var address = car.LocationPickUp; var point = locationService.GetLatLongFromAddress(address); if (point != null) { var lat = point.Latitude; var lon = point.Longitude; var coordinate = new Coordinate(lat, lon); //coordinates.Add(coordinate); var carLocation = new CarLocation(car.Id, coordinate); carLocations.Add(carLocation); } } //TODO // return the car with her coordinates return(new Response { //Coordinates = coordinates CarLocations = carLocations }); }
public static string GetAddressFromLatLon(GeoLocation location) { try { if (locationService == null) { locationService = new GoogleLocationService(Data.AppConstants.GMapApiKey); } var result = locationService.GetAddressFromLatLang(location.Latitude, location.Longitude); if (result != null) { return(result.Address); } else { return(string.Empty); } } catch (Exception) { return(string.Empty); } }
public void GetGeolocFromAddress() { if (!IsConnectedToInternet()) { FOutputStatus[0] = "Can't get geoloc as Internet is f****d bro."; FLogger.Log(LogType.Debug, "Can't get geoloc as Internet is f****d bro."); FOutputStatusBool[0] = false; loggedIn = false; ClearOutputPins(); } else { try { var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(FAddressForCoordinates[0]); FOutputCoordinates.SliceCount = 2; FOutputCoordinates[0] = point.Latitude; FOutputCoordinates[1] = point.Longitude; FOutputStatus[0] = "DONE! Got geolocation from address, f*****g riiiiiiiight!"; FLogger.Log(LogType.Debug, "DONE! Got geolocation from address, f*****g riiiiiiiight!"); } catch { FOutputStatus[0] = "Could not get geocoordinates from address."; FLogger.Log(LogType.Debug, "Could not get geocoordinates from address."); } } }
public async Task <ActionResult <IEnumerable <Flight> > > GetLanLng(Address address) { var address1 = "Stavanger, Norway"; AddressData addressData = new AddressData(); addressData.City = "Stavanger"; addressData.Country = "Norway"; var locationService = new GoogleLocationService(); MapPoint point; try { point = locationService.GetLatLongFromAddress(addressData); } catch (Exception e) { throw; } var latitude = point.Latitude; var longitude = point.Longitude; return(Ok()); }
public ActionResult CUSTOMER_Create([DataSourceRequest] DataSourceRequest request, CUSTOMER cUSTOMER) { if (ModelState.IsValid) { var address = cUSTOMER.cust_dir; var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(address); var latitude = point.Latitude; var longitude = point.Longitude; var entity = new CUSTOMER { cust_id = cUSTOMER.cust_id, cust_name = cUSTOMER.cust_name, cust_phone = cUSTOMER.cust_phone, cust_mail = cUSTOMER.cust_mail, cust_dir = cUSTOMER.cust_dir, cust_longitud = latitude.ToString(), cust_latitud = longitude.ToString(), cust_km = cUSTOMER.cust_km, }; db.CUSTOMER.Add(entity); db.SaveChanges(); cUSTOMER.cust_id = entity.cust_id; } return(Json(new[] { cUSTOMER }.ToDataSourceResult(request, ModelState))); }
public virtual void SetaCoordenadas() { if (string.IsNullOrEmpty(this.Endereco)) { return; } GoogleLocationService g = new GoogleLocationService(); AddressData a = new AddressData(); try { a.Address = this.Endereco + ", " + this.Numero; //"Avenida Lins de Vasconcelos, 473"; a.City = this.Cidade; //"São Paulo"; a.Country = "Brasil"; //"São Paulo" a.State = this.UF; //"SP"; a.Zip = this.CEP; //"01537-000"; var ponto = g.GetLatLongFromAddress(a); this.Latitude = ponto.Latitude; this.Longitude = ponto.Longitude; ponto = null; } catch { //todo: log } g = null; a = null; }
public void GetAddress(string add) { var location = new GoogleLocationService(); string ur = "https://maps.googleapis.com/maps/api/place/autocomplete/xml?input=" + add + "&types=geocode&language=en&key=AIzaSyAFAfIYYn-j8qsBgk8j4f3RWXEvlJZIhvI"; XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(ur); List <Address> lst = new List <Address>(); XmlNodeList elementList = xmldoc.GetElementsByTagName("description"); for (int i = 0; i < 3; i++) { Address address = new Address(); string str = elementList[i].InnerXml; var Location = location.GetLatLongFromAddress(str); address.latitude = Location.Latitude; address.longitude = Location.Longitude; address.add = str; lst.Add(address); } Post(lst[0]); }
private void btnEditCabinet_Click(object sender, EventArgs e) { String rue = textBoxRueCabinet.Text.ToString(); String CP = textBoxCPCabinet.Text.ToString(); String ville = textBoxVilleCabinet.Text.ToString(); var address = rue + CP + " , " + ville; try { var locationService = new GoogleLocationService(); var point = locationService.GetLatLongFromAddress(address); var latitude = point.Latitude; var longitude = point.Longitude; Cabinet unCabinet = (Cabinet)comboBoxCabinet.SelectedItem; unCabinet.setCP(CP); unCabinet.setRue(rue); unCabinet.setVille(ville); unCabinet.setLatitude(latitude); unCabinet.setLongitude(longitude); Passerelle.Passerelle.editCabinet(unCabinet); } catch (Exception exe) { MessageBox.Show("Il ne n'existe pas d'adresse au : " + address); } }
public async Task AddShopAsync(ClaimsPrincipal user, ShopViewModel shopViewModel) { Shop shop = new Shop(); var addressData = new AddressData { Address = shopViewModel.Address, City = shopViewModel.City.ToUpper(), Country = "Italy" }; var gls = new GoogleLocationService(); var latlong = gls.GetLatLongFromAddress(addressData); var latitude = latlong.Latitude; var longitude = latlong.Longitude; shop.Name = shopViewModel.Name; shop.ShortDesc = shopViewModel.ShortDesc; shop.City = shopViewModel.City; shop.Address = shopViewModel.Address; shop.Website = shopViewModel.Website; shop.Phone = shopViewModel.Phone; shop.Latitude = latitude; shop.Longitude = longitude; shop.InsertDate = DateTime.Now; shop.InsertUserId = user.GetUserId(); shop.UserId = user.GetUserId(); _dbContext.Shop.Add(shop); await _dbContext.SaveChangesAsync(); }
public static void Main(string[] args) { AddressData[] addresses = new AddressData[] { new AddressData // Belgium { Address = "Rue du Cornet 6", City = "VERVIERS", State = null, Country = "Belgium", Zip = "B-4800" }, new AddressData { Address = "1600 Pennsylvania ave", City = "Washington", State = "DC" } }; var gls = new GoogleLocationService(); foreach (var address in addresses) { var latlong = gls.GetLatLongFromAddress(address); var Latitude = latlong.Latitude; var Longitude = latlong.Longitude; System.Console.WriteLine("Address ({0}) is at {1},{2}", address, Latitude, Longitude); } System.Console.ReadLine(); }
public ActionResult Edit([Bind(Include = "DepartmentId,Name,AddressLine1,AddressLine2,City,Country,PostalCode,CategoryId,OrganisationId")] Department department, FormCollection collection) { if (ModelState.IsValid) { int orgId = 0; orgId = Convert.ToInt32(collection.Get("OrgId")); department.OrganisationId = orgId; var gls = new GoogleLocationService(); AddressData address = new AddressData() { Address = department.AddressLine1 + "' " + department.AddressLine2, City = department.City, Country = department.Country, State = "", Zip = department.PostalCode }; var latlng = gls.GetLatLongFromAddress(address); department.Latitude = Convert.ToDouble(latlng.Latitude, CultureInfo.InvariantCulture); department.Longitude = Convert.ToDouble(latlng.Longitude, CultureInfo.InvariantCulture); var jurisdiction = Convert.ToDecimal(collection.Get("jurisdiction")); department.Jurisdiction = jurisdiction; db.Entry(department).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Management", "Organisations", null)); } ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "Name", department.CategoryId); ViewBag.OrganisationId = new SelectList(db.Organisations, "OrganisationId", "Name", department.OrganisationId); return(View(department)); }
static void Main(string[] args) { System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US"); //System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("uk_UA"); string address = "Оболонський проспект, 36Д, Київ"; /*string strUrl = string.Format("http://maps.google.com./maps/api/geocode/json&address={0}&sensor=false", System.Web.HttpUtility.UrlEncode(address));*/ GoogleLocationService locationService = new GoogleLocationService(); MapPoint point = locationService.GetLatLongFromAddress(address); // витягти адресу з координат (можна ) //locationService.GetAddressFromLatLang(point.Latitude, point.Longitude); System.Console.WriteLine($"{point.Latitude},{point.Longitude}"); //50.519432,30.5003759 // витягти адресу з координат (можна ) AddressData add = locationService.GetAddressFromLatLang(50.519432, 30.5003759); System.Console.WriteLine(add.Address); }
public void SetCoordinatesHotel(int hotelId) { var hotel = db.Hotels.Find(hotelId); AddressData loc = new AddressData { Address = hotel.Address.Street, City = hotel.Address.City, State = hotel.Address.Voivodeship.Name, Country = "Poland", Zip = hotel.Address.PostalCode }; var gls = new GoogleLocationService(); try { var latlong = gls.GetLatLongFromAddress(loc); hotel.Address.Latitude = latlong.Latitude; hotel.Address.Longitude = latlong.Longitude; db.SaveChanges(); } catch (System.Net.WebException ex) { BackgroundJob.Enqueue(() => SetCoordinatesHotel(hotel.HotelId)); } }
public coordinates GetLatLngByAddress(string address) { try { var googleAPIKey = _config.Value.GoogleAPIKey; var locationService = new GoogleLocationService(apikey: googleAPIKey); MapPoint point = locationService.GetLatLongFromAddress(address); if (point == null) { return(null); } else { var response = new coordinates { Latitude = point.Latitude, Longitude = point.Longitude }; return(response); } } catch (Exception ex) { //return string.Format("Google Maps API Error {0}", ex.Message); return(null); } }
public static void Main(string[] args) { AddressData[] addresses = new AddressData[] { new AddressData // Belgium { Address = "Rue du Cornet 6", City = "VERVIERS", State = null, Country = "Belgium", Zip = "B-4800" }, new AddressData { Address = "1600 Pennsylvania ave", City = "Washington", State = "DC" }, new AddressData { Address = "407 N Maple Dr. #1", City = "Beverly Hills", State = "CA" } }; var gls = new GoogleLocationService(); foreach (var address in addresses) { try { var latlong = gls.GetLatLongFromAddress(address); var latitude = latlong.Latitude; var longitude = latlong.Longitude; System.Console.WriteLine("Address ({0}) is at {1},{2}", address, latitude, longitude); var reversedAddress = gls.GetAddressFromLatLang(latitude, longitude); System.Console.WriteLine("Reversed Address from ({1},{2}) is {0}", reversedAddress, latitude, longitude); System.Console.WriteLine("======================================="); } catch(System.Net.WebException ex) { System.Console.WriteLine("Google Maps API Error {0}", ex.Message); } } System.Console.ReadLine(); }