This is what I was trying to do: The user enters an address, which is autocompleted by Google. Then when they press the submit button, an alert box pops up, telling them whether the address entered is within 5 miles of (42.352487, -71.079290). Then a confirm box pops up asking if they would like to proceed to the next page.
Nothing happens when I click the submit button. codeAddress() is never triggered. How can I get the button to work?
Also, I would appreciate any tips or glaringly obvious errors that you notice. I'm still new to Javascript.
Here is my search box and submit button:
<input id="searchTextField" type="text" size="60"><button id="search" type="button" onClick="codeAddress();">Submit</button>
And the Javascript:
<script type="text/javascript">
//GOOGLE AUTOCOMPLETE
function initialize() {
var input = document.getElementById('searchTextField');
var options = {componentRestrictions: {country: 'us'}};
new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
function getDistance( latA, longA, latB, longB ) //haversine formula to get the radius of the points
{
var a = Math.sin((latA - latB).toRad()/ 2) * Math.sin((latA - latB).toRad() / 2) +
Math.cos(latB.toRad()) * Math.cos(latB.toRad()) *
Math.sin((longA - longB).toRad() / 2) * Math.sin((longA - longB).toRad() / 2);
var d = 3963.1676 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); // 3963.1676 is the radius of the earth in miles
return d;
}
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("searchTextField").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
var distance = getDistance( 42.352487, -71.079290, latitude, longitude );
if( distance < 5 ){ //if the address entered is within 5 miles of (42.352487, -71.079290)
alert( "You're in luck! We can deliver to your address.");
var next_page = confirm("Proceed?");
if(next_page == true)
{
window.location="food.php";
}
} else {
alert( "Sorry, we cannot deliver to the address you have entered.");
window.location = "homepage.php";
}
}
});
</script>