【发布时间】:2017-01-07 03:56:23
【问题描述】:
我想查看数据库中是否已经存在纬度和经度。我有一个网站,人们可以在其中输入他们的实际地址,并将其显示在地图上。我确实想防止物理地址被输入两次。我认为最好的方法是将地址的纬度和经度与数据库中存储的内容进行比较。
我正在使用 Google Map API 来查找用户输入的地址的纬度和经度。按照 Google 的建议,我将这些值存储(缓存)为 Float (10,6) 值。
当我尝试比较用户输入的地址值和我在数据库中存储的值时,我遇到的问题似乎是对浮点值进行四舍五入。
这是我用来比较这些值的代码:
$url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=".urlencode($address);
$lat_long = get_object_vars(json_decode(file_get_contents($url)));
// pick out what we need (lat,lng)
$lat = $lat_long['results'][0]->geometry->location->lat;
$lng = $lat_long['results'][0]->geometry->location->lng;
// Check to see if Property is already in database
$getlatlng = sprintf("SELECT * FROM `Property` WHERE CAST(lat AS DECIMAL(10,6)) = CAST(%s AS DECIMAL(10,6)) AND CAST(lng AS DECIMAL(10,6)) = CAST(%s AS DECIMAL(10,6))",
$PDO_DB->quote($lat),
$PDO_DB->quote($lng));
$resultlatlng = $PDO_DB->query($getlatlng);
$rowlatlng = $resultlatlng->fetch(PDO::FETCH_ASSOC);
一个例子是地址:601 N Lincoln Rd, Escanaba, MI 49829
数据库中存储的值是:
lat = 45.752487
lng = -87.082733
Google Map API 返回的值是:
lat = 45.7524878
lng = -87.0827338
我的猜测与返回的值有关,被四舍五入:
lat = 45.752488
lng = -87.082734
这导致我的数据库中的内容与 Google 返回的内容不相等。存储在数据库中的值存储在与上面相同的代码中,只是离开了将值插入数据库的部分。
【问题讨论】:
-
您只存储 6 位小数。
0827338是 7。Here, (M,D) means than values can be stored with up to M digits in total, of which D digits may be after the decimal point. For example, a column defined as FLOAT(7,4) will look like -999.9999 when displayed. MySQL performs rounding when storing values, so if you insert 999.00009 into a FLOAT(7,4) column, the approximate result is 999.0001.-dev.mysql.com/doc/refman/5.7/en/floating-point-types.html -
将存储在 MySQL 中的值字段更改为 FLOAT(11,7) 是否可以很好地解决此问题?
标签: php mysql google-maps google-maps-api-3 floating-point