Tags

, ,


I was working with google map api, I have task to make a infowindow for a marker. I faced some problem when I assigned multiple line code to a javascript variable. I tried to put a html code to a javascrpt variable which will use for info window.

I need to put block of html code (cakephp element) to a variable. if we do like the following

<script>
var infowindow = '<div class="map_info_content">
    <table cellpadding="3" cellspacing="3">
        <tr>
            <td colspan="2">
                <h1 class="map_title"><?=$map_title?></h1>
            </td>
        </tr>
        <tr>
            <td align="left" valign="top">
                <img src="<?=$imgurl?>" style="<?=$style_img?>" /> 
            </td>
            <td align="left" valign="top">
                <p>
                    <?=$msg?>
                </p>
            </td>
        </tr>
    </table>';
</script>

Its not not working, we need to put a slash / each end of line or need to write infowindow += “” for each line.
Now If we keep that html code to a cakephp element and just call the element and make it json_encode it work or keep this in to a php variable and make it json encode it working lets see

<?php
    $html = '<div class="map_info_content">
    <table cellpadding="3" cellspacing="3">
        <tr>
            <td colspan="2">
                <h1 class="map_title">Title</h1>
            </td>
        </tr>
        <tr>
            <td align="left" valign="top">
                <img src="info.jpg" style="" /> 
            </td>
            <td align="left" valign="top">
                <p>
                    HERE IS YOUR MSG
                </p>
            </td>
        </tr>
    </table>';
// Now make it json encode
$html = json_encode($html);
?>
// Now Assign it to a javascript variable
<script>
 var infowindow = <?=$html?> 
// OR if cakephp element
 var infowindow = <?=json_encode($this->element("infowindow"))?>

</script>

json_encode is very useful method to working like this.
🙂

Advertisement