I want a user to be able to get the closest user. So, I have to get the user's longitude and latitude from the browser and send it to the OnPost action method below. Each time the user visits the website, the position is updated. NOTE: The point class which takes the coordinates in the controller, is from the NetTopologySuite library used for modelling and manipulating 2-dimensional linear geometry
[HttpPost]
public async Task<IActionResult> Profile(ProfileViewModel profileModel, double latitude, double longitude)
{
var user = await _userManager.GetUserAsync(User);
if (ModelState.IsValid)
{
if (user.DOB != profileModel.DOB) user.DOB = profileModel.DOB;
user.Location = new Point(latitude, longitude) { SRID = 4326 };
}
}
Here in the view, I am trying to set the coordinates to the asp-routes defined in the form from the script so I can use it in the controller, but the latitude and longitude are not being sent to the action method above. I am new to jQuery
<form asp-controller="Account" asp-action="Profile" method="post" asp-route-latitude="" asp-route-longitude="">
<label asp-for="DOB"></label>
<input asp-for="DOB" class="form-control" />
</form>
<script type="text/javascript">
var x = document.getElementById("Location");
window.onload = function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
console.log("Geolocation not supported by browser.");
}
}
function showPosition(position) {
$("form").attr("asp-route-latitude", position.coords.latitude);
$("form").attr("asp-route-longitude", position.coords.longitude);
}
</script>
PS - Even if I fix this problem, I am not sure if this is the best way to achieve the goal where a consumer requests for a vendor and one of the closest ones is sent to him just like Uber. Suggestions on how best to achieve this would be much appreciated.
You need to make an ajax call to controller/action method to sent the data
<script type="text/javascript">
var x = document.getElementById("Location");
window.onload = function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
else {
console.log("Geolocation not supported by browser.");
}
}
function showPosition(position) {
$("form").attr("asp-route-latitude", position.coords.latitude);
$("form").attr("asp-route-longitude", position.coords.longitude);
$.ajax({
url : '[controller_name]/Profile?latitude='+position.coords.latitude+'&longitude='+position.coords.longitude,
type : 'POST',
data : {
'profileModel' : {}
},
dataType:'json',
success : function(data) {
console.log(data);
},
error : function(request,error){
console.log(error);
}
});
}
</script>