PHP uses Geohash algorithm to find nearby shops

Source: Internet
Author: User
Tags cos sin

Geohash has the following features:

First, Geohash uses a string to represent the longitude and latitude two coordinates. With Geohash, you simply apply the index on one column.

Second, Geohash represents not a point, but a rectangular area. For example, the code WX4G0EC19, which represents a rectangular region. Users can publish address codes to show that they are located near Beihai Park without exposing their precise coordinates, which helps protect privacy.

Third, the prefix of the encoding can represent a larger area. For example, WX4G0EC1, whose prefix wx4g0e represents a larger range including encoded WX4G0EC1. This feature can be used to search nearby locations. You can query all nearby locations by first calculating geohash (for example, WX4G0EC1) based on the user's current coordinates and then querying by its prefix (SELECT * from places WHERE geohash like ' wx4g0e% ').

Geohash is much more efficient than using latitude and longitude directly.

Geohash base class:

<?php/** * Geohash generation class for PHP *//** * * Encode and decode geohashes * * Find neighbors * */class Geohash    {Private $BITSS = [16, 8, 4, 2, 1];    Private $neighbors = [];        Private $borders = [];    Private $coding = "0123456789bcdefghjkmnpqrstuvwxyz";        Private $CODINGMAP = [];        Public Function __construct () {$this->neighbors[' right '] [' even '] = ' bc01fg45238967deuvhjyznpkmstqrwx ';        $this->neighbors[' left ' [' even '] = ' 238967DEBC01FG45KMSTQRWXUVHJYZNP ';        $this->neighbors[' top ' [' even '] = ' p0r21436x8zb9dcf5h7kjnmqesgutwvy ';            $this->neighbors[' bottom ' [' even '] = ' 14365h7k9dcfesgujnmqp0r2twvyx8zb ';        $this->borders[' right ' [' even '] = ' bcfguvyz ';        $this->borders[' left ' [' even '] = ' 0145HJNP ';        $this->borders[' top ' [' even '] = ' prxz ';            $this->borders[' bottom ' [' even '] = ' 028b ';        $this->neighbors[' Bottom ' [' odd '] = $this->neighbors[' left ' [' even ']; $this->neighbors[' top ' [' odd '] = $this->neighbors[' right ' [' even '];        $this->neighbors[' left ' [' odd '] = $this->neighbors[' bottom '] [' even '];            $this->neighbors[' right ' [' odd '] = $this->neighbors[' top ' [' even '];        $this->borders[' Bottom ' [' odd '] = $this->borders[' left ' [' even '];        $this->borders[' top ' [' odd '] = $this->borders[' right ' [' even '];        $this->borders[' left ' [' odd '] = $this->borders[' bottom '] [' even '];            $this->borders[' right ' [' odd '] = $this->borders[' top ' [' even ']; Build map from encoding char to 0 padded bitfield for ($i =0; $i <32; $i + +) {$this->codingmap[subs        TR ($this->coding, $i, 1)] = Str_pad (Decbin ($i), 5, "0", str_pad_left); }}/** * Decode a Geohash and return an array with decimal lat,long in it */Public function Dec        Ode ($hash) {//decode hash into binary string $binary = "";        $HL = strlen ($hash); for ($i =0; $i < $HL;        $i + +) {$binary. = $this->codingmap[substr ($hash, $i, 1)];        }//split the binary into lat and log binary strings $BL = strlen ($binary);        $blat = "";        $blong = "";            for ($i =0; $i < $BL; $i + +) {if ($i%2) {$blat = $blat. substr ($binary, $i, 1);            } else {$blong = $blong. substr ($binary, $i, 1);        }}//now concert to decimal $lat = $this->bindecode ($blat,-90, 90);            $long = $this->bindecode ($blong,-180, 180); Figure out how precise the bit count makes this calculation $LATERR = $this->calcerror (strlen ($blat),-90, 90)        ;            $LONGERR = $this->calcerror (strlen ($blong),-180, 180); How many decimal places should we use? There ' s a little art to//this to ensure I get the same roundings as geohash.org $latPlaces = max (1,-round (        LOG10 ($LATERR)))-1; $longPlaces = Max (1,-round (log10 ($LONGERR)))-1;        Round it $lat = Round ($lat, $latPlaces);        $long = Round ($long, $longPlaces);    Return Array ($lat, $long);        } Private Function Calculateadjacent ($srcHash, $dir) {$srcHash = Strtolower ($srcHash);        $LASTCHR = $srcHash [Strlen ($srcHash)-1]; $type = (strlen ($srcHash)% 2)?        ' Odd ': ' Even ';            $base = substr ($srcHash, 0, strlen ($srcHash)-1); if (Strpos ($this->borders[$dir [$type], $LASTCHR)!== false) {$base = $this->calculateadjacent ($base, $d        IR); } return $base.    $this->coding[strpos ($this->neighbors[$dir] [$type], $lastChr)];            The Public Function Neighbors ($srcHash) {$geohashPrefix = substr ($srcHash, 0, strlen ($srcHash)-1);        $neighbors [' top '] = $this->calculateadjacent ($srcHash, ' top ');        $neighbors [' bottom '] = $this->calculateadjacent ($srcHash, ' bottom '); $neighbors [' right '] = $this->calculateadjacent ($srcHash, ' right ');                 $neighbors [' left '] = $this->calculateadjacent ($srcHash, ' left ');        $neighbors [' topleft '] = $this->calculateadjacent ($neighbors [' left '], ' top ');        $neighbors [' topright '] = $this->calculateadjacent ($neighbors [' Right '], ' top ');        $neighbors [' bottomright '] = $this->calculateadjacent ($neighbors [' Right '], ' bottom ');            $neighbors [' bottomleft '] = $this->calculateadjacent ($neighbors [' left '], ' bottom ');    return $neighbors; }/** * Encode a hash from given lat and long */Public function Encode ($lat, $long) {//how m        Any bits does latitude need?        $plat = $this->precision ($lat);        $latbits = 1;        $err = 45;            while ($err > $plat) {$latbits + +;        $err/= 2;        }//how Many bits does longitude need?        $plong = $this->precision ($long);        $longbits = 1;        $err = 90; while ($err > $pLong) {$longbits + +;        $err/= 2;                }//bit counts need to be equal $bits = Max ($latbits, $longbits); As the hash create bits in groups of 5, lets not//waste any bits-lets bulk it up to a multiple of 5//a        nd favour the longitude for any odd bits $longbits = $bits;        $latbits = $bits;        $addlong = 1;            while (($longbits + $latbits)% 5! = 0) {$longbits + = $addlong;            $latbits + =! $addlong;        $addlong =! $addlong;        }//encode each as binary string $blat = $this->binencode ($lat, -90, $latbits);            $blong = $this->binencode ($long, -180, (+), $longbits);        Merge lat and long together $binary = "";        $uselong = 1;                 while (strlen ($blat) + strlen ($blong)) {if ($uselong) {$binary = $binary. substr ($blong, 0, 1);            $blong = substr ($blong, 1); } else {$binary = $binary. substr ($blat, 0, 1);            $blat = substr ($blat, 1);        } $uselong =! $uselong;        }//convert binary string to hash $hash = "";            for ($i =0; $i <strlen ($binary), $i +=5) {$n = Bindec (substr ($binary, $i, 5));        $hash = $hash. $this->coding[$n];    } return $hash; }/** * What's the maximum error for $bits bits covering a range $min to $max */Private Function Calcer                Ror ($bits, $min, $max) {$err = ($max-$min)/2;        while ($bits-) {$err/= 2;    } return $err;  }/* * Returns precision of number * precision of are 0.5 * precision of 42.4 is 0.05 * precision        of 42.41 is 0.005 etc * */private Function precision ($number) {$precision = 0;        $pt = Strpos ($number, '. '); if ($pt!== false) {$precision =-(strlen ($numbER)-$pt-1);    } return Pow (ten, $precision)/2;  }/** * Create binary encoding of number as detailed in Http://en.wikipedia.org/wiki/Geohash#Example * removing The tail recursion is a exercise for the reader * Author:bruce Chen (Weibo: @ a developer) */Private FU        Nction Binencode ($number, $min, $max, $bitcount) {if ($bitcount = = 0) return "";                #echo "$bitcount: $min $max <br>"; This was our mid point-we would produce a bit to say//whether $number was above or below this mid point $         Mid = ($min + $max)/2;         if ($number > $mid) {return "1". $this->binencode ($number, $mid, $max, $bitcount-1);         } else {return ' 0 '. $this->binencode ($number, $min, $mid, $bitcount-1);     }}/** * Decodes binary encoding of number as detailed in Http://en.wikipedia.org/wiki/Geohash#Example * Removing the tail recursion is a Exercise for the reader * * */Private Function Bindecode ($binary, $min, $max) {$mid = ($min + $max)/2;    if (strlen ($binary) = = 0) return $mid;    $bit = substr ($binary, 0, 1); $binary = substr ($binary, 1);     if ($bit = = 1) {return $this->bindecode ($binary, $mid, $max);} else {return $this->bindecode ($binary, $min, $mid);} }}

Test instance:

$geohash = new Geohash (), $hash = $geohash->encode ($latitude, $longitude),//var_dump ($hash), exit;//determines the query scope, the greater the value, The smaller the range obtained//when the Geohash base32 encoding length is 8 o'clock, the accuracy is about 19 meters, and when the encoding length is 9 o'clock, the accuracy is about 2 meters, the encoding length needs to be selected according to the data condition. $pre _hash = substr ($hash, 0, 5);//Take out adjacent eight areas $neighbors = $geohash->neighbors ($pre _hash); Array_push ($neighbors, $pre _ $values = "; foreach ($neighbors as $key = = $val) {$values. = ' \ '. $val. ‘\‘‘ .‘,‘;} $values = substr ($values, 0,-1);//Var_dump ($values); $stores =\db::select ("select * from ' stores ' WHERE left (' Geohash ', 5 ) in ($values) "), foreach ($stores as $key = = $value) {$geohash _arr= $geohash->decode ($value->geohash); $stores [ $key]->latitude= $geohash _arr[0];//latitude $stores[$key]->longitude= $geohash _arr[1];//Longitude $distance= $this Getdistance ($request [' latitude '], $request [' longitude '], $value->latitude, $value->longitude); $stores [$key] ->distance= $distance; $sortdistance [$key] = $distance; }array_multisort ($sortdistance, SORT_ASC, $stores); Var_dump ($stores); return response ()->json ([' Status_code ' =>0, ' nearby_stores ' + $stores]);/** * @desc calculates distance according to latitude and longitude between two points * @param float $latitude Latitude Value * @ param float $longitude Longitude value */function Getdistance ($latitude 1, $longitude 1, $latitude 2, $longitude 2) {$earth _radius = 637 1000; Approximate radius of earth in meters $dLat = Deg2rad ($latitude 2-$latitude 1); $dLon = Deg2rad ($longitude 2-$longitude 1); /* Using the Haversine formula Http://en.wikipedia.org/wiki/Haversine_formula http://www.codecodex.com/wiki/ Calculate_distance_between_two_points_on_a_globe Verification: Baidu Map Http://developer.baidu.com/map/jsdemo.htm#a6_1 Calculate The distance * * $a = sin ($dLat/2) * sin ($dLat/2) + cos (Deg2rad ($latitude 1)) * cos (Deg2rad ($latitude 2)) * sin ($dLon/2) * si N ($dLon/2); $c = 2 * ASIN (SQRT ($a)); $d = $earth _radius * $c; Return round ($d); Rounded

  

PHP uses Geohash algorithm to find nearby shops

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.