2013-05-26 58 views
0

請在下面的代碼中提供幫助。發生的事情是,當我點擊一個按鈕時,我得到了一個地方名稱的經緯度。但是,最近它不起作用。它打印出「地址x失敗到地理編碼。接收狀態」請注意,x是給定的地址,並且沒有給出狀態碼。使用v3進行Google地理編碼不會顯示錯誤

$id=$_REQUEST['id']; 
    define("MAPS_HOST", "maps.googleapis.com"); 
    define("KEY", "xxxxxxx"); 

    $query = "SELECT * FROM markers WHERE mid = $id LIMIT 1"; 
    $result = mysql_query($query); 
    if (!$result) { 
     die("Invalid query: " . mysql_error()); 
    } 

    // Initialize delay in geocode speed 
    $delay = 0; 
    $base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml?address="; 

    if($row = @mysql_fetch_assoc($result)){ 
    $geocode_pending = true; 
    $address = $row["address"]; 
    while ($geocode_pending) { 
    $request_url = $base_url . urlencode($address) . "&sensor=false&key=" . KEY; 
     $xml = simplexml_load_file($request_url) or die("url not loading"); 

     $status = $xml->Response->Status->code; 
     if (strcmp($status, "200") == 0) { 
      // Successful geocode 
      $geocode_pending = false; 
      $coordinates = $xml->Response->Placemark->Point->coordinates; 
      //$coordinatesSplit = split(",", $coordinates); 
      // Format: Longitude, Latitude, Altitude 
      //$lat = $coordinatesSplit[1]; 
      //$lng = $coordinatesSplit[0]; 
      list($lat,$lng) = explode(",",$coordinates); 
      $query = sprintf("UPDATE markers " . 
       " SET lat = '%s', lng = '%s' " . 
       " WHERE mid = '%s' LIMIT 1;", 
       mysql_real_escape_string($lng), 
       mysql_real_escape_string($lat), 
       mysql_real_escape_string($id)); 
      $update_result = mysql_query($query); 
      if (!$update_result) { 
      die("Invalid query: " . mysql_error()); 
      }else{ 
       echo "$lat;$lng"; 
      } 
     } else if (strcmp($status, "620") == 0) { 
      // sent geocodes too fast 
      $delay += 100000; 
     } else { 
      // failure to geocode 
      $geocode_pending = false; 
      echo "Address " . $address . " failed to geocode. "; 
      echo "Received status " . $status . " 
    \n"; 
     } 
     usleep($delay); 
    } 
    } 

回答

1

我不知道在哪個API你的代碼是基於,但目前API的響應不會與這些行工作:

$status = $xml->Response->Status->code; 
if (strcmp($status, "200") == 0) { 

沒有元素ResponseStatuscode,此外,響應不會包含數字狀態碼。

用這個代替:

$status = $xml->status; 
if (strcmp($status, "OK") == 0) { 

修復代碼的其餘部分,請看一看返回的XML的結構,也有沒有元素PlacemarkPointcoordinates

它應該是:

$lat = $xml->result->geometry->location->lat; 
$lng = $xml->result->geometry->location->lng; 
+0

非常感謝Dr.Molle。我刪除密鑰後,它就像一個魅力。 – user1149162

相關問題