1

代码:

function setMaps() {
    var geocoder = new google.maps.Geocoder();
    var result = "";

    $('.map_canvas').each(function(){

        geocoder.geocode( {
            'address': $(this).attr('address'), 
            'region': 'de'
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                result += results[0].geometry.location.lng()+",";
                result += results[0].geometry.location.lat();
            } else {
                result = "Unable to find address: " + status;
            }
            $(this).gmap({ 'center': result });
        });
    });
}

此方法应在一页上显示多个地图。

HTML:

<div class="map_canvas" address="Berlin, Zoo">

</div>

问题是它$(this).gmap({ 'center': result });不起作用:

Uncaught TypeError: Cannot set property 'position' of undefined

知道如何将 map_canvas 对象传递给回调函数吗?

4

1 回答 1

2

试试这个:

function setMaps() {
    var geocoder = new google.maps.Geocoder();
    var result = "";

    $('.map_canvas').each(function(){
       var _this = $(this); // <------ here
        geocoder.geocode( {
            'address': $(this).attr('address'), 
            'region': 'de'
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                result += results[0].geometry.location.lng()+",";
                result += results[0].geometry.location.lat();
            } else {
                result = "Unable to find address: " + status;
            }
            _this.gmap({ 'center': result }); // <---- and here
        });
    });
}
于 2012-09-09T11:14:13.710 回答