谷歌地图商店定位器修改硬编码初始化为动态

时间:2012-05-18 13:55:41

标签: javascript google-maps-api-3 this typeerror

我正在尝试修改此示例 http://storelocator.googlecode.com/git/examples/panel.html

javascript代码在这里: https://gist.github.com/2725336

我遇到困难的方面正在改变这一点:

MedicareDataSource.prototype.FEATURES_ = new storeLocator.FeatureSet(
  new storeLocator.Feature('Wheelchair-YES', 'Wheelchair access'),
  new storeLocator.Feature('Audio-YES', 'Audio')
);

从函数创建FeatureSet,例如我有这个解析JSON对象的函数

WPmmDataSource.prototype.setFeatures_ = function(json) {
    var features = [];

    // convert features JSON to js object
    var rows = jQuery.parseJSON(json);

    // iterate through features collection
    jQuery.each(rows, function(i, row){

    var feature = new storeLocator.Feature(row.slug + '-YES', row.name)

    features.push(feature);
    });

    return  new storeLocator.FeatureSet(features);
    };

然后将第一个代码段更改为

WPmmDataSource.prototype.FEATURES_ = this.setFeatures_(wpmm_features);

返回错误:

Uncaught TypeError: Object [object Window] has no method 'setFeatures_'

1 个答案:

答案 0 :(得分:1)

我认为您只需对WPmmDataSource.prototypesetFeatures_方法进行一些更改:

WPmmDataSource.prototype = {
    FEATURES_ : null,        
    setFeatures_ : function( json ) {
        //Set up an empty FEATURES_ FeatureSet
        this.FEATURES_ = new storeLocator.FeatureSet();
        //avoid the use of "this" within the jQuery loop by creating a local var
        var featureSet = this.FEATURES_;
        // convert features JSON to js object
        var rows = jQuery.parseJSON( json );
        // iterate through features collection
        jQuery.each( rows, function( i, row ) {
            featureSet.add(
                new storeLocator.Feature( row.slug + '-YES', row.name ) );
        });
    }
}

有了这个,你不必通过从setFeatures_返回一个值来完成作业;它可以直接访问FEATURES_成员。这一行:

WPmmDataSource.prototype.FEATURES_ = this.setFeatures_(wpmm_features);

不再需要。这也意味着稍后,当您创建了WPmmDataSource的实例时,您的代码可以像这样工作:

var wpmd = new WPmmDataSource( /* whatever options, etc. you want */ );
wpmd.setFeatures_( json );
// Thereafter, wpmd will have its FEATURES_ set

我不确定你想要达到的目标,但我相信这会让你超越当前失速的障碍。我希望这能让你前进 -