tags:

views:

82

answers:

3

I'm using the following code to geocode a supplied address using the Google Maps API. The idea is to geocode the address and pass the lat/long in the form post so that my controller action can utilize it. Unfortunately, this doesn't seem to work as the lat/long aren't submitted with the rest of the form. What am I doing wrong?

$(document).ready(function() {
    $("#search_form").submit(function(event) {
        var address = $("#searchAddress").val();

        if (address != "") {
            var geocoder = new GClientGeocoder();

            geocoder.getLatLng(
                address,
                function(point) {
                    if (point) {
                        // Found address, populate hidden form fields
                        $("#searchLatitude").val(point.lat());
                        $("#searchLongitude").val(point.lng());  
                    }
                }
            );
        }
    });
});
+1  A: 

You are submitting the form and then setting the values. This does not work. You need to set the values and then submit the form.

Ólafur Waage
That's what I was afraid of. Is there a standard workaround to this?
Kevin Pang
There are some good suggestions in the other answers. You could look into them.
Ólafur Waage
A: 

jQuery form plug-in will make your life easier. There is a beforeSubmit event that you could use.

kgiannakakis
+2  A: 

geocoder.getLatLong() is asynchronous so your Submit is not waiting on your function(point) to be called.

Add a button (not a submit of course) and attach a click handler like so:

$("#buttonId").click(function() {

    var address = $("#searchAddress").val();

        if (address != "") {
            var geocoder = new GClientGeocoder();

            geocoder.getLatLng(
                address,
                function(point) {
                    if (point) {
                        // Found address, populate hidden form fields
                        $("#searchLatitude").val(point.lat());
                        $("#searchLongitude").val(point.lng());  

                        $("#search_form").submit();

                    }
                }
            );
        }

});
Chad Grant