谷歌地图API密钥失败使用PHP与MySQL

时间:2015-01-23 15:13:43

标签: php mysql google-maps

我使用以下代码对地址进行地理编码,但达到了他们的阈值。代码在此之外工作正常。我注册了云服务并启用了60天免费试用,以增加每日限额。我添加了一个KEY值,你可以在下面看到并加上& KEY ='。$ KEY在$ geocode变量的末尾发送KEY但是我仍然得到同样的错误,因为我没有得到geocode阈。

传递KEY值我做错了什么?

<?php
require("phpsqlajax_dbinfo.php");

define("KEY", "my-api-key");

// Opens a connection to a MySQL server
$connection = mysql_connect(localhost, $username, $password);
if (!$connection) {
  die("Not connected : " . mysql_error());
}

// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die("Can\'t use db : " . mysql_error());
}

// Select all the rows in the markers table
$query = "SELECT latitude,full_address,city,postal_code,matrix_unique_id FROM fort_property_res WHERE latitude IS NULL";
$result = mysql_query($query);
if (!$result) {
  die("Invalid query: " . mysql_error());
}

// Initialize delay in geocode speed
$delay = 0;
// Iterate through the rows, geocoding each address
while ($row = @mysql_fetch_assoc($result)) {
  $geocode_pending = true;

  while ($geocode_pending) {
    $adres=$row["full_address"].','.$row["city"].', FL '.$row["postal_code"];
    $address = urlencode($adres);
    $id = $row["matrix_unique_id"];
    $request_url = $base_url . "&address=" . urlencode($address);
     $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$address.'&sensor=false&key='.$KEY);
     $output= json_decode($geocode);
     $latitude = $output->results[0]->geometry->location->lat;
     $longitude = $output->results[0]->geometry->location->lng;
     if ($latitude) {
      // successful geocode
      $geocode_pending = false;
      $coordinates = $xml->Response->Placemark->Point->coordinates;
      $coordinatesSplit = split(",", $coordinates);
      $lat = $latitude;
      $lng = $longitude;
     //die();

      $query = sprintf("UPDATE fort_property_res " .
             " SET latitude = '%s', longitude = '%s' " .
             " WHERE matrix_unique_id = '%s' LIMIT 1;",
             mysql_real_escape_string($lat),
             mysql_real_escape_string($lng),
             mysql_real_escape_string($id));
      $update_result = mysql_query($query);

      if (!$update_result) {
        die("Invalid query: " . mysql_error());
      }
    } 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 个答案:

答案 0 :(得分:2)

如果您使用的是define,那么您不应该在变量上设置$,请尝试以下操作:

$geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$address.'&sensor=false&KEY='.KEY);

(请注意,$KEY现在是KEY在网址的末尾