Example #1
0
        public void RefreshCoordinates()
        {
            using (var repositoriesContainer = new InnostarRepositoriesContainer())
            {
                var organizationsList = repositoriesContainer.RepositoryFor <Organization>().GetAll().ToList();

                IGeoCoder geoCoder = new GoogleGeoCoder();

                foreach (var mapObject in organizationsList)
                {
                    var organization = mapObject;

                    var addresses = geoCoder.GeoCode(organization.Address).ToList();

                    if (addresses.Any())
                    {
                        organization.Latitude  = addresses.First().Coordinates.Latitude;
                        organization.Longitude = addresses.First().Coordinates.Longitude;
                    }
                }

                repositoriesContainer.RepositoryFor <Organization>().Save(organizationsList);
                repositoriesContainer.ApplyChanges();
            }
        }
Example #2
0
        /// <summary>
        /// Determines whether the specified value is valid.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <returns>
        ///     <c>true</c> if the specified value is valid; otherwise, <c>false</c>.
        /// </returns>
        public override bool IsValid(object value)
        {
            var address = GetPropertyValue(value, AddressPropertyName);

            if (address.IsNullOrEmpty())
            {
                return(AllowNull);
            }

            var geocoder = new GoogleGeoCoder(); // key not needed
            var result   = geocoder.GeoCode(address.Trim()).FirstOrDefault();

            if (result == null)
            {
                // No results
                return(false);
            }
            _result = result;                                                             // store so that other classes that inherit from this attribute can access the result without re-geocoding
            SetPropertyValue(value, result.Coordinates.Latitude, LatitudePropertyName);   // set latitude
            SetPropertyValue(value, result.Coordinates.Longitude, LongitudePropertyName); // set longitude

            var fullAddress = result.FormattedAddress;                                    // (result.Street.HasValue() && result.Street.Trim().HasValue() ? result.Street + ", " : "") + result.City + " " + result.State + ", " + result.Country + " " + result.PostalCode;

            SetPropertyValue(value, fullAddress, AddressPropertyName);                    // set exact address

            return(true);
        }
        public void AddStreet(ISheet sheet, int row, string postCode)
        {
            //IGeoCoder geoCoder = new BingMapsGeoCoder("AoOO7N-PyP6n3dBlaVYM8_tKhG2Hslm9yL088fTftMQkV9H1LmQnMysWTedYqiSK");
            //IGeoCoder geoCoder = new GoogleGeoCoder("AIzaSyD4qJe0Memxi9X6YjK5kHutrfiAtSm41rM");
            IGeoCoder geoCoder = new GoogleGeoCoder();
            string    streetNameNumber;

            Address[] addresses;
            while (true)
            {
                try
                {
                    Location latLang = geoCoder.GeoCode(postCode).ToArray()[0].Coordinates;
                    addresses        = geoCoder.ReverseGeocode(latLang.Latitude, latLang.Longitude).ToArray();
                    streetNameNumber = addresses[0].FormattedAddress.Split(',')[0];
                    break;
                }
                catch (Exception)
                {
                }
            }

            bool hasHouseNumber = System.Text.RegularExpressions.Regex.IsMatch(streetNameNumber, @"\d");
            int  count          = 0;

            if (hasHouseNumber)
            {
                count = 1;
            }

            string[] streetNameNumberArray = addresses[0].FormattedAddress.Split(',')[0].Split(' ');
            //string town = addresses[0].FormattedAddress.Split(',')[1].Split(' ')[0];
            string town       = addresses[0].FormattedAddress.Split(',')[1].Trim();
            string streetName = "";

            while (count < streetNameNumberArray.Length)
            {
                streetName += streetNameNumberArray[count];
                if (count != streetNameNumberArray.Length - 1)
                {
                    streetName += " ";
                }
                count++;
            }
            sheet.CreateRow(row);
            sheet.GetRow(row).CreateCell(0).SetCellValue(postCode);
            sheet.GetRow(row).CreateCell(1).SetCellValue(streetName);
            sheet.GetRow(row).CreateCell(2).SetCellValue(town);
            sheet.GetRow(row).CreateCell(3).SetCellValue(addresses[0].Coordinates.Latitude);
            sheet.GetRow(row).CreateCell(4).SetCellValue(addresses[0].Coordinates.Longitude);
            Console.WriteLine(postCode + " " + streetName + " " + town + addresses[0].Coordinates.Latitude + addresses[0].Coordinates.Longitude);
        }
    private static List <ImportFields> GetLocationForOldData(List <ImportFields> listdata)
    {
        int numRecord = listdata.Count;
        List <ImportFields> outputList = new List <ImportFields>();
        GoogleGeoCoder      geoCoder;
        ImportFields        writedata;
        string physicalLocation;

        for (int i = 0; i < numRecord; i++)
        {
            writedata = listdata.ElementAt(i);
            if (!writedata.Longitude.HasValue)
            {
                geoCoder = new GoogleGeoCoder();
                bool      getLocation  = false;
                Address[] matchAddress = null;
                int       numTry       = 0;
                while (!getLocation && numTry < 5)
                {
                    try
                    {
                        numTry++;
                        physicalLocation = writedata.LandscapeStreet + " " +
                                           writedata.LandscapeZipcode + " " +
                                           writedata.LandscapeCity + " " +
                                           writedata.LandscapeState + " " +
                                           writedata.LandscapeCountry;
                        matchAddress = geoCoder.GeoCode(physicalLocation).ToArray();
                        getLocation  = true;
                        break;
                    }
                    catch (Exception ex)
                    {
                        System.Threading.Thread.Sleep(2000);
                        //  Pollinator.Common.Logger.Error("Error occured at " + typeof(Admin_ImportData).Name + "Get location from address. Exception:", ex);
                    }
                }
                if (matchAddress != null && matchAddress.Length > 0)
                {
                    writedata.Latitude  = matchAddress[0].Coordinates.Latitude;
                    writedata.Longitude = matchAddress[0].Coordinates.Longitude;
                    if (matchAddress.Length > 1)
                    {
                        writedata.FuzyLocation = true;
                    }
                }
            }
            outputList.Add(writedata);
        }
        return(outputList);
    }
Example #5
0
        public GeoPoint DetermineAddressCoordinate(string address)
        {
            IGeoCoder geoCoder = new GoogleGeoCoder();

            var result = new GeoPoint();

            var addressCoordinates = geoCoder.GeoCode(address).FirstOrDefault();

            if (addressCoordinates != null)
            {
                result.Latitude  = addressCoordinates.Coordinates.Latitude;
                result.Longitude = addressCoordinates.Coordinates.Longitude;
            }

            return(result);
        }
Example #6
0
        public static async Task <string> Google(string freeFormAddress)
        {
            var g           = new GoogleGeoCoder();
            var jsonContent = await g.Find(new ApiGeocodeQuery { Q = freeFormAddress });

            var data    = jsonContent.FromJson <GoogleJson>();
            var results = data.Results.FirstSafe() ?? new Formats.JSON.Google.Result
            {
                Geometry = new Geometry
                {
                    Location = new Formats.JSON.Google.Location()
                }
            };
            var latlng = results.Geometry.Location;

            return(string.Format(LatLngFmt, freeFormAddress, latlng.Lat, latlng.Lng));
        }
        public static Coord GetLatLong(String accessKey, String address1, String address2, String suburb, String state, String postcode, String country)
        {
            Coord  coord   = new Coord();
            String address = address1;

            if (address2 != String.Empty)
            {
                address += " " + address2;
            }
            IGeoCoder geoCoder = new GoogleGeoCoder(accessKey);

            Address[] addresses = geoCoder.GeoCode(address, suburb, state, postcode, country);
            if (!addresses.IsEmpty())
            {
                coord.Latitude  = addresses[0].Coordinates.Latitude;
                coord.Longitude = addresses[0].Coordinates.Longitude;
            }
            return(coord);
        }
