I am building a car share site and have a page for browsing existing journeys. At the top of the page is a search bar used to search for a location. I want to use Google Maps API to validate the place name and then send it to the controller with coordinates to then do a search within a radius.
For the life of me, no matter what combinations of code i use, i cannot seem to update the HiddenFor or search fields before the form is submitted to the controller. I know the code for validating places work as i use it on another page for creating journeys.
So the theory is the user enters a place name in the SearchString textbox, clicks the submit button, the jquery code then runs, validates the place, gets a correct location with geocoder, then updates the searchstring and coordinate hidden fields and finally posts to the controller.
Here is my current code:
@using (Html.BeginForm("BrowseJourney", "Journey", FormMethod.Post, new { id = "searchForm" }))
{ <div class="form-group" style="padding-bottom: 50px;">
<div class="col-md-2">
Find by location:
</div>
<div class="col-md-3">
@Html.TextBox("SearchString", null, new { @class = "form-control" , id = "SearchString"})
</div>
<div class="col-md-2">
Distance:
</div>
<div class="col-md-1">
@Html.DropDownList("Distance", null, new { @class = "form-control" })
</div>
@Html.HiddenFor(model => model.SearchLatitude, new { id = "SearchLatitude" })
@Html.HiddenFor(model => model.SearchLongitude, new { id = "SearchLongitude" })
<div class="col-md-2">
<input type="submit" value="Search" class="btn btn-default" id="submitButton" />
</div>
</div>
}
And the javascript:
<script src="https://maps.googleapis.com/maps/api/js?v=3&key=AIzaSyD4lap4yr45W9ztvRtfNw7JA-d03UVYtx0®ion=GB" type="text/javascript"></script>
<section class="scripts">
<script type="text/javascript">
$('#submitButton').click(function() {
var address = document.getElementById("SearchString").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address,
componentRestrictions: {
country: 'UK'
}
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
document.getElementById("SearchString").value = results[0].formatted_address;
document.getElementById("SearchLatitude").value = results[0].geometry.location.lat();
document.getElementById("SearchLongitude").value = results[0].geometry.location.lng();
} else {
alert("Unable to find location");
document.getElementById("SearchString").value = null;
}
});
});
</script>
</section>
And finally the controller:
public ActionResult BrowseJourney(string searchString, int distance, string searchLatitude, string searchLongitude)
{
}
Any help is greatly appreciated!