Once you start playing with the Google Maps API, making your own maps using various bits of JavaScript, you’ll eventually come under attack from single quotes.
Look at this code, for example, which is a mixture of Javascript and PHP:
var point = new GPoint(<? echo $longitude . "," . $latitude; ?>); var marker = createMarker(point, '<? echo $html; ?>'); map.addOverlay(marker);
The role of this snippet is to add a marker to the map at the given longitude and latitude, with the given HTML appearing when the marker is clicked.
So you stick this JavaScript inside a loop that grabs the appropriate values from a database, and sticks a bunch of markers on the map. Things go horribly wrong, however, when you try and create a marker for St. Dunstan’s Basilica, and you can’t figure out why. Here’s what’s happening:
var point = new GPoint(-63.12516,46.23367);
var marker = createMarker(point, 'St. Dunstan's Basilica');
map.addOverlay(marker);
I’ve highlighted the problematic area. And the problem is this: your browser’s JavaScript interpreter is getting confused by the single quote (aka “apostrophe”) in the string St. Dunstan’s Basilica — it thinks that single quote is the end of the string. And if you look in your Javascript console (Tools \| JavaScript Console in Firefox), you’ll see an error like:
Error: missing ) after argument list
How to solve this problem? Simply escape all of your single quotes in your HTML, using PHP, before you insert the HTML into the JavaScript. So:
var point = new GPoint(<? echo $longitude . "," . $latitude; ?>); var marker = createMarker(point, '<? echo str_replace("'","\\'",$html); ?>'); map.addOverlay(marker);
The change has the effect of converting all of the single quotes into escaped single quotes (\'
). Note that you use \\'
in your str_replace because the backslash is also an escape character in PHP, so you need to “escape your backslash” in PHP too.
The resulting JavaScript will now look like:
var point = new GPoint(-63.12516,46.23367); var marker = createMarker(point, 'St. Dunstan\'s Basilica'); map.addOverlay(marker);
And it will no longer cause problems.
Comments
Peter, you are a born teacher
Peter, you are a born teacher.
thanks a million! this makes
thanks a million! this makes perfect sense.. I was trying to do this.. but somehow forgot to escape the backslash in PHP as well.
I have a clients site on
I have a clients site on Google Maps that displays the single quote as ' - anyone know how to get rid of it? I have taken the quote off of the display over 6 weeks ago, and it still hasnt changed??
Thank you so much for this
Thank you so much for this tip. That crazy apostrophe was causing me tons of headaches and I knew that was the problem but just didn’t know how to get rid of it.
Thanks for the help!!
Thank you very much !!!!! :D
Thank you very much !!!!! :D
Add new comment