You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SharePoint 2013中调用列表存储的API密钥加载Google Maps Web部件

解决方案:将SharePoint列表中的Google API密钥传递到前端iframe

看起来你已经搞定了从SharePoint列表获取API密钥的部分,只差把这个值传到前端iframe的src里了。这里给你两种简单可行的方法,顺便修正下代码里的小问题:

方法1:后台动态设置iframe的Src属性

这是最直接的方式,让后台C#代码直接控制iframe的地址:

步骤1:修改ascx中的iframe标签

给iframe加上runat="server",这样后台代码就能访问到这个控件:

<iframe id="mapa" runat="server" width="600" height="450" frameborder="0" style="border:0" allowfullscreen></iframe>

步骤2:修正后台代码并设置Src

首先,你的SPQuery里有个语法错误:FiledRef应该是FieldRef,属性写法也不对,我已经帮你修正了。然后在获取到apiKey后,直接拼接iframe的地址:

private void obtenerCamposGoogle()
{
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    {
        using (SPWeb web = site.OpenWeb())
        {
            SPList list = web.Lists["XXX"];
            if (list != null)
            {
                SPQuery query = new SPQuery();
                // 修正SPQuery的XML语法错误
                query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>google_apikey</Value></Eq></Where>";
                SPListItemCollection collitem = list.GetItems(query);
                foreach (SPListItem oListItem in collitem)
                {
                    apiKey = SPEncode.HtmlEncode(oListItem["Valor"].ToString());
                    // 动态设置iframe的Src属性
                    if (!string.IsNullOrEmpty(apiKey))
                    {
                        mapa.Src = $"https://www.google.com/maps/embed/v1/place?q=place_id:MYPLACE&key={apiKey}";
                    }
                }
            }
        }
    }
}

方法2:使用ASP.NET数据绑定

如果你更习惯前端绑定的方式,可以用这种方法:

步骤1:修改后台的apiKey访问权限

把静态的apiKey改成protected,让前端能访问到:

protected string apiKey; // 替换原来的public static string apiKey;

步骤2:在ascx里绑定Src属性

用<%# %>语法绑定后台的apiKey:

<iframe id="mapa" width="600" height="450" frameborder="0" style="border:0" 
        src='<%# $"https://www.google.com/maps/embed/v1/place?q=place_id:MYPLACE&key={apiKey}" %>' 
        allowfullscreen></iframe>

步骤3:触发数据绑定

在Page_Load里调用DataBind(),让绑定生效:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        obtenerCamposGoogle();
        this.DataBind(); // 触发数据绑定
    }
}

额外注意事项

  • 确保你的SharePoint列表"XXX"存在,且有标题为google_apikey的列表项,同时Valor字段有正确的API密钥值。
  • 检查你的Google API密钥是否启用了Maps Embed API,并且设置了正确的域名限制(允许你的SharePoint站点域名访问),否则地图可能加载失败。
  • 记得处理apiKey为空的情况,比如可以加个判断,如果为空就隐藏iframe或者显示提示信息。

内容的提问来源于stack exchange,提问作者Imrik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:19:31