2013-05-22 29 views
0

我希望在Google地圖上隨機放置標記,以便隨時通過PHP隨機生成標記的經度和緯度,並通過AJAX加載標記。我遇到的問題不僅是座標小數點,還有一些是負數。例如,我需要的經度介於-2.07137437719725和-1.92779606909178之間,緯度介於50.71603387939352和50.793906977546456之間。我能找到的唯一隨機函數只能用於正整數,所以不可行。我曾嘗試將數字乘以十億以除去小數,然後稍後將產生的隨機數除以相同的數量返回到使用小數,但不幸的是,PHP無法處理如此大的數字。如何在PHP中獲得隨機十進制數(正數和負數)

我希望你能幫上忙。

感謝

保羅

+0

看到這個答案:http://stackoverflow.com/a/1504655/782609 – kamituel

+0

聽起來像是你想要做類似'地理guessing'東西的東西嗎? –

+0

Fred - Nope在地圖上只需要隨機標記。 – AdrenalineJunky

回答

0

你可以使用這樣的事情:

float Latitudes = (float)((rand(0, 180000000) - 90000000))/1000000); 
float Latitudes = (float)((rand(0, 360000000) - 180000000))/1000000); 

我個人認爲,精度可達0.001將是一件好事足夠的位置。如果你不相信我,請在谷歌地圖(-32.833,151.893)&(-32.832,151.895)上試試它,看看它們有多遠。

+0

rand()是廢話,用mt_rand()代替。 – GordonM

+0

@yiz謝謝,但這是相當低的水平或準確性,它不允許指定一個地圖範圍,這是我目前的項目重要,因爲地圖被分割成區域,所以它必須在區域之一 – AdrenalineJunky

+0

@GordonM謝謝但即使mt_rand也有問題,因爲它仍然只使用整數,所以沒有正數,負數或小數。 – AdrenalineJunky

1

這是我爲此做好的一個功能。它將一些小數點作爲參數,並使用偶數/奇數的隨機數檢查來使隨機化的陽性/陰性。

$latlon = randomLatLon(4); 
    print_r($latlon); 

    function randomLatLon($granularity) { 

      // $granularity = Number of decimal spaces. 
      $power = pow(10,$granularity); // Extended 10 to the power of $granularity. 

      // Generate the lat & lon (as absolutes) according to desired granularity. 
      $lat = rand(0,90 * $power)/$power; 
      $lon = rand(0,180 * $power)/$power; 

      // Check if a random number is even to randomly make the lat/lon negative. 
      if (rand(0,100) % 2 == 0) { 
        $lat = $lat * -1; 
      } 

      // Same for lon... 
      if (rand(0,100) % 2 == 0) { 
        $lon = $lon * -1; 
      } 

      return array(
        "lat" => $lat, 
        "lon" => $lon, 
      ); 


    } 
相關問題