Reputation: 17
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!
Upvotes: 0
Views: 145
Reputation: 24645
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) ?>;
Upvotes: 2
Reputation: 305
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?>
Upvotes: 0
Reputation: 1191
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.
Upvotes: 0