2013-02-04 53 views
0

我目前使用Google Maps API v3創建了一個定位器。它搜索存儲在數據庫中的位置。使用Google Maps API v3按姓名搜索mySQL數據庫

這些位置有名稱。我想綁定一個搜索功能,通過名稱或位置搜索數據庫。我已經瀏覽了Google Places API,但我不確定應用這種文本搜索功能的位置。我還沒有看到一個很好的例子,如何做到這一點,甚至可能。

任何建議或意見或例子將不勝感激。

謝謝!

UPDATE:語言 - PHP

+0

用什麼語言? – gmaliar

+0

我目前已經設置使用php –

+0

查詢名稱的數據庫,併發送相應的座標到API – Randy

回答

0

你的引擎收錄使用過時的mysql_ extension。對於新代碼,您應該使用MySQLiPDO。以下代碼使用PDO

try { 
    //Connect to database 
    $dbh = new PDO("mysql:host=$host;dbname=$database", $username, $password); 
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    // Prepare statement 1 
    $searchStmt = $dbh->prepare("SELECT lat,lng FROM markers WHERE name LIKE ? "); 
    // Assign parameters 
    $searchStmt->bindParam(1,$name); 
    $searchStmt->setFetchMode(PDO::FETCH_ASSOC); 
    $searchStmt->execute(); 
    $row = $searchStmt->fetch(); 
    $center_lat = $row['lat']; 
    $center_lng = $row['lng']; 
    // Start XML file, create parent node 
    $dom = new DOMDocument("1.0"); 
    header("Content-type: text/xml"); 
    $node = $dom->createElement("markers"); 
    $parnode = $dom->appendChild($node); 
    // Prepare statement 2 
    $markerStmt = $dbh->prepare("SELECT name, lat, lng, (3959 * acos(cos(radians(?)) * cos(radians(lat)) * cos(radians(lng) - radians(?)) + sin(radians(?)) * sin(radians(lat)))) AS distance FROM markers HAVING distance < ? ORDER BY distance LIMIT 0 , 20"); 
    // Assign parameters 
    $markerStmt->bindParam(1,$center_lat); 
    $markerStmt->bindParam(2,$center_lng); 
    $markerStmt->bindParam(3,$center_lat); 
    $markerStmt->bindParam(4,$radius); 
    //Execute query 
    $markerStmt->setFetchMode(PDO::FETCH_ASSOC); 
    $markerStmt->execute(); 
    //Default for zero rows 
    if ($markerStmt->rowCount()==0) { 
     $node = $dom->createElement("marker"); 
     $newnode = $parnode->appendChild($node); 
     $newnode->setAttribute("name", "No Records Found"); 
     $newnode->setAttribute("lat", $center_lat); 
     $newnode->setAttribute("lng", $center_lng); 
     $newnode->setAttribute("distance", 0); 
       } 
    else { 
    // Iterate through the rows, adding XML nodes for each 
    while($row = $markerStmt->fetch()) { 
     $node = $dom->createElement("marker"); 
     $newnode = $parnode->appendChild($node); 
     $newnode->setAttribute("name", $row['name']); 
     $newnode->setAttribute("lat", $row['lat']); 
     $newnode->setAttribute("lng", $row['lng']); 
     $newnode->setAttribute("distance", $row['distance']); 
     } 
    } 
echo $dom->saveXML(); 

} 


catch(PDOException $e) { 
    echo "I'm sorry I'm afraid you can't do that.". $e->getMessage() ;// Remove or modify after testing 
    file_put_contents('PDOErrors.txt',date('[Y-m-d H:i:s]').", mapSelect.php, ". $e->getMessage()."\r\n", FILE_APPEND); 
} 
//Close the connection 
$dbh = null; 

$searchStmt在數據庫中搜索名稱。它使用找到的座標爲$markerStmt

if ($markerStmt->rowCount()==0) { 
... 
} 

用於在找不到記錄的情況下在搜索位置提供標記。