0

I have a form which converts an adress to geocode with the Google Map API using the onsubmit property. Since I know geocoding is asynchronous. Sometimes it works, and sometime it doesn't. Can anyone help me please? Thanks a lot!

jsp-file :

<body>
    <form name="addLocation" method="POST" action="addLocation.htm" commandName="location" onsubmit="changeAdress()">
        <table>
            <tr>
                <td>Name</td>
                <td><input type="text" name="name" value="${location.name}"/></td>
            </tr>
            <tr>
                <td>Adress</td>
                <td><input type="text" id="adress" name="adress"/></td>
            </tr>
            <tr>
                <td><input type="hidden" id="geolocation" name="geolocation"/></td>
            </tr>
        </table>
            <input type="hidden" name="id" value="${location.id}"/>
            <input type="submit" name="action" value="Save"/>
            <input type="submit" name="action" value="Cancel"/>
    </form>
</body> 

script :

    function changeAdress() {
        var adress = document.getElementById("adress").value; 
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({'address': adress}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var latitude = results[0].geometry.location.lat();
                var longitude = results[0].geometry.location.lng();
                document.addLocation.geolocation.value = latitude + " " + longitude;
                document.addLocation.submit();
            } else alert("geocode failed:" + status);
        });
        return false;
    }

You can allways try it yourself: http://jbossewss-leuvenspeaks.rhcloud.com/Test/newLocation.htm

JFluyt
  • 23
  • 3

1 Answers1

0

Remove the inline event handler, use a proper event handler, then prevent the form from submitting, and submit it programatically when the geocoder completes and the value is added to the form.

The return false in your code does not prevent the form from submitting btw.

document.getElementsByName('addLocation')[0].addEventListener('submit', function(e) {
    e.preventDefault();

    var self     = this;
    var adress   = document.getElementById("adress").value; 
    var geocoder = new google.maps.Geocoder();
    var geoloc   = document.getElementById("geolocation"); 

    geocoder.geocode({'address': adress}, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude  = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();

            geoloc.value = latitude + " " + longitude;
            self.submit();
        } else {
            alert("geocode failed:" + status);
        }
    }); 
});
adeneo
  • 312,895
  • 29
  • 395
  • 388