我是javascript的新手,对PHP知之甚少。我正试图从格式化为KML文件的谷歌地图路线中获取数据。现在,我正在使用jquery字符串将路线点的坐标保存到文本文件中。
文本文件如下所示:
[{"lat":51.101510000000005,"lng":4.948580000000001},{"lat":5.110208,"lnng":4.94763},}
我想做的是获得每个Lat和Lng的坐标,并将它们放在kml文件中。将它们放入文件中可能是我能够弄清楚的事情,但我似乎找不到如何提取每个Lat和Lng值。
如果我在JS中使用stringify将原始数组保存到文本文件,这是一种错误的方法,请随时提供更好的解决方案。
提前感谢
这是我现在的代码:
PHP
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = $_POST['RoutePath'];
fwrite($myfile, $txt);
fclose($myfile);
Javascript
directionsDisplay.setDirections(response);
console.log(response);
varRoutePath = response.routes[0].overview_path;
console.log(varRoutePath);
xml = JSON.stringify(varRoutePath);
console.log(xml);
function fuDownloadRoute() {
console.log("fuDownloadRoute");
console.log(xml);
$.post('Test.php', { RoutePath: xml },
function (data) {
$('#result').html(data);
});
}
您的坐标采用JavaScript对象表示法(JSON)格式。PHP有一个用于编码和解码JSON字符串的函数集。
在您的特定情况下,您可以使用json_decode()
,如下所示,首先将文本转换为数组,然后在每个坐标对上迭代:
$myjson = '[{"lat":51.101510000000005,"lng":4.948580000000001},{"lat":51.10208,"lng":4.94763},{"lat":51.102160000000005,"lng":4.94744},{"lat":51.102140000000006,"lng":4.944330000000001}]';
$coordinates = json_decode($myjson, true); // decode into associative array
foreach($coordinates as $pair) {
echo $pair['lat'] .','. $pair['lng'] . PHP_EOL;
}
输出:
51.10151,4.94858
51.10208,4.94763
51.10216,4.94744
51.10214,4.94433