1

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());  
                    }
                }
            );
        }
    });
});
0

3 Answers 3

3

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();

                    }
                }
            );
        }

});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

That's what I was afraid of. Is there a standard workaround to this?
There are some good suggestions in the other answers. You could look into them.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.