Find the nearest distance Geohash algorithm (add peripheral neighbor number)

Source: Internet
Author: User
Tags rowcount

Next previous article: Find nearby Dot Geohash algorithm and implementation (Java version) http://blog.csdn.net/sunrise_2013/article/details/42024813

Reference Documentation:

Http://www.slideshare.net/sandeepbhaskar2/geohash Introduction to Geohash principles and examples

http://geohash.gofreerange.com/Demo Instance

http://geohash.gofreerange.com/around 8 lattice instances

Due to the loss of some of the dot, in order to solve the edge problem, you need to calculate the block around the eight lattice, supplementary code, to achieve the surrounding 8 encoding of the recent code.

Gets the code for the surrounding 8 Geohash values based on a Geohash value.

For example, in the lower left part of the grid 4 and the point of the lower right part of the large square 1 is close, but their geohash value must be quite far apart, because the first time the block is too large, many times we have a simple comparison of the value of Geohash, the results seem to be able to find similar points, And it seems to be arranged by distance, but in fact there are some points that are missing out.
Above this problem, you can search a lattice, around eight lattice data, the unified acquisition before filtering. This solves the problem at the coding level.


Main code:

<span Style= "Font-family:arial, Helvetica, Sans-serif;" >public Static string[] Getgeohashexpand (String geohash) {</span></span> 
 try {String Geohashtop = Calculateadjacent (Geohash, TOP); String Geohashbottom = calculateadjacent (Geohash, BOTTOM); String geohashright = calculateadjacent (Geohash, right);  String geohashleft = Calculateadjacent (Geohash, left); String geohashtopleft = calculateadjacent (Geohashleft, TOP); String geohashtopright = calculateadjacent (Geohashright, TOP); String geohashbottomright = calculateadjacent (Geohashright, BOTTOM);  String geohashbottomleft = calculateadjacent (Geohashleft, BOTTOM); string[] Expand = {Geohash, geohashtop, Geohashbottom, Geohashright, Geohashleft, Geohashtopleft, Geohashtopright, Geoha Shbottomright, geohashbottomleft}; return expand; } catch (Exception e) {//logger.error ("Geohash error", e); return null;}} 
</pre><pre code_snippet_id= "571887" snippet_file_name= "blog_20150105_5_8338259" name= "code" class= "Java" >
public static string Calculateadjacent (string srchash, int dir) {             Srchash = Srchash.tolowercase ();             Char LASTCHR = Srchash.charat (Srchash.length ()-1);             int type = (srchash.length ()% 2) = = 1? Odd:even;             String base = srchash.substring (0, Srchash.length ()-1);             if (Borders[dir][type].indexof (LASTCHR)! =-1) {                     base = Calculateadjacent (base, dir);             }             Return base + Base32.charat (Neighbors[dir][type].indexof (LASTCHR));     }



All code Examples:

Geohase.java

Package com. Disttest;//geohash.java//geohash Library for java//ported from David Troy's Geohash library for javascript//-Http://gith ub.com/davetroy/geohash-js/tree/master//(c) from David troy//(c) to Tom carden//distributed under the MIT     Licensepublic class Geohash {public static int bits[] = {16, 8, 4, 2, 1};     public static String BASE32 = "0123456789BCDEFGHJKMNPQRSTUVWXYZ";     public static int right = 0;     public static int left = 1;     public static int TOP = 2;     public static int BOTTOM = 3;     public static int even = 0;     public static int ODD = 1;     public static string[][] neighbors;     public static string[][] BORDERS;             static {neighbors = new string[4][2];             BORDERS = new String[4][2];             Neighbors[bottom][even] = "bc01fg45238967deuvhjyznpkmstqrwx";             Neighbors[top][even] = "238967DEBC01FG45KMSTQRWXUVHJYZNP";             Neighbors[left][even] = "P0r21436x8zb9dcf5h7kjnmqesgutwvy"; Neighbors[rigHt][even] = "14365H7K9DCFESGUJNMQP0R2TWVYX8ZB";             Borders[bottom][even] = "Bcfguvyz";             Borders[top][even] = "0145HJNP";             Borders[left][even] = "PRXZ";             Borders[right][even] = "028b";             Neighbors[bottom][odd] = Neighbors[left][even];             Neighbors[top][odd] = Neighbors[right][even];             Neighbors[left][odd] = Neighbors[bottom][even];             Neighbors[right][odd] = Neighbors[top][even];             Borders[bottom][odd] = Borders[left][even];             Borders[top][odd] = Borders[right][even];             Borders[left][odd] = Borders[bottom][even];     Borders[right][odd] = Borders[top][even];                      } private static void Refine_interval (double[] interval, int CD, int mask) {if (CD & mask) > 0) {             Interval[0] = (Interval[0] + interval[1])/2.0;             } else {interval[1] = (Interval[0] + interval[1])/2.0; }} public STatic string Calculateadjacent (string srchash, int dir) {Srchash = Srchash.tolowercase ();             Char LASTCHR = Srchash.charat (Srchash.length ()-1); int type = (srchash.length ()% 2) = = 1?             Odd:even;             String base = srchash.substring (0, Srchash.length ()-1);             if (Borders[dir][type].indexof (LASTCHR)! =-1) {base = Calculateadjacent (base, dir);     } return base + Base32.charat (Neighbors[dir][type].indexof (LASTCHR)); } public static string[] Getgeohashexpand (string geohash) {try {string geohashtop = Calculateadjacent (geo hash, TOP); String Geohashbottom = calculateadjacent (Geohash, BOTTOM); String geohashright = calculateadjacent (Geohash, right);  String geohashleft = Calculateadjacent (Geohash, left); String geohashtopleft = calculateadjacent (Geohashleft, TOP); String geohashtopright = calculateadjacent (Geohashright, TOP); String geohashbottomright = calculateadjacent (GeohaShright, BOTTOM);  String geohashbottomleft = calculateadjacent (Geohashleft, BOTTOM); string[] Expand = {Geohash, geohashtop, Geohashbottom, Geohashright, Geohashleft, Geohashtopleft, Geohashtopright, Geoha Shbottomright, geohashbottomleft}; return expand;          } catch (Exception e) {//logger.error ("Geohash error", e); return null;}}             public static double[][] Decode (String Geohash) {Boolean is_even = true;             double[] lat = new double[3];             double[] lon = new DOUBLE[3];             Lat[0] =-90.0;             LAT[1] = 90.0;             Lon[0] =-180.0;             LON[1] = 180.0;             Double lat_err = 90.0;             Double lon_err = 180.0;                     for (int i = 0; i < geohash.length (); i++) {char c = geohash.charat (i);                     int cd = Base32.indexof (c);                             for (int j = 0; J < Bits.length; J + +) {int mask = bits[j]; if (Is_evEN) {lon_err/= 2.0;                             Refine_interval (Lon, CD, Mask);                                     } else {Lat_err/= 2.0;                             Refine_interval (lat, CD, mask);                     } Is_even =!is_even;             }} Lat[2] = (Lat[0] + lat[1])/2.0;             LON[2] = (Lon[0] + lon[1])/2.0;     return new double[][] {lat, lon};             public static String encode (double latitude, double longitude) {Boolean is_even = true;             int i = 0;             Double lat[] = new DOUBLE[3];             Double lon[] = new DOUBLE[3];             int bit = 0;             int ch = 0;             int precision = 12;             String Geohash = "";             Lat[0] =-90.0;             LAT[1] = 90.0;             Lon[0] =-180.0;             LON[1] = 180.0; while (Geohash.length () < precision) {if (Is_even) {Double mid = (Lon[0] + L                             ON[1])/2.0;                                     if (Longitude > mid) {ch |= bits[bit];                             Lon[0] = mid;                             } else {lon[1] = mid;                             }} else {double mid = (Lat[0] + lat[1])/2.0;                                     if (Latitude > mid) {ch |= bits[bit];                             Lat[0] = mid;                             } else {lat[1] = mid;                     }} Is_even =!is_even;                     if (bit < 4) {bit++; } else {Geohash + = Base32.charat (CH);                            bit = 0;                     ch = 0;     }} return Geohash; }}

Test Example:

Package com.  Disttest; Import Java.sql.drivermanager;import java.sql.resultset;import java.sql.sqlexception;import java.sql.Connection;  Import java.sql.Statement;        public class Sqltest {public static void main (string[] args) throws Exception {Connection conn = null;        String SQL;        String SQL1;                String url = "Jdbc:mysql://132.97.194.62/test?"         + "User=root&password=sheng&useunicode=true&characterencoding=utf8";            try {class.forname ("com.mysql.jdbc.Driver");//dynamic load MySQL driver//System.out.println ("Load MySQL driver successfully");            A connection represents a database connection conn = drivermanager.getconnection (URL);                                     Statement contains many methods, such as executeupdate can be inserted, update and delete Statement stmt = Conn.createstatement ();        Double lon1=109.0145193757;      Double lat1=34.236080797698;       Generates GEOHASH encoding//Geohash GHash = new Geohash () according to geographic coordinates; String Gcode=geohash. Encode (LAT1, lon1). substring (0, 4);                    String gcode= "wqj6z";                  String[] Neargcode=geohash.getgeohashexpand (gcode);      for (int i=0;i<neargcode.length;i++) {System.out.println (neargcode[i]); sql = "SELECT * from retailersinfotable where geohash like" + "'" +neargcode[0]+ "% ' or '" +neargcod            e[1]+ "% ' or '" +neargcode[2]+ "% '" + "or" "+neargcode[3]+"% ' or ' "+neargcode[4]+"% ' or ' "+neargcode[5]+"% ' "            + "or" "+neargcode[6]+"% ' or ' "+neargcode[7]+"% ' or ' "+neargcode[8]+"% ' ";            SYSTEM.OUT.PRINTLN (SQL);            ResultSet rs = stmt.executequery (sql);//ExecuteQuery Returns a collection of results, otherwise returns a null value Rs.last (); int rowCount = Rs.getrow ();            Get the total number of ResultSet System.out.println (rowCount);                        Rs.beforefirst ();            System.out.println ("Current Position: Longitude" +lon1+ "Dimension:" +LAT1);    int i=0;            string[][] array = new STRING[ROWCOUNT][3]; while (Rs.next()) {//remove geographic coordinates from database double lon2=double.parsedouble (rs.getstring ("longitude"));                        Double lat2=double.parsedouble (rs.getstring ("Latitude"));            Generates GEOHASH encoding Geohash Geohash = new Geohash () according to geographic coordinates;                        String Geocode=geohash.encode (LAT2, Lon2). substring (0, 9);                     Calculates the distance between two points int dist= (int) test.getdistance (Lon1, LAT1, Lon2, LAT2);    Array[i][0]=string.valueof (i);    Array[i][1]=geocode;            Array[i][2]=integer.tostring (Dist);                    i++;                System.out.println (lon2+ "---" +lat2+ "---" +geocode+ "---" +dist); } array=sqltest.getorder (array);        Two-dimensional array sorting sqltest.showarray (array);            Print array} catch (SQLException e) {System.out.println ("MySQL operation Error");        E.printstacktrace ();        } finally {conn.close (); }/* * Two-dimensional array sorting, compare array[][2], returns a two-dimensional array * */public static string[][] GetOrder (string[][] array) {for (int j = 0; J < Array.Length; J + +) {for (int bb = 0; bb < array.length-1; bb++)  {string[] ss;int a1=integer.valueof (array[bb][2]);  Convert to type int a2=integer.valueof (array[bb+1][2]), if (A1&GT;A2) {ss = Array[bb];array[bb] = array[bb + 1];ARRAY[BB + 1] = SS;}}}    return array;  }/* Print array */public static void Showarray (string[][] array) {for (int. a=0;a<array.length;a++) {for (int      j=0;j<array[0].length;j++) System.out.print (array[a][j]+ "");      System.out.println ();    }}/* public static void Main (string[] args) {String aaa= "wxsfdf";    Geohash Geohash = new Geohash ();    string[] str = Geohash.getgeohashexpand (AAA);    for (int i=0;i<str.length;i++) {System.out.println (str[i]); }        }*/    }








Find the nearest distance Geohash algorithm (add peripheral neighbor number)

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.