简体   繁体   中英

Correct way of calling a javascript function

I am trying to extend the google maps marker example from the this website by adding the extraction of the country name.

Since google maps returns an array with details to each address, I need to iterate over the array to find the entry eg for "country". Since I would like to reuse the piece of code, I create a function.

But I am not sure how to call this function (here call find(components, item) ) correctly.

I do not get any return from the find function. How do I call the find function correctly from within the select function? * Could there be a different mistake why I get an empty return? *

Thank you for your thoughts and suggestions!

$(document).ready(function() { 

initialize();

$(function() {
    $("#address").autocomplete({
        //This bit uses the geocoder to fetch address values
        source: function(request, response) {
            geocoder.geocode( {'address': request.term }, function(results, status) {
                response($.map(results, function(item) {
                    return {
                        label:  item.formatted_address,
                    value: item.formatted_address,
                    components: item.address_components,
                    latitude: item.geometry.location.lat(),
                    longitude: item.geometry.location.lng()
                    }
                }));
            })
        },

        // address_component selection
        find: function(components, item) {
            for(var j=0;j < components.length; j++){
                for(var k=0; k < components[j].types.length; k++){
                    if(components[j].types[k] == "country"){
                        return components[j].long_name;
                    }
                }
            }
        },

    //This bit is executed upon selection of an address
    select: function(event, ui) {
        $("#latitude").val(ui.item.latitude);
        $("#longitude").val(ui.item.longitude);
        $("#country").val(this.find(ui.item.components, "country"));
        var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
        marker.setPosition(location);
        map.setCenter(location);
    }
    });
});

The find() function is defined in the autocomplete options object.

If you want to access your find function you'll have to define it outside the autocomplete options or to get a pointer to it :

var find = $(event.target).data("autocomplete").options.find;

This is because jQuery changes the context of functions with the element that is attached to the listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM