- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathGeohash.cs
84 lines (77 loc) · 3.16 KB
/
Geohash.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Threading.Tasks;
namespaceAlgorithms.Other
{
publicstaticclassGeohash
{
privateconststringBase32Characters="0123456789bcdefghjkmnpqrstuvwxyz";// Convert latitude and longitude coordinates into a concise string
privateconstintGeohashLength=12;// ± 1.86 cm
/// <summary>
/// Encodes the provided latitude and longitude coordinates into a Geohash string.
/// Geohashing is a method to encode geographic coordinates (latitude, longitude).
/// into a short string of letters and digits. Each character in the resulting Geohash .
/// string adds more precision to the location. The longer the Geohash, the smaller the area.
/// </summary>
/// <param name="latitude">The latitude of the location to encode. It must be a value between -90 and 90.</param>
/// <param name="longitude">The longitude of the location to encode. It must be a value between -180 and 180.</param>
/// <returns>
/// A Geohash string of length 12 representing the location with high precision.
/// A longer Geohash provides higher precision in terms of geographic area.
/// and a 12-character Geohash can be accurate down to around 1.86 cm.
/// </returns>
publicstaticstringEncode(doublelatitude,doublelongitude)
{
double[]latitudeRange=new[]{-90.0,90.0};
double[]longitudeRange=new[]{-180.0,180.0};
boolisEncodingLongitude=true;
intcurrentBit=0;
intbase32Index=0;
StringBuildergeohashResult=newStringBuilder();
while(geohashResult.Length<GeohashLength)
{
doublemidpoint;
if(isEncodingLongitude)
{
midpoint=(longitudeRange[0]+longitudeRange[1])/2;
if(longitude>midpoint)
{
base32Index|=1<<(4-currentBit);
longitudeRange[0]=midpoint;
}
else
{
longitudeRange[1]=midpoint;
}
}
else
{
midpoint=(latitudeRange[0]+latitudeRange[1])/2;
if(latitude>midpoint)
{
base32Index|=1<<(4-currentBit);
latitudeRange[0]=midpoint;
}
else
{
latitudeRange[1]=midpoint;
}
}
isEncodingLongitude=!isEncodingLongitude;
if(currentBit<4)
{
currentBit++;
}
else
{
geohashResult.Append(Base32Characters[base32Index]);
currentBit=0;
base32Index=0;
}
}
returngeohashResult.ToString();
}
}
}