Bitrix-D7 23.9
 
Загрузка...
Поиск...
Не найдено
geohash.php
1<?php
2namespace Bitrix\Main\Text;
3
4
6
7class GeoHash
8{
9 const MAX_LENGTH = 15;
10
11 protected static $latitudeInterval = array(-90.0, 90.0);
12 protected static $longitudeInterval = array(-180.0, 180.0);
13 protected static $bits = array(16, 8, 4, 2, 1);
14 protected static $base32Chars = array(
15 '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'b', 'c', 'd', 'e', 'f', 'g',
16 'h', 'j', 'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
17 );
18
19 public static function encode(array $coordinate, $length = self::MAX_LENGTH)
20 {
21 $latitudeInterval = static::$latitudeInterval;
22 $longitudeInterval = static::$longitudeInterval;
23
24 $isEven = true;
25 $bit = 0;
26 $charIndex = 0;
27
28 $geohash = '';
29
30 while(mb_strlen($geohash) < $length)
31 {
32 if($isEven)
33 {
34 $middle = ($longitudeInterval[0] + $longitudeInterval[1]) / 2;
35 if($coordinate[1] > $middle)
36 {
37 $charIndex |= static::$bits[$bit];
38 $longitudeInterval[0] = $middle;
39 }
40 else
41 {
42 $longitudeInterval[1] = $middle;
43 }
44 }
45 else
46 {
47 $middle = ($latitudeInterval[0] + $latitudeInterval[1]) / 2;
48 if($coordinate[0] > $middle)
49 {
50 $charIndex |= static::$bits[$bit];
51 $latitudeInterval[0] = $middle;
52 }
53 else
54 {
55 $latitudeInterval[1] = $middle;
56 }
57 }
58 if($bit < 4)
59 {
60 $bit++;
61 }
62 else
63 {
64 $geohash .= static::$base32Chars[$charIndex];
65 $bit = 0;
66 $charIndex = 0;
67 }
68 $isEven = $isEven ? false : true;
69 }
70
71 return $geohash;
72 }
73
74 public static function decode($geohash)
75 {
76 $base32DecodeMap = array_flip(static::$base32Chars);
77
78 $latitudeInterval = static::$latitudeInterval;
79 $longitudeInterval = static::$longitudeInterval;
80
81 $isEven = true;
82 $geohashLength = mb_strlen($geohash);
83 for($i = 0; $i < $geohashLength; $i++)
84 {
85 if(!isset($base32DecodeMap[$geohash[$i]]))
86 {
87 throw new SystemException('This geo hash is invalid.');
88 }
89 $currentChar = $base32DecodeMap[$geohash[$i]];
90 $bitsTotal = count(static::$bits);
91 for($j = 0; $j < $bitsTotal; $j++)
92 {
93 $mask = static::$bits[$j];
94 if($isEven)
95 {
96 if(($currentChar & $mask) !== 0)
97 {
99 }
100 else
101 {
103 }
104 }
105 else
106 {
107 if(($currentChar & $mask) !== 0)
108 {
110 }
111 else
112 {
114 }
115 }
116 $isEven = $isEven ? false : true;
117 }
118 }
119
120 return array(
123 );
124 }
125}
static decode($geohash)
Definition geohash.php:74
static encode(array $coordinate, $length=self::MAX_LENGTH)
Definition geohash.php:19