Skip to content

Instantly share code, notes, and snippets.

@kopiro
Last active August 29, 2015 13:57
Show Gist options
  • Save kopiro/9828696 to your computer and use it in GitHub Desktop.
Save kopiro/9828696 to your computer and use it in GitHub Desktop.
Localize models in Laravel with an Artisan Command
<?php
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class Localize extends Command {
protected $name = 'localize';
protected $description = 'Set the coordinates';
public function __construct()
{
parent::__construct();
}
public function fire()
{
function gps($address) {
$url = "https://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=%s";
$res = file_get_contents(sprintf($url,urlencode($address)));
if (empty($res)) {
throw new Exception("Empty response");
}
$json = json_decode($res);
if (empty($json) || count($json->results)<1) {
throw new Exception($json->status);
}
$first = current($json->results);
return array(
'lat'=> $first->geometry->location->lat,
'lng'=> $first->geometry->location->lng
);
}
function localize($shop, $address) {
try {
echo($address.'... ');
$coords = gps($address);
$shop->lat = $coords['lat'];
$shop->lng = $coords['lng'];
$shop->save();
echo("OK\n");
} catch (Exception $e) {
echo("ERROR [".$e->getMessage()."]\n");
$address_exploded = explode(',', $address);
if (count($address_exploded)>=2) {
unset($address_exploded[0]);
localize($shop, trim(implode(',', $address_exploded)));
}
}
}
foreach (Company::whereRaw('lat IS NULL or lng IS NULL')->get() as $model) {
localize($model, $model->address_complete.", Italy");
sleep(1);
}
}
protected function getArguments()
{
return array();
}
protected function getOptions()
{
return array();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment