来自一个 mysql 条目的多个坐标,用于折线谷歌地图


Multiple coordinates from one mysql entry to use in polylines google maps

嗨,我需要知道是否有办法分离我从 MySQL 数据库中检索到的坐标,以便在谷歌地图折线上使用 https://developers.google.com/maps/documentation/javascript/examples/polyline-simple它们目前存储的方式是这样的

(x, y)(x, y)(x, y)

由于坐标的数量每次都不同,因为它取决于用户记录坐标数据的时间。 但是我不知道如何分隔坐标以输入代码,如下所示:

var polyCoordinates = [
    new google.maps.LatLng(x, y),
    new google.maps.LatLng(x, y),
    new google.maps.LatLng(x, y)
  ];

我像这样检索数据

while ($row = mysql_fetch_array($query)) {
    echo "new google.maps.LatLng(" . $row['coordinate'] . "),";
}

是的,您需要做的是按某些字符拆分从数据库中获取的字符串。在PHP中,这个函数被称为爆炸。

因此,首先您需要从初始字符串中删除一些字符,以便在下一阶段更容易处理。我们要取出的是整行的开始(和结束(。这可以通过像这样的substr和strlen(返回长度(命令来完成

$coordinates = $row['coordinate'];
$coordinates = explode("(", $coordinates)[1];
$coordinates = substr($coordinates, 1, strlen($coordinates) - 2);
// $coordinates is now "x,y)(x,y)(x,y"

现在基于字符串"分解"它"(("只留下"x,y"对

$pieces = explode(")(", $coordinates);

之后$pieces是包含以下项(字符串(的数组

$pieces[0] is "x, y" // First pair
$pieces[1] is "x, y" // Second pair
$pieces[2] is "x, y" // Third pair

现在我们已经有了所有这些,我们可以遍历它们,将你的初始函数称为新的google.maps.LatLng(x,y(,就像这样

for ($i = 0; $i < strlen($pieces); ++$i) {
    // Here you could also use the $pieces[$i] straight away since it is now always pair like "x,y"
    $coords = explode(",", $pieces[$i]);
    $x = $coords[0];
    $y = $coords[1];
    echo("new google.maps.LatLng(" . $x . "," . $y . ")");
    if ($i + 1 < strlen($pieces)) {// If this isn't last row
        echo(",'n"); // Print comma
    }
}

如果我的答案有什么问题,请告诉我,多年没有写PHP:)