Search code examples
google-mapsiframegoogle-maps-static-api

White space in URL when using AJAX with google static maps


I have a page that has an instance of Google statics maps embedded in an iFrame. When the page loads, the initial instance of this iFrame loads a set location. There is a list of addresses on the page that the user can click on and based on their choice, the iFrame with the embedded Google maps is reloaded through AJAX.

I am having some trouble with loading the new URL. Below is the PHP I am currently using

$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";

I get the address from my database and assign it to a variable. I then pass the variable into the static maps URL.

With the url defined, I call an iFrame

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

The iFrame does not load when I directly hit the php page or call the page through AJAX. When I inspect the page using Chrome or Firefox, I see the following source

<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>

If I take the src string from the above and load the link through the browser directly, the map loads.

Why is my iFrame not loading?

Update

New iFrame HTML after adding rawurlencode() to encode $address variable

<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>

Solution

  • You must encode the street_address, e.g. via rawurlencode()

    Spaces are not allowed in a URL(it works when you use the URL with spaces directly in a browser, because most browsers automatically encode the URLs)