2014-12-20 30 views
0

您好,我需要知道,如果有分離的方式座標,我已經從一個MySQL數據庫中檢索到的谷歌地圖折線使用https://developers.google.com/maps/documentation/javascript/examples/polyline-simple
他們當前存儲這樣多座標折線使用谷歌地圖

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

作爲座標數每次變化,因爲它取決於用戶如何長記錄的座標數據。但是我不知道如何separe座標在進入到這樣的代碼:

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'] . "),"; 
} 
+0

這樣你想要做的就是將字符串像_(2,30),(6,1),(8,7)_一樣分成x和y對,如x = 2和y = 30,然後調用_new google.maps .LatLng(2,30)_。那是對的嗎? –

+0

這正是我想要做的。可能嗎? –

回答

0

的數據是,你需要做的是分割字符串通過某些字符從數據庫中獲得。在PHP中,該函數被稱爲explode

所以首先你需要去掉初始字符串中的一些字符,以便在下一個階段更容易處理。我們想要拿出的是整排的開始(和結束)。這可以用substrstrlen(返回長度)來完成命令這樣

$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[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多年:)

+0

完全正是我所需要的。謝謝:) –

+2

請務必熟悉處理字符串的概念,而不是僅僅複製粘貼代碼。這將最終回報! :) –