In this article I will explain with an example, how to find the Address of a location using Geographical coordinates i.e. Latitude and Longitude using the Google Maps Geocoding API in ASP.Net Core (.Net Core) MVC.
Getting Google API Client ID and Client Secret
In order to use Google Account API for login, you will need to create an Application in Google Console and get Client ID and Client Secret. For more details please refer the following article.
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, simple the View is returned.
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
View
HTML Markup
The View consists of two HTML INPUT TextBoxes and an HTML Button.
The Button has been assigned with a
JavaScript onclick event handler.
When the Button is clicked, the
GetAddress JavaScript function is called.
Inside the
GetAddress JavaScript function, the values of Latitude and Longitude are fetched from their respective TextBoxes.
Then, using the Latitude and Longitude values the Google Maps Geocoding API LatLng object is created.
Next, the geocode function of the Geocoder object is called and the LatLng object is passed as parameter.
Finally, if
GeocoderStatus is OK then the
formatted_address of the location is displayed using
JavaScript Alert Message Box.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
Latitude:
<input type="text" id="txtLatitude" value="18.92488028662047" />
Longitude:
<input type="text" id="txtLongitude" value="72.8232192993164" />
<input type="button" value="Get Address" onclick="return GetAddress()" />
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=<API KEY>"></script>
<script type="text/javascript">
function GetAddress() {
var lat = document.getElementById("txtLatitude").value;
var lng = document.getElementById("txtLongitude").value;
var latlng = new google.maps.LatLng(lat, lng);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
alert("Location: " + results[1].formatted_address);
}
}
});
}
</script>
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Downloads