Example #8
0
        public override bool IsValid(object value)
        {
            if (base.IsValid(value))
            {
                var city       = _result.Components.Where(c => c.Types[0] == GoogleAddressType.Locality).FirstOrDefault();
                var state      = _result.Components.Where(c => c.Types[0] == GoogleAddressType.AdministrativeAreaLevel1).FirstOrDefault();
                var country    = _result.Components.Where(c => c.Types[0] == GoogleAddressType.Country).FirstOrDefault();
                var postalcode = _result.Components.Where(c => c.Types[0] == GoogleAddressType.PostalCode).FirstOrDefault();
                var zipAddress = ProcessAddressComponent(city) + ProcessAddressComponent(state) + ProcessAddressComponent(country) + ProcessAddressComponent(postalcode);

                if (!(FilterToZipCodeOnlyPropertyName == null && FilteredAddressPropertyName == null)) // if filtering has been enabled, execute filter
                {
                    if (GetPropertyValue(value, FilterToZipCodeOnlyPropertyName) == "2")               // Zip code only
                    {
                        SetPropertyValue(value, zipAddress, FilteredAddressPropertyName);

                        // Find new lat-long
                        var geocoder = new GoogleGeoCoder(); // key not needed
                        var result   = geocoder.GeoCode(zipAddress.Trim()).FirstOrDefault();
                        if (result != null)                  // we have results
                        {
                            SetPropertyValue(value, result.Coordinates.Latitude, FilteredLatitudePropertyName);
                            SetPropertyValue(value, result.Coordinates.Longitude, FilteredLongitudePropertyName);
                        }
                        else
                        {
                            SetPropertyValue(value, null, FilteredLatitudePropertyName);
                            SetPropertyValue(value, null, FilteredLongitudePropertyName);
                        }
                    }
                    else
                    {
                        SetPropertyValue(value, null, FilteredAddressPropertyName); // null indicates that filtered address is the same as actual/exact address
                    }
                }

                return(true);
            }
            return(false);
        }
        private void loadMap()
        {
            try
            {
                //check if event
                if (Request["event"] != null)
                {
                    umbraco.presentation.nodeFactory.Node e = new umbraco.presentation.nodeFactory.Node(Convert.ToInt32(Request["event"]));


                    ShowResult(e.Name, new Location(
                                   Convert.ToDouble(e.GetProperty("latitude").Value, Utility.GetNumberFormatInfo()),
                                   Convert.ToDouble(e.GetProperty("longitude").Value, Utility.GetNumberFormatInfo())));
                }

                else
                {
                    //address supplied
                    if (Request["s"] != null && Request["s"] != string.Empty)
                    {
                        litMultipleResults.Text = MultipleResultsCaption;

                        litResults.Text     = string.Empty;
                        pnlMultiple.Visible = false;

                        IGeoCoder geoCoder  = new GoogleGeoCoder(Utility.GetGoogleMapsKey());
                        Address[] addresses = geoCoder.GeoCode(Request["s"]);
                        if (addresses.Length == 0)//no results
                        {
                            pnlCreateTopic.Visible = false;

                            litResults.Text = umbraco.macro.GetXsltTransformResult(umbraco.content.Instance.XmlContent, umbraco.macro.getXslt(ResultsXslt));

                            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "test",
                                                                umbraco.macro.GetXsltTransformResult(umbraco.content.Instance.XmlContent, umbraco.macro.getXslt("MemberLocatorScript.xslt")), true);
                        }
                        else
                        {
                            if (addresses.Length > 1)//multiple results, need to choose first
                            {
                                //show the first result
                                ShowResult(addresses[0].ToString(), new Location(addresses[0].Coordinates.Latitude, addresses[0].Coordinates.Longitude));

                                //rblLocations.Items.Clear();
                                //foreach (Address address in addresses)
                                //{
                                //    rblLocations.Items.Add(new ListItem(address.ToString(), address.Coordinates.Latitude.ToString(Utility.GetNumberFormatInfo()) + "," + address.Coordinates.Longitude.ToString(Utility.GetNumberFormatInfo())));
                                //}
                                //pnlMultiple.Visible = true;
                            }
                            else// single result, ok show results
                            {
                                ShowResult(addresses[0].ToString(), new Location(addresses[0].Coordinates.Latitude, addresses[0].Coordinates.Longitude));
                            }
                        }
                    }
                    else //node address, use member location
                    {
                        //use member location
                        Member   current        = Member.GetCurrentMember();
                        Location memberLocation = new Location(
                            double.Parse(current.getProperty("latitude").Value.ToString(), Utility.GetNumberFormatInfo()),
                            double.Parse(current.getProperty("longitude").Value.ToString(), Utility.GetNumberFormatInfo())
                            );

                        ShowResult(current.getProperty("location").Value.ToString(), memberLocation);
                    }
                }
            }
            catch (Exception ex) {
                if (Request["debug"] == null)
                {
                    litResults.Text = "Error displaying locator results";
                }
                else
                {
                    litResults.Text = ex.Message + "</br>" + ex.StackTrace;
                }
            }

            // }
        }
Example #10
0
        public static List <ProviderWrapper> Search(SearchRequest searchRequest)
        {
            List <ProviderResult> providerResults = MemoryStorageCaching.Get <List <ProviderResult> >(CACHE_KEY, SECTION)
                                                    ?? new List <ProviderResult>();

            if (!providerResults.Any())
            {
                using (ApplicationContext context = new ApplicationContext())
                {
                    providerResults = context.ProviderResult.Include(t => t.ContactInformations).Include(t => t.Addresses).Include(t => t.ProvidedServices).ToList();
                    MemoryStorageCaching.Set(CACHE_KEY, providerResults, SECTION, new CacheItemPolicy
                    {
                        AbsoluteExpiration = DateTimeOffset.Now.AddHours(1)
                    });
                }
            }

            List <ProviderResult> filteredList = new List <ProviderResult>();
            LatLong latLong;

            foreach (ProviderResult providerResult in providerResults)
            {
                foreach (string filter in searchRequest.Filters)
                {
                    providerResult.ProvidedServices    = providerResult.ProvidedServices.Distinct(new ServicesEquality()).ToList();
                    providerResult.ContactInformations = providerResult.ContactInformations.Distinct(new ContactEquality()).ToList();

                    if (filter.Any())
                    {
                        if (providerResult.ProvidedServices.Any(t => t.Name.ToLower().Contains(filter.ToLower())))
                        {
                            filteredList.Add(providerResult);
                        }
                    }
                    else
                    {
                        filteredList.Add(providerResult);
                    }
                }
            }

            if (!searchRequest.Query.IsValidLatLong(out latLong))
            {
                if (!string.IsNullOrEmpty(searchRequest.Query))
                {
                    Models.GeoLocation latLongRequest = new GoogleGeoCoder().GetLatLong(searchRequest.Query);
                    latLong = new LatLong
                    {
                        Longitude = latLongRequest.Longitude,
                        Latitude  = latLongRequest.Latitude
                    };
                }
            }

            if (latLong == null)
            {
                throw new Exception("Invalid Query Provided");
            }

            List <ProviderWrapper> providerWrappers = GeoLocations.GetProviderDistances(filteredList, latLong.Latitude, latLong.Longitude, searchRequest.Range);

            return(providerWrappers.Take(searchRequest.Limit).ToList());
        }
        public static Task <IEnumerable <Position> > GeoCodeAsync(string address)
        {
            IGeoCoder geocoder = new GoogleGeoCoder();

            return(geocoder.GetPositionsForAddressAsync(address));
        }
 protected override IGeoCoder CreateGeoCoder()
 {
     geoCoder = new GoogleGeoCoder();
     return(geoCoder);
 }
    private List <ImportFields> ParseDemoInfo(string filePath, string sDirPath)
    {
        string content = File.ReadAllText(filePath);

        File.Delete(filePath);

        // Parse content
        string[] stringSeparators = new string[] { "\r\n" };
        string[] lines            = content.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);

        int numRecord = lines.Length;
        List <ImportFields> listData       = new List <ImportFields>();
        List <ImportFields> notConvertList = new List <ImportFields>();
        ImportFields        data;
        IGeoCoder           geoCoder = new GoogleGeoCoder();

        string nameList = "Tom, Marry, Adinath, Ajitesh, Akshaj, Akshobhya, Ameyatma, Badri, Badrinath, Bhudhav, Chakradev, Chhatrabhuj, Eashan, Eha, Eka, Ekana, Evyavan, Harinarayan, Hemang, Ijay, Indivar, Ish, Jaipal, Jaithra, Kamalakar, Kamalkant, Kamalnath, Lakshmidhar, Lakshmigopal, Lakshmiraman, Liladhar, Lohitaksh, Lohitaksha, Loknath, Lokranjan, Madhuban, Mahakram, Mahatru, Namish, Narahari, Nityanta, Padmanabha, Padmapati, Padmesh, Parmesh, Phanindranath, Pramodan, Rakshan, Ramakaant, Ramashray, Ranganath, Ratannabha, Ratnabhu, Ratnanidhi, Sadabindu, Sadru, Sahishnu, Samarendra, Samarendu, Samarjit, Samavart, Samendu, Saprathas, Satanand, Satkartar, Satveer,Tommy, Denny, Herry, Nate, Yathavan, David, Aadinath, Aaditeya, Zacharry, Aamod, Zuhayr";

        string[] firstnames = nameList.Split(new char[] { '\n', ',' });

        string orgNameList = "Coca, Pollinator, Friendly Farmers, Microsoft, Hobbyist, Beekeeper, Gardener";

        string[] orgNames     = orgNameList.Split(new char[] { '\n', ',' });
        int      numFirstName = firstnames.Length;
        string   physicalLocation;
        Random   random = new Random();

        for (int i = 1; i < numRecord; i++)
        {
            data = new ImportFields();
            string[] values = ImportExportUltility.GetCsvRecord(lines[i]);
            if (values.Length > 2)
            {
                physicalLocation = values[1].Replace("See map: Google Maps ", "");
                string[] sAddress       = physicalLocation.Split(new char[] { '\n', ',' }, StringSplitOptions.RemoveEmptyEntries);
                int      len            = sAddress.Length;
                int      startDataIndex = 0;
                while (string.IsNullOrWhiteSpace(sAddress[startDataIndex]) && startDataIndex < len)
                {
                    startDataIndex++;
                }
                if (startDataIndex < len)
                {
                    data.LandscapeStreet = sAddress[startDataIndex].Trim();
                }
                if (startDataIndex + 1 < len)
                {
                    data.LandscapeZipcode = sAddress[startDataIndex + 1].Trim();
                }
                if (startDataIndex + 2 < len)
                {
                    data.LandscapeCity = sAddress[startDataIndex + 2].Trim();
                }
                data.LandscapeState   = values[2].Trim();
                data.Premium          = 1;
                data.PollinatorSize   = random.Next(1, 8);
                data.PollinatorType   = random.Next(1, 9);
                data.FirstName        = firstnames[random.Next(1, numFirstName - 1)];
                data.OrganizationName = orgNames[random.Next(1, 8)];
                data.PhotoUrl         = "";//UploadFiles/458586204/Burts Bees logo.png";

                if (IS_GET_LOCATION)
                {
                    //Get location from address
                    physicalLocation = physicalLocation.Replace("\n", "").Trim();

                    geoCoder = new GoogleGeoCoder();
                    bool      getLocation  = false;
                    Address[] matchAddress = null;
                    int       numTry       = 0;
                    while (!getLocation && numTry < 5)
                    {
                        try
                        {
                            matchAddress = geoCoder.GeoCode(physicalLocation).ToArray();
                            getLocation  = true;
                            numTry++;
                            break;
                        }
                        catch (Exception ex)
                        {
                            System.Threading.Thread.Sleep(2000);
                            //  Pollinator.Common.Logger.Error("Error occured at " + typeof(Admin_DataMigration).Name + "Get location from address. Exception:", ex);
                        }
                    }

                    if (matchAddress != null && matchAddress.Length > 0)
                    {
                        data.Latitude  = matchAddress[0].Coordinates.Latitude;
                        data.Longitude = matchAddress[0].Coordinates.Longitude;
                        listData.Add(data);
                    }
                    else
                    {
                        data.LineNumber       = (i + 1).ToString();
                        data.PhysicalLocation = physicalLocation;
                        notConvertList.Add(data);
                    }
                }
                else
                {
                    if (i != 29 && i != 53)
                    {
                        listData.Add(data);
                    }
                }
            }
        }

        WriteCsvFile(listData, sDirPath, @"\output.csv");

        if (IS_GET_LOCATION)
        {
            //write file to check error line (can't get location)
            var    csv     = new StringBuilder();
            string newLine = "LineNumber,PhysicalLocation,OrganizationName,PollinatorSize,PollinatorType, LandscapeCity,LandscapeState,LandscapeZipcode," + Environment.NewLine;
            csv.Append(newLine);
            for (int i = 0; i < notConvertList.Count; i++)
            {
                ImportFields writedata = notConvertList.ElementAt(i);
                newLine = string.Format("{0}, \"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\",\"{6}\",\"{7}\",{8}",
                                        writedata.LineNumber,
                                        writedata.PhysicalLocation,
                                        writedata.OrganizationName,
                                        writedata.PollinatorSize,
                                        writedata.PollinatorType,
                                        writedata.LandscapeCity,
                                        writedata.LandscapeState,
                                        writedata.LandscapeZipcode,
                                        Environment.NewLine);
                csv.Append(newLine);
            }

            File.WriteAllText(sDirPath + @"\output_error.csv", csv.ToString());
        }

        return(listData);
    }