MySQL POINT字段的PHP数据类型

时间:2015-01-14 17:38:29

标签: php mysql geospatial spatial sqldatatypes

我创建了一个MySQL表,其中一个字段的类型为POINT,用于存储lat,lon坐标(例如:36.6294654 -93.1725982)。

我收到错误,提交表单,我认为这是由于数据类型不匹配造成的。

SQLSTATE[22003]: Numeric value out of range: 1416 Cannot get geometry object from data you send to the GEOMETRY field

我的理解是POINT应该有示例的格式(我也尝试过lat,lon)。我认为,问题是空间将变量转换为STRING

我错过了什么,这里?

这是我的PHP代码,用于连接数据库并插入记录。

// use google's geocoding service to transform an address into lat/lon coordinates (https://developers.google.com/maps/documentation/geocoding/)
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($street) . ',+' . urlencode($city) . ',+' . urlencode($state) . ',+' . urlencode($zip) . '&key=YOUR_API_KEY');
$json = json_decode($json, true);
$latlon = $json['results'][0]['geometry']['location']['lat'] . ' ' . $json['results'][0]['geometry']['location']['lng'];
try {
    $dbh = new PDO('mysql:host=someserver;port=someport;dbname=somedatabase', 'someusername', 'somepassword', array(PDO::ATTR_PERSISTENT => true));
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = 'INSERT INTO Venues (Name, Street, City, State, Zip, Country, TimeZone, LatLon, Phone, Email, Website, Host, Notes) VALUES (:name, :street, :city, :state, :zip, :country, :timezone, :latlon, :phone, :email, :website, :host, :notes)';
    $stmt = $dbh->prepare($sql);
    $stmt->execute(array(":name" => $name, ":street" => $street, ":city" => $city, ":state" => $state, ":zip" => $zip, ":country" => $country, ":timezone" => $timezone, ":latlon" => $latlon, ":phone" => $phone, ":email" => $email, ":website" => $website, ":host" => $host, ":notes" => $notes));
    if ($stmt->rowCount() == 1) {
        echo '<p>"' . $name . '" creation succeeded.</p>';
    } else {
        echo '<p>"' . $name . '" creation failed.</p>';
    }
    $stmt->setFetchMode(PDO::FETCH_ASSOC);
    $dbh = null;
}
catch(PDOException $e) {
    echo $e->getMessage();
}

或者,我可以只有单独的lat和lon字段,但我想练习msyql的内置几何功能。

编辑...

根据this answer的建议,我将$latlonPOINT()包围在一起。但是,它没有改变结果。

编辑2 ...

这是表结构,以防万一看起来不正确。

VenueKey    int(11)
Name        varchar(255)
Street      varchar(255)
City        varchar(255)
State       varchar(2)
Zip         varchar(10)
Country     varchar(2)
TimeZone    varchar(20)
LatLon      point
Phone       varchar(20)
Email       varchar(255)
Website     varchar(255)
Host        varchar(255)
Notes       text

1 个答案:

答案 0 :(得分:1)

这可以解决您的问题:

$latlng = 'POINT(' . $json['results'][0]['geometry']['location']['lat']. " " . $json['results'][0]['geometry']['location']['lng']. ')';

然后将:latlonPointFromText包裹在一起:

$sql = 'INSERT INTO Venues (Name, Street, City, State, Zip, Country, TimeZone, LatLon, Phone, Email, Website, Host, Notes) VALUES (:name, :street, :city, :state, :zip, :country, :timezone, PointFromText(:latlon), :phone, :email, :website, :host, :notes)';