MVC动态谷歌地图标记

时间:2015-06-22 20:07:58

标签: javascript asp.net-mvc google-maps google-maps-api-3

我试图从我的MVC模型项目中绘制多个动态谷歌地图标记。我能够通过硬编码而不是动态编写。我错过了什么?

function codeAddress(index, value)
    {
        //var addressArray = ['Canada', 'India', 'America'];
        //$.each(addresses, function()
        //{
        //    var addresses = value.ASSET_NAME;
        //});
        @for (int i = 0; i < Model.Count(); i++)
        {
            var addressArray = Model[i].ASSET_NAME;
        }

        //var geocoder = new google.maps.Geocoder();

        for (var x = 0; x < addressArray.Count(); x++)
        {
            geocoder.geocode({ 'address': addressArray[x] }, function (results, status)
            {
                if (status == google.maps.GeocoderStatus.OK)
                {
                    var marker = new google.maps.Marker({
                        map: map,
                        position: results[0].geometry.location                    
                    });
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
        }
    }

1 个答案:

答案 0 :(得分:0)

由于范围,您的addressArray仅存在于for循环中。这就是当您尝试获取addressArray.Count();

时出现错误的原因

相反,首先像这样制作一个空数组:

var addressArray = [];

而不是覆盖addressArray,你应该push这样:

for (int i = 0; i < Model.Count(); i++)
    {
        addressArray.push(Model[i].ASSET_NAME);
    }

= - = - = - edit - = - = - =

我的不好,不知怎的,我认为这是纯粹的javascript。遗憾的是我不知道asp.net,但你应该使用asp.net构建一个javascript数组字符串,并将其分配给Javascript addressArray。 所以,我认为你可以尝试这样的事情:

@{
var addressArray = '[';
for (int i = 0; i < Model.Count(); i++)
    {
        if (i!=0){
             addressArray = addressArray + ',';
        };
        addressArray = addressArray + '"' + Model[i].ASSET_NAME+ '"' ;
    };
addressArray = addressArray + ']';
}

var addressArray = @addressArray;