我试图在php中重现一些js代码。我不确定为什么我没有得到相同的结果。我认为js超越了一些变量(longitudeRange and latitudeRange
更精确),而php并没有。
php $range
与js range
的结果不同。
任何想法?
resp = encodeGeohash([34.2360444, -118.5284408]);
alert(resp);
function encodeGeohash (location) {
var g_BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz";
var precision = 10;
var latitudeRange = {
min: -90,
max: 90
};
var longitudeRange = {
min: -180,
max: 180
};
var hash = "";
var hashVal = 0;
var bits = 0;
var even = 1;
while (hash.length < precision) {
var val = even ? location[1] : location[0];
var range = even ? longitudeRange : latitudeRange;
var mid = (range.min + range.max) / 2;
if (val > mid) {
hashVal = (hashVal << 1) + 1;
range.min = mid;
} else {
hashVal = (hashVal << 1) + 0;
range.max = mid;
}
even = !even;
if (bits < 4) {
bits++;
} else {
bits = 0;
hash += g_BASE32[hashVal];
hashVal = 0;
}
}
return hash;
};
&#13;
php代码:
function geoHash($location)
{
$g_BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz";
$precision = 10;
$latitudeRange = ['min' => -90, 'max' => 90];
$longitudeRange = ['min' => -180, 'max' => 180];
$hash = "";
$hashVal = 0;
$bits = 0;
$even = 1;
while (strlen($hash) < $precision) {
$val = $even ? $location[1] : $location[0];
$range = $even ? $longitudeRange : $latitudeRange;
$mid = ($range['min'] + $range['max']) / 2;
var_dump($range);
if ($val > $mid) {
$hashVal = ($hashVal << 1) + 1;
$range['min'] = $mid;
} else {
$hashVal = ($hashVal << 1) + 0;
$range['max'] = $mid;
}
$even = !$even;
if ($bits < 4) {
$bits++;
} else {
$bits = 0;
$hash .= $g_BASE32[$hashVal];
$hashVal = 0;
}
}
var_dump($hash);
return $hash;
}
geoHash([34.2360444, -118.5284408]);
答案 0 :(得分:0)
分配时
var range = even ? longitudeRange : latitudeRange;
在javascript中,范围引用一个对象。所以,当你以后分配
range.min = mid;
它实际上更改了longitudeRange
或latitudeRange
引用的其中一个对象的属性
相反,你的PHP代码在那个地方使用了一个数组,它使用了写时复制,即当你分配$range['min'] = $mid;
时,它既不影响$latitudeRange
也不影响$longitudeRange
。
您可以使用对象
<?php
function geoHash($location)
{
$g_BASE32 = "0123456789bcdefghjkmnpqrstuvwxyz";
$precision = 10;
$latitudeRange = (object)['min' => -90, 'max' => 90];
$longitudeRange = (object)['min' => -180, 'max' => 180];
$hash = "";
$hashVal = 0;
$bits = 0;
$even = 1;
while (strlen($hash) < $precision) {
$val = $even ? $location[1] : $location[0];
$range = $even ? $longitudeRange : $latitudeRange;
$mid = ($range->min + $range->max) / 2;
if ($val > $mid) {
$hashVal = ($hashVal << 1) + 1;
$range->min = $mid;
} else {
$hashVal = ($hashVal << 1) + 0;
$range->max = $mid;
}
$even = !$even;
if ($bits < 4) {
$bits++;
} else {
$bits = 0;
$hash .= $g_BASE32[$hashVal];
$hashVal = 0;
}
}
return $hash;
}
var_dump(geoHash([34.2360444, -118.5284408]));