views:

204

answers:

4

Hello Dear StackOverflowers,

I am new to web programming and finding the server-client mixture confusing. I have written very simple code which accepts a PHP 2D array [index][keys] (from a query) to just draw markers on a Google map (JavaScript). It works. But it doesn't look right to me! Is this indeed the correct way to pass the values from my PHP array into the Javascript functions?

Thanks in advance Ari


Edit for clarity again, added 4 spaces, thanks for the advice!

<head>

<meta http-equiv="content-type" content="text/html; charset=utf-8">

<title><?php echo $title;?></title

<script src="http://maps.google.com/maps?file=api&amp;amp;v=2&amp;amp;sensor=false&amp;amp;key=GoogleMapsKey"
type="text/javascript">

</script>

<script type="text/javascript"  language="JavaScript">

var m_map;

//Add one marker. 
function addmarker(iLat, iLon)
{ 
 var point = new GLatLng(iLat, iLon);
 m_map.addOverlay(new GMarker(point)); 
}


function initialize() 

{

if (GBrowserIsCompatible()) 
{

    m_map = new GMap2(document.getElementById("map_canvas"));
    m_map.setCenter(new GLatLng(37.4419, -122.1419), 1);
    m_map.setUIToDefault();

    <?php foreach($query as $item):?>

    var oLat = '<?php  echo $item['lat'];?>';
    var oLon = '<?php  echo $item['lon'];?>';

    addmarker(oLat, oLon);  

    <?php endforeach;?>

}
}// End initialize() 

</script>
</head>

<body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 500px; height: 300px"   ></div>
+1  A: 

There doesn't appear to be anything inherently wrong with your code. Can you provide the output?

Darrell Brogdon
Hi, I am sorry, need to edit some of the code as most of it doesn't show. I am working on it, replacing < with '
BeMeCollective
+1  A: 

The browser doesn't care how the values, structures, even code gets there, as long as it's valid JavaScript.

Ignacio Vazquez-Abrams
+1  A: 

I'd write :

<?php foreach($query as $item):?>

addmarker('<?php echo $item['lat'];?>', '<?php echo $item['lon'];?>');  

<?php endforeach;?>

because it is more concise and it doesn't declare the two JS variables more than one time.

Fabien Ménager
+1  A: 
<?php 
foreach($query as $item):?>

    var oLat = '<?php  echo $item['lat'];?>';
    var oLon = '<?php  echo $item['lon'];?>';

    addmarker(oLat, oLon);  

    <?php endforeach;?>

The above code segment should provide following output if you have $query variable set as $query=array(array('lat'=>2,'lon'=>4),array('lat'=>5,'lon'=>6),array('lat'=>7,'lon'=>8),array('lat'=>9,'lon'=>1));


var oLat = '2'; var oLon = '4';

addmarker(oLat, oLon);

var oLat = '5'; var oLon = '6';

addmarker(oLat, oLon);

var oLat = '7'; var oLon = '8';

addmarker(oLat, oLon);

var oLat = '9'; var oLon = '1';

addmarker(oLat, oLon);

Check you page html source.

Acharya