1

国名の抽出を追加して、このWebサイトからGoogleマップマーカーの例を拡張しようとしています。

Google マップは各住所の詳細を含む配列を返すため、配列を反復処理して、たとえば「国」のエントリを見つける必要があります。コードを再利用したいので、関数を作成します。

しかし、この関数を正しく呼び出す方法がわかりません (ここではfind(components, item) を呼び出します)。

find 関数から何も返されません。select 関数内から find 関数を正しく呼び出すにはどうすればよいですか? *空のリターンを取得する別の間違いがあるのでしょうか? *

あなたの考えや提案をありがとう!

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

1 に答える 1

0

find()関数は options オブジェクトで定義されますautocomplete

検索機能にアクセスしたい場合は、オートコンプリート オプションの外で定義するか、それへのポインターを取得する必要があります。

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

これは、jQuery がリスナーにアタッチされた要素を使用して関数のコンテキストを変更するためです。

于 2011-08-22T01:38:11.127 に答える