I am calculating distance between two Latitude and long
one is the current location of the user and another from the database, I want here if the lat-long distance is between 4km then show data
how can I do it using C#?
Answering to my question, as it was originally asked by RameshwarLate
So here are the steps, which you need to achieve:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YourApiKeyHere&callback=initMap">
</script>?
var map, infoWindow,CurrentLat,CurrentLong;
function initMap() {
//Just to intialize maps api
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
CurrentLat = position.coords.latitude;
CurrentLong = position.coords.longitude;
//Save CurrentLat, CurrentLong here in Javascript or pass to C# using ajax
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}?
//pass address here like 123,Street,City , it will give you lat/long
public string ConvertAddressIntoLatLong(string address)
{
var locationService = new GoogleLocationService();
var point = locationService.GetLatLongFromAddress(address);
var latitude = point.Latitude;
var longitude = point.Longitude;
return (latitude+","+longitude);
}?
Note: You may need to install NuGet package to GeoLocation
public static double DistanceTo(double lat1, double lon1, double lat2, double lon2, char unit = 'K')
{
double rlat1 = Math.PI * lat1 / 180;
double rlat2 = Math.PI * lat2 / 180;
double theta = lon1 - lon2;
double rtheta = Math.PI * theta / 180;
double dist =
Math.Sin(rlat1) * Math.Sin(rlat2) + Math.Cos(rlat1) *
Math.Cos(rlat2) * Math.Cos(rtheta);
dist = Math.Acos(dist);
dist = dist * 180 / Math.PI;
dist = dist * 60 * 1.1515;
switch (unit)
{
case 'K': //Kilometers -> default
return dist * 1.609344;
case 'N': //Nautical Miles
return dist * 0.8684;
case 'M': //Miles
return dist;
}
return dist;
}?
Hope this helps, please upvote and share your thoughts by commenting on this answer.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly