Wednesday 8 April 2015

Find Latitude and Longitude of Location using address in C#

        public static List<float> GetLatLongOfAddress(string Address)
        {
            WebClient webClient = new WebClient();
            webClient.QueryString.Add("address", Address);
            string result = webClient.DownloadString("https://maps.googleapis.com/maps/api/geocode/json");
            var json = JObject.Parse(result);
            var loc = json["results"].First()["geometry"]["location"];
            return new List<float>
            {
                float.Parse(Regex.Replace((string)loc["lat"], "[^0-9A-Za-z.-]+", " ").Trim()),
                float.Parse(Regex.Replace((string)loc["lng"], "[^0-9A-Za-z.-]+", " ").Trim())
            };
        }
 

Find distance between two locations using their Latitudes and Longitudes in C#

        public static float GetDistanceBetween(List<float> location1, List<float> location2)
        {
            var lat1 = location1[0];
            var lat2 = location2[0];
            var lon1 = location1[1];
            var lon2 = location2[1];
            var R = 6371; // Radius of the earth in km
            var dLat = deg2rad(lat2 - lat1);  // deg2rad below
            var dLon = deg2rad(lon2 - lon1);
            var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
                    Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) *
                    Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
            var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
            var d = R * c; // Distance in km
            return (float)d;
        }

        private static double deg2rad(double deg)
        {
            return deg * (Math.PI / 180);
        }

No comments:

Post a Comment