我在我的一个 Laravel Seeder 中使用此代码,只要您给它位置区域和城镇,它就会在罗马尼亚获得一个随机街道名称,它通过获取该区域的纬度和经度然后随机添加 2 公里的半径来工作,之后,它向 google api 发出另一个请求,并从中提取随机街道名称。
我不知道这是否对您有帮助,调整此代码可以生成一个真实地址,前提是您提供第一个好位置来查看;
这是代码:
protected function getRandomStreetNameFromCity($judet, $city){
$kmRange = 2;
$initalLocation = [];
$randomLocation= [];
$randomKmval = mt_rand(1, $kmRange) / mt_getrandmax();
// Poor Man Lat and Lng
//Latitude: 1 deg = 110.574 km
//Longitude: 1 deg = 111.320*cos(latitude) km
$guzzelCl = new Client();
$guzelReq = $guzzelCl->request('GET', 'http://maps.googleapis.com/maps/api/geocode/json?address=Romania,'.$judet.','.$city.'&sensor=false', [
'verify' => false,
]);
if($guzelReq->getStatusCode() == 200){
$arrJson = json_decode($guzelReq->getBody(), true);
while (count($arrJson['results']) <= 0){
$judet= $this->getNewJudet();
$city = $this->getNewOras();
$guzelReq = $guzzelCl->request('GET', 'http://maps.googleapis.com/maps/api/geocode/json?address=Romania,'.$judet.','.$city.'&sensor=false', [
'verify' => false,
]);
$arrJson = json_decode($guzelReq->getBody(), true);
}
$initalLocation = $arrJson['results'][0]['geometry']['location'];
}
$plusMinus = $this->generateRandomString(1);
$randomExp = [ 1 => $tempLat = eval("return (1 / (110.574 ".$plusMinus." ".$randomKmval." )+ ".$initalLocation['lat']." );"),
2 => eval('return ('.$initalLocation['lng'].' '.$plusMinus.' 1/111.320*cos($tempLat));'),
];
$guzelReq = $guzzelCl->request('GET', 'http://maps.googleapis.com/maps/api/geocode/json?latlng='.$randomExp[1].','.$randomExp[2], [
'verify' => false,
]);
return explode(',', json_decode($guzelReq->getBody(), true)['results'][0]['formatted_address'])[0];
}
protected function getNewJudet(){
//This is a administrative type of location named 'judet' Romania is divided in a number bellow 50 of this
return array_rand($this->judetOras, 1);
}
protected function getNewOras(){
//This is a Town String
return $this->judetOras[$iterateJud = array_rand($this->judetOras, 1)][array_rand($this->judetOras[$iterateJud], 1)];
}
protected function generateRandomString($length = 10) {
$characters = '-+';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}