Jimmy
Jimmy

Reputation: 12487

Uncaught TypeError: Cannot call method 'val' of undefined

I'm having a hard time with this. This is the code im working with:

http://jsfiddle.net/arunpjohny/Jfdbz/

$(function () {
    var lastQuery  = null,
        lastResult = null, // new!
        autocomplete,
        processLocation = function (input, lat, long, callback) { // accept a callback argument
            var query = $.trim(input.val()),
                geocoder;

            // if query is empty or the same as last time...
            if (!query || query === lastQuery) {
                if (callback) {
                    callback(lastResult); // send the same result as before
                }
                return; // and stop here
            }

            lastQuery = query; // store for next time

            geocoder = new google.maps.Geocoder();
            geocoder.geocode({address: query}, function (results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                    lat.val(results[0].geometry.location.lat());
                    long.val(results[0].geometry.location.lng());
                    lastResult = true; // success!
                } else {
                    alert("Sorry - We couldn't find this location. Please try an alternative");
                    lastResult = false; // failure!
                }
                if (callback) {
                    callback(lastResult); // send the result back
                }
            });
        },
        ctryiso = $("#ctry").val(),
        options = {
            types: ["geocode"]
        };

    if (ctryiso !== '') {
        options.componentRestrictions= { 'country': ctryiso };        
    }
    autocomplete = new google.maps.places.Autocomplete($("#loc")[0], options);

    google.maps.event.addListener(autocomplete, 'place_changed', processLocation);

    $('#search').click(function (e) {
        var form = $(this).closest('form'),
            input = $("#loc"),
            lat = $("#lat"),
            lng = $("#lng");
        e.preventDefault(); // stop the submission

        processLocation(input, lat, lng, function (success) {
            if (success) { // if the geocoding succeeded, submit the form
                form.submit();
            }
        });
    });

    $('#geosearch').click(function (e) {
        var form = $(this).closest('form'),
            input = $("#geoloc"),
            lat = $("#geolat"),
            lng = $("#geolng");
        e.preventDefault(); // stop the submission

        processLocation(input, lat, lng);
    });
});

When the autosuggestion link is clicked it should geocode the result in the first and second example. However when I click on a autosuggest option from the dropdown I get the following error on line 39:

Uncaught TypeError: Cannot call method 'val' of undefined

Can anyone help pinpoint where I am going wrong here please?

EDIT: To replicate I do the following:

Apparently according to my editor line 39 says this:

if (ctryiso !== '') {

Upvotes: 0

Views: 2214

Answers (3)

Chamika Sandamal
Chamika Sandamal

Reputation: 24312

google.maps.event.addListener will not pass the parameters to the function you provided(processLocation) so you need to create new function for it.

process = function () {
    var input = $("#loc"),
        lat = $("#lat"),
        lng = $("#lng");
    processLocation(input, lat, lng, null);
}

and call it like,

google.maps.event.addListener(autocomplete, 'place_changed', process);

then it will works like this,

http://jsfiddle.net/Jfdbz/6/

UPDATE,


Here is a more cleaner way as you requested. http://jsfiddle.net/Jfdbz/9/

Change the processLocation like this,

processLocation = function (callback) { // accept a callback argument
            var input = $("#loc"),
                lat = $("#lat"),
                long = $("#lng");
            // rest of the cocde ***
}

Upvotes: 1

Axel Amthor
Axel Amthor

Reputation: 11096

as far as I can see, this

$('#search').click(function (e) {
    var form = $(this).closest('form'),
        input = $("#loc"),
        lat = $("#lat"),
        lng = $("#lng");
    e.preventDefault(); // stop the submission

    processLocation(input, lat, lng, function (success) {
        if (success) { // if the geocoding succeeded, submit the form
            form.submit();
        }
    });
});

defines the lat, lng etc variables with scope function, so you can not reference those in other functions like

 geocoder.geocode({address: query}, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                lat.val(results[0].geometry.location.lat());
                long.val(results[0].geometry.location.lng());

try to define them outside:

 var lastQuery  = null,
    lastResult = null, // new!
    autocomplete,
    lat = null,
    lng = null ...

and then use as this:

var form = $(this).closest('form'),
    input = $("#loc"); // !!
// no var here:
    lat = $("#lat");
    lng = $("#lng");

Upvotes: 0

Matt Harrison
Matt Harrison

Reputation: 13567

In this line:

google.maps.event.addListener(autocomplete, 'place_changed', processLocation);

That callback is being called with no arguments thus input is undefined and therefore you can't call val() on it in line 6.

Instead do this:

google.maps.event.addListener(autocomplete, 'place_changed',function(){
    processLocation(arguments); //With whatever arguments you need
});

Upvotes: 0

Related Questions