MySQL data in javascript using PHP's foreach loop (Googlel Maps API) -
i'm trying use google maps v3 api create markers on google map. have coordinates of markers in mysql database, , in php array in .php file. how use foreach() loop (or suitable method) loop through elements in php array , create new google map marker each iteration of loop?
ps: php decent, not javscript knowledge. tutorial i'm following on creating markers @ http://www.svennerberg.com/2009/07/google-maps-api-3-markers/
code
i'm using codeigniter framework, controller+model file retrieved necessary data(name, lng, lat...) array $map. can loop array using usual method:
foreach($map $row) { $lng = $row[lng] // not necessary, show in array $lat = $row[lat] // how use loop create new marker code in javascript? }
the js code creating google map marker has created once per foreach loop iteration like:
var map = new google.maps.map(document.getelementbyid('map'), { zoom: 7, center: new google.maps.latlng($lng, $lat), // how pass php variables js code? maptypeid: google.maps.maptypeid.roadmap });
so question how pass php variables in php array create js code above, once per each foreach() loop iteration?
first of all, on right track, need understand separate concepts of server-side , client-side languages , how can interact. php doesn't "pass" variables javascript, generate whatever html document want.
that html document can contain javascript, execute page rendered browser. so, think of php making javascript code:
example of php outputting javascript code in html page:
<script type="text/javascript"> var testval = "<?php echo "hello, " . (5 + 3) . "!" ?>"; // "hello, 8! </script>
now, looked tutorial, , code in question not right code — instead code create map, , lat/long parameters in example center, not marker.
so, in php page, want following:
- somewhere, need create map:
var map = new google.maps.map...
(as shown in tutorial) - next,
$map
array array items containing'lng'
,'lat'
keys. (note: should wrap array key names quotes) - inside opened script tag use
<?php
create php code block, , createforeach
loop. each item, create javascript code needed create marker.
example of foreach loop:
<script type="text/javascript"> <?php foreach($map $row) { $lng = $row['lng']; $lat = $row['lat']; ?> // creating marker , positioning on map new google.maps.marker({ position: new google.maps.latlng(<?php echo $lat ?>, <?php echo $lng; ?>), map: map }); <?php } ?> </script>
Comments
Post a Comment