我在javascript中有一个地图代码,它根据纬度和经度显示标记,我在脚本中有一个功能,通过该功能为地图提供纬度和经度。
function GetValues()
{
contentstring[0] = "Sector 40 Chandigarh, India";
regionlocation[0] = "30.739444,76.737981";
contentstring[1] = "sector 30 chandigarh, India";
regionlocation[1] = "30.716292,76.787029";
}
我想要做的是从数据库中获取值并在此函数中打印它,为此我得到了一个数组。这是在下面给出的。 来自以下代码
echo "<pre>";
print_r($rows);
echo "</pre>";
Array
(
[0] => Array
(
[id] => 25
[stop] => sec 40d Chandigarh
[latitude] => 30.7363831
[longitude] => 76.7309729
)
[1] => Array
(
[id] => 26
[stop] => sec 53 Chandigarh
[latitude] => 30.7163083
[longitude] => 76.7284448
)
[2] => Array
(
[id] => 27
[stop] => sec 60 Chandigarh
[latitude] => 30.7122544
[longitude] => 76.7206652
)
)
我试图循环这个数组并将值放在函数中但它没有用。任何人都可以告诉你该怎么做。
我试过的代码是
function GetValues() {
//contentstring[0] = "Sector 40 Chandigarh, India";
//regionlocation[0] = "30.739444,76.737981";
<?
for($i=0;$i<count($rows); $i++)
{?>
contentstring[<? echo $i; ?>]
<?}?>
=
<?foreach($rows as $row4)
{
contentstring[1] = '<? echo $row4['stop']; ?>';
regionlocation[1] = "<? echo $row4['latitude']; echo ","; echo $row4['longitude']; ?>";
<?}?>
}
答案 0 :(得分:1)
我建议您使用JSON - 从数据库中获取值,然后使用json_encode
创建要在javascript函数中使用的json对象。
/* echo the results as a javascript variable */
<script type='text/javascript'>
<?php
echo "var json=".json_encode( $rows ).";";
?>
</script>
/*
which would yield something like
*/
<script type='text/javascript'>
var json={
{"id":"25","stop":"sec 40d Chandigarh","latitude":"30.7363831","longitude":"76.7309729"},
{"id":"26","stop":"sec 53 Chandigarh","latitude":"30.7163083","longitude":"76.7284448"},
{"id":"27","stop":"sec 60 Chandigarh","latitude":"30.7122544","longitude":"76.7206652"}
};
function GetValues() {
if( typeof( json )!='undefined' && typeof( json )=='object' ){
for( var n in json ){
var record=json[ n ];
var contentstring=record['stop'];/* stop is a reserved word in javascript! */
var regionlocation={ lat:record.latitude, lng:record.longitude };
/* Add the marker to the map - pseudo code */
map.addMarker( contentstring, regionlocation );
}
}
}
</script>