0

This is what I am trying to accomplish (the accepted answer).

var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
];


The difference is the values are stored in an array. I tried this:

    <?foreach($nearest_hospitals as $item):?>
    var locations = [
          [<?$item->H_NAME;?>, <?$item->H_LAT;?>, <?$item->H_LONG;?>, <?$item->H_ID;?>],
    ];
    <?endforeach?>


With this, the map is not showing. Please help me. Thank you!

Community
  • 1
  • 1
Hugo Harun
  • 17
  • 2
  • 4

3 Answers3

2

To ensure proper encoding of the resulting javascript object I would suggest creating a php array of all of your elements then calling json_encode to produce the json.

<?php

   $locations = array();
   foreach($nearest_hospitals as $item){
        $locations[] = array($item->H_NAME,$item->H_LAT,$item->H_LONG,$item->H_ID);
   }
?>
var locations = <?= json_encode($locations) ?>;
Orangepill
  • 24,500
  • 3
  • 42
  • 63
0

In your case, use Array.push.

Sample code:

var locations = new Array;
<?foreach($nearest_hospitals as $item):?>
    locations.push(
          [<?$item->H_NAME;?>, <?$item->H_LAT;?>, <?$item->H_LONG;?>, <?$item->H_ID;?>]
    );
<?endforeach?>

Ps: I haven't tested this code yet.

long.luc
  • 1,191
  • 1
  • 10
  • 30
  • Don't expect sample code works without any adjustments. You need to read and understand the idea and code by yourself. – long.luc Sep 02 '13 at 04:57
0

Try to declare your locations variable outside the loop. Example:

var locations = {};
<?foreach($nearest_hospitals as $item):?>
    locations.push(
          [<?$item->H_NAME;?>, <?$item->H_LAT;?>, <?$item->H_LONG;?>, <?$item->H_ID;?>],
    );
<?endforeach?>
Raiiy
  • 320
  • 2
  • 12
  • `TypeError: Object # has no method 'push'` – Paul S. Sep 02 '13 at 03:38
  • Sorry, declare like var locations = Array(); And use {} in place of [] like: locations.push( {$item->H_NAME;?>, $item->H_LAT;?>, $item->H_LONG;?>, $item->H_ID;?>}, ); – Raiiy Sep 02 '13 at 03:41