0

请帮助下面的代码。发生的情况是,当我单击一个按钮时,我得到了一个地方名称的纬度和经度。但是,最近,它不起作用。它打印“地址 x 无法进行地理编码。收到状态”请注意,x 是给定的地址,没有给出状态代码。

    $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);
     }
    }
4

1 回答 1

1

我不确定您的代码基于哪个 API,但当前 API 的响应不适用于这些行:

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

没有元素ResponseStatus或者code,此外,响应将不包含数字状态代码。

改用这个:

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

要修复其余代码,请查看返回的 XML 的结构,也没有元素Placemark和.Pointcoordinates

它应该是:

$lat = $xml->result->geometry->location->lat;
$lng = $xml->result->geometry->location->lng;
于 2013-05-26T22:04:30.067 回答