【问题标题】:White space in URL when using AJAX with google static maps将 AJAX 与谷歌静态地图一起使用时 URL 中的空白
【发布时间】:2013-04-13 18:45:28
【问题描述】:

我有一个页面,其中有一个嵌入在 iFrame 中的 Google 静态地图实例。当页面加载时,这个 iFrame 的初始实例会加载一个设置的位置。页面上有一个地址列表,用户可以点击并根据他们的选择,通过 AJAX 重新加载嵌入了 Google 地图的 iFrame。

我在加载新 URL 时遇到了一些问题。下面是我目前正在使用的 PHP

$database->mysqlquery("SELECT street_address
                       FROM favorites
                       WHERE id = $row_id");

while($row = mysql_fetch_array($database->results)){
    $address = $row[street_address];
}

$url = "http://maps.googleapis.com/maps/api/staticmap?center=$address&zoom
=18&size=640x640&sensor=false";

我从我的数据库中获取地址并将其分配给一个变量。然后我将变量传递给静态地图 URL。

定义了 url,我调用了 iFrame

<iframe width = "425" height = "315" frameborder = "0" scrolling = "no" 
marginheight = "0" marginwidth = "0" src= "<?php echo $url; ?>" id = "iframe"></iframe>

直接点击php页面或通过AJAX调用页面时iFrame不加载。当我使用 Chrome 或 Firefox 检查页面时,我看到以下来源

<iframe width="425" height="315" frameborder="0" scrolling="no" 
marginheight="0" `marginwidth="0" 
src="http://maps.googleapis.com/maps/api/staticmap?center=116 Ponce De Leon Ave 
NE, Atlanta, GA&amp;zoom=18&amp;size=640x640&amp;sensor=false" id="iframe"></iframe>

如果我从上面获取 src 字符串并直接通过浏览器加载链接,地图就会加载。

为什么我的 iFrame 没有加载?

更新

添加 rawurlencode() 以编码 $address 变量后的新 iFrame HTML

<iframe width="425" height="315" frameborder="0" scrolling="no" marginheight="0" 
marginwidth="0" 
src="http://maps.googleapis.com/maps/api/staticmap? 
center=116%20Ponce%20De%20Leon%20Ave%20NE%2C%20Atlanta%2C%20GA&amp;
zoom=18&amp;size=640x640&amp;sensor=false" id="iframe"></iframe>

【问题讨论】:

    标签: google-maps iframe google-static-maps


    【解决方案1】:

    您必须对 street_address 进行编码,例如通过rawurlencode()

    URL 中不允许使用空格(当您直接在浏览器中使用带有空格的 URL 时,它会起作用,因为大多数浏览器会自动对 URL 进行编码)

    【讨论】:

    • 我添加了 rawurlencode() 函数来编码 $address 变量。我仍然无法加载地图。 src 现在有格式化的空格,但地图仍然不显示。如果我复制新 src 中的链接并使用浏览器访问它,地图会显示
    • 1st: URL 中仍有空格和换行符。 那么: 返回的文件是图像,而不是 HTML 文档!服务器发送一个x-frame-options-header,它设置为same-origin,因此你不能将它用作iframe-src。使用&lt;img/&gt; 而不是&lt;iframe/&gt;
    • Awww,你确实是对的。它需要包含在 img 而不是 iframe 中。添加了上面的换行符,以便我可以更好地显示代码
    • 有一个问题,我在页面上加载的默认地图(不是通过 AJAX)使用 iFrame 来显示地图。为什么我需要在 AJAX 加载页面上使用“img src”,而不是在默认页面上?
    • 我不确定您在其他页面上加载了什么,但您在此处加载的是图像,当您想使用 iframe 时,您需要使用另一个 URL,例如由maps.google.com 上的嵌入代码提供
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 2015-05-15
    • 1970-01-01
    • 2017-01-12
    • 2017-04-26
    • 1970-01-01
    相关资源
    最近更新 更多