4,PHP.JAVA实现GEOHASH
2),测试下代码
<?php
require_once(‘geohash.class.php‘);
//######################辅助函数############################
// format var_dump 测试显示函数
function p($var, $echo=true,$label=null, $strict=true)
{
echo "<br>";
$label = ($label===null) ? ‘‘ : rtrim($label).‘ ‘;
if(!$strict) {
if (ini_get(‘html_errors‘)) {
$output = print_r($var, true);
$output = "<pre>".$label.htmlspecialchars($output,ENT_QUOTES)."</pre>";
} else
{
$output = $label . " : " . print_r($var, true);
}
}else {
ob_start();
var_dump($var);
$output = ob_get_clean();
if(!extension_loaded(‘xdebug‘)) {
$output = preg_replace("/\]\=\>\n(\s+)/m", "] => ", $output);
$output = ‘<pre>‘. $label. htmlspecialchars($output, ENT_QUOTES). ‘</pre>‘;
}
}
if ($echo) {
echo($output);
return null;
}else
return $output;
}
//######################数据库连接############################
//创建连接
function con() {
$dbh = new PDO(‘mysql:host=localhost;dbname=geohash‘, ‘root‘, ‘‘);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec(‘set names utf8‘);
return $dbh;
}
//条件查询
function select_query($sql,$values){
try{
$dbh=con();
/*查询*/
$stmt = $dbh->prepare($sql);
$stmt->execute($values);
$arr = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$arr[]=$row ;
};
return $arr;
// 现在运行完成,在此关闭连接
$dbh = null;
}catch(PDOException $e){
print"Error!:".$e->getMessage()."<br/>";
die();
}
}
//查询所有任务
function select_all(){
try{
$dbh=con();
/*查询*/
$stmt = $dbh->prepare(‘SELECT * FROM person‘);
$stmt->execute();
$arr = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$arr[]=$row ;
};
return $arr;
// 现在运行完成,在此关闭连接
$dbh = null;
}catch(PDOException $e){
print"Error!:".$e->getMessage()."<br/>";
die();
}
}
//所有插入操作
function insert($sql,$values){
try{
$dbh=con();
/*插入*/
$stmt = $dbh->prepare($sql);
$stmt->execute($values);
$lastid=$dbh->lastinsertid();
return $lastid;
// 现在运行完成,在此关闭连接
$dbh = null;
}catch(PDOException $e){
print"Error!:".$e->getMessage()."<br/>";
die();
}
}
//######################模拟地理位置插入数据############################
$geo=new Geohash;
$gps=array();
for($i=0;$i<=10;$i++){
$g=array((rand(1000000,1000010)/100000),(rand(2000000,2000000)/100000));
// $g=array(30.68635,103.9521);
$gps[]=$g;
}
$sql=‘insert into person(geohash,lat,lng) values(?,?,?)‘;
foreach ($gps as $k => $v) {
$encode=$geo->encode($v[0],$v[1]);
$decode=$geo->decode($encode);
$values=array($encode,$decode[0],$decode[1]);
// $values=array($encode,$v[0],$v[1]);
insert($sql,$values);
}
//######################查找相识的点############################
$sql=‘select geohash,lat,lng from person where geohash like "s3y0zn%" ‘;
$values=array();
$rs=select_query($sql,$values);
p($rs);
3),实际使用注意事项
实际使用的时候,应该查处类似一个九宫格的位置,然后比较九宫格里面与目标点的距离

如果只是查出一个矩形位置,很可能丢掉相邻矩形最近的位置;
参考http://blog.csdn.net/it_man/article/details/39640179
原文:http://my.oschina.net/acitiviti/blog/526537