MapJob.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. namespace addons\RfDevTool\common\queues;
  3. use Yii;
  4. use yii\base\BaseObject;
  5. use linslin\yii2\curl\Curl;
  6. use Overtrue\Pinyin\Pinyin;
  7. use common\helpers\StringHelper;
  8. use common\models\common\Provinces;
  9. /**
  10. * Class MapJob
  11. *
  12. *
  13. * $all = Provinces::find()
  14. * ->select(['id', 'title'])
  15. * ->asArray()
  16. * ->all();
  17. *
  18. * foreach ($all as $item) {
  19. * $messageId = Yii::$app->queue->push(new \common\queues\MapJob([
  20. * 'id' => $item['id'],
  21. * 'address' => $item['title'],
  22. * ]));
  23. * }
  24. *
  25. * @package common\queues
  26. * @author jianyan74 <751393839@qq.com>
  27. */
  28. class MapJob extends BaseObject implements \yii\queue\JobInterface
  29. {
  30. /**
  31. * @var int
  32. */
  33. public $id;
  34. /**
  35. * 地址
  36. *
  37. * @var string
  38. */
  39. public $address;
  40. /**
  41. * @var string
  42. */
  43. public $type = 'baidu';
  44. /**
  45. * @param \yii\queue\Queue $queue
  46. * @return mixed|void
  47. */
  48. public function execute($queue)
  49. {
  50. $type = $this->type;
  51. $model = Provinces::findOne($this->id);
  52. if (($result = $this->$type()) !== false) {
  53. list($lng, $lat) = $result;
  54. if ($model) {
  55. $model->lng = (string) $lng;
  56. $model->lat = (string) $lat;
  57. }
  58. }
  59. if ($model) {
  60. $model->pinyin = $this->pinyin($model->title);
  61. $model->save();
  62. }
  63. }
  64. /**
  65. * @param $title
  66. * @return string
  67. */
  68. public function pinyin($title)
  69. {
  70. // 首先字母转大写拼音
  71. if (($chinese = StringHelper::strToChineseCharacters($title)) && !empty($chinese[0])) {
  72. $title_initial = mb_substr($chinese[0][0], 0, 1, 'utf-8');
  73. return ucwords((new Pinyin())->abbr($title_initial));
  74. }
  75. return '';
  76. }
  77. /**
  78. * @throws \Exception
  79. */
  80. public function baidu()
  81. {
  82. $curl = new Curl();
  83. $data = $curl->setGetParams([
  84. 'address' => $this->address,
  85. 'output' => 'json',
  86. 'ak' => Yii::$app->services->config->backendConfig('map_baidu_ak'),
  87. ])->get("http://api.map.baidu.com/geocoder/v2/", false);
  88. if (isset($data['status']) && $data['status'] == 0) {
  89. return [
  90. $data['result']['location']['lng'],
  91. $data['result']['location']['lat']
  92. ];
  93. }
  94. return false;
  95. }
  96. }
粤ICP备19079148号