-1

Hello I'm trying to create multiple markers on a leaflet map using a for loop in the scriptsection of a phtml page. I want to display this map on multiple pages however each page should show different markers. For this I pass a list of identifiers in the php section of the phtml file. Now I want to loop through this list and call another php array (all in the same file) with the for loop val.

e.g.

<?php
$buidling_code = $block->getData('building_code');
    $building_array = [];
    if (strpos($buidling_code, '|') !== false) {
            $building_array = explode("|",$building_code);  
    }else{
        array_push($building_array,$buidling_code);
    }
?>

so here we could have 5 building codes these codes would then need to be used in the following script part

<script>
for(i = 0; i<<?=count($building_array)?>;i++) 

var marker = L.marker([<?=$location_data[$building_array[$i]]['cordinates'][0]?>, <?=$location_data[$buidling_code]['cordinates'][1]?>]).addTo(mymap).bindPopup("<b><a href=<?=$location_data[$buidling_code]['popup']?>><?=$location_data[$buidling_code]['name']?></a></b>.");
}

But this fails is there a way to use the i value in the php part in the script section?

  • 1
    Does this answer your question? [can we use php variable in javascript and javascript variable in php code?](https://stackoverflow.com/questions/20613697/can-we-use-php-variable-in-javascript-and-javascript-variable-in-php-code) – Jared Smith Mar 26 '20 at 16:05

3 Answers3

0

You are mixing PHP and JavaScript. Try to decouple them in the for loop, since one is not aware of the other. Create variables that contain the converted php data into JSON.

<script>
var markers = <?php echo json_encode($location_data);?>;
var total = <?=count($building_array)?>;
for(var i = 0; i<total;i++) {
  var marker = L.marker([markers[i]['cordinates'][0], ...etc);
}
Ibu
  • 42,752
  • 13
  • 76
  • 103
0

one way you can do this is to create a hidden input. Then in JS assign the value of the hidden input to what you want to pass. On submit PHP will have access throught the $_POST variable. do you need an example?

DCR
  • 14,737
  • 12
  • 52
  • 115
0

export the php-array to java script:

var marker_array = [ <? echo join(",",$building_array ); ?> ];
draz
  • 793
  • 6
  • 10