Exemplo n.º 1
0
 public static function getCity($location)
 {
     $geocode = GeocodeModel::lookup($location);
     if (is_null($geocode)) {
         // Geocode was not in database, so perform Geocoding API request.
         $geocode = self::getGeocodeJSON($location);
         if (is_null($geocode)) {
             return null;
         }
     }
     $geocode = new Geocode($geocode);
     $address_components = $geocode->getAddressComponents();
     $city = null;
     $state = null;
     foreach ($address_components as $c) {
         if (in_array("locality", $c['types'])) {
             $city = $c['short_name'];
         }
         if (in_array("administrative_area_level_1", $c['types'])) {
             $state = $c['short_name'];
         }
     }
     if (is_null($city) || is_null($state)) {
         return null;
     }
     return "{$city}, {$state}";
 }
Exemplo n.º 2
0
 public function testGeocodeKey()
 {
     $actual = new Geocode('ADDR', false, 'DUMMYKEY');
     $this->assertEquals('https://maps.googleapis.com/maps/api/geocode/json?key=DUMMYKEY', $actual->getServiceUrl());
     $actual = new Geocode('ADDR', true, 'DUMMYKEY');
     $this->assertEquals('https://maps.googleapis.com/maps/api/geocode/json?key=DUMMYKEY', $actual->getServiceUrl());
 }
Exemplo n.º 3
0
 function test_all()
 {
     $address = "Av. Mal. Floriano Peixoto, 44 - Gonzaga, Santos - São Paulo, 11060-300, Brazil";
     //$address = "sd;lksdl;skdl;skd";
     $geocode = new Geocode($address);
     $lat = $geocode->address();
     echo "<pre>";
     print_r($geocode->state());
     echo "</pre>";
 }
 public function setGeocode($code_list, $foreignTable, $foreignId, $memberId)
 {
     $newcode_list = array();
     foreach ($code_list as $code) {
         $newcode_list[$code] = $code;
     }
     foreach ($this->getCodeList($foreignTable, $foreignId) as $geocode) {
         if (!in_array($geocode->getGeocode(), $code_list)) {
             $geocode->delete();
         } else {
             unset($newcode_list[$geocode->getGeocode()]);
         }
     }
     foreach ($newcode_list as $code) {
         $code = explode(',', $code);
         if (count($code) == 2) {
             $obj = new Geocode();
             $obj->setForeignId($foreignId);
             $obj->setForeignTable($foreignTable);
             $obj->setLat($code[0]);
             $obj->setLng($code[1]);
             $obj->setMemberId($memberId);
             $obj->save();
             $obj->free(true);
             unset($obj);
         }
     }
 }
Exemplo n.º 5
0
 function getClosestHub($address, $maxMiles)
 {
     $geocode = Geocode::geocode($address);
     $longitude = $geocode['longitude'];
     $latitude = $geocode['latitude'];
     $maxMeters = miles2meters($maxMiles);
     return self::$collection->findOne(array('geojson' => array('$near' => array('$geometry' => array('type' => 'Point', 'coordinates' => array($longitude, $latitude)), '$maxDistance' => $maxMeters))));
 }
Exemplo n.º 6
0
 public static function generateRandomLocation()
 {
     $location = [];
     $address = '';
     $catStreets = ['Major', 'Catalunya', 'Doctor', 'Pau Casals', 'Jacint Verdaguer'];
     $catTowns = ['Barcelona', 'Hospitalet de Llobregat', 'Badalona', 'Tarrasa', 'Sabadell', 'Lérida', 'Tarragona', 'Mataró', 'Santa Coloma de Gramanet', 'Reus', 'Gerona', 'Cornellá de Llobregat', 'San Cugat del Vallés', 'San Baudilio de Llobregat', 'Manresa', 'Rubí', 'Villanueva y Geltrú', 'Viladecans', 'El Prat de Llobregat', 'Castelldefels', 'Granollers', 'Sardañola del Vallés', 'Mollet del Vallés', 'Esplugas de Llobregat', 'Gavá', 'Figueras', 'San Felíu de Llobregat', 'Vich', 'Lloret de Mar', 'Blanes', 'Igualada', 'Villafranca del Panadés', 'Ripollet', 'Vendrell', 'Tortosa', 'Moncada y Reixach', 'San Adrián de Besós', 'Olot', 'Cambrils', 'San Juan Despí', 'Barberá del Vallés', 'Salt', 'San Pedro de Ribas', 'Sitges', 'Premiá de Mar', 'San Vicente dels Horts', 'Martorell', 'San Andrés de la Barca', 'Salou', 'Pineda de Mar', 'Santa Perpetua de Moguda', 'Valls', 'Molins de Rey', 'Calafell', 'Olesa de Montserrat', 'Castellar del Vallés', 'Palafrugell', 'El Masnou', 'Vilaseca', 'San Felíu de Guixols', 'Esparraguera', 'Amposta', 'Manlleu'];
     while (!$location || count(array_filter($location)) < 8) {
         $address = $catStreets[array_rand($catStreets)] . ', ' . mt_rand(1, 50) . ', ' . $catTowns[array_rand($catTowns)] . ', España';
         $location = Geocode::geocodeAddress($address);
     }
     $location['raw'] = $address;
     return $location;
 }
Exemplo n.º 7
0
<?php

global $MJob;
$jobs = $MJob->getAll();
foreach ($jobs as $job) {
    $job['geocode'] = Geocode::geocode($job['location']);
    $MJob->save($job, false);
}
Exemplo n.º 8
0
 private function auto_geocode_address()
 {
     $auto_geocode_field = $this->auto_geocode_field;
     $address = ${$auto_geocode_field};
     $geo = MultiGeocoder::geocode($address);
     if ($geo->success) {
         ${$lat_column_name} = $geo->lat;
         ${$lng_column_name} = $geo->lng;
     } else {
         $msg = $this->auto_geocode_error_message . ' ';
         $msg .= $address . ' in ' . $auto_geocode_field;
         Geocode::logger('error', $msg);
     }
     return $geo->success;
 }
Exemplo n.º 9
0
 /**
  * Сохранение новых данных в локальной БД
  *
  * @param float $latitude
  * @param dloat $longitude
  * @param string $lang
  * @param string $address
  */
 public function setToBase($latitude, $longitude, $lang = 'ru', $address)
 {
     if (empty($address)) {
         return false;
     }
     $_ = new Geocode();
     $_->latitude = $latitude;
     $_->longitude = $longitude;
     $_->lng = strtoupper($lang);
     $_->address = $address;
     return $_->save();
 }
Exemplo n.º 10
0
 function search()
 {
     // global $CStudent; $CStudent->requireLogin();
     global $params;
     $params = $_REQUEST;
     global $MSublet, $MStudent;
     // process without sorting/filtering
     function processRaw($sublet)
     {
         // Processing result
         $sublet['photo'] = isset($sublet['photos'][0]) ? $sublet['photos'][0] : $GLOBALS['dirpreFromRoute'] . 'assets/gfx/subletnophoto.png';
         $sublet['address'] = $sublet['address'];
         if (strlen($sublet['city']) > 0) {
             $sublet['address'] .= ', ' . $sublet['city'];
         }
         if (strlen($sublet['state']) > 0) {
             $sublet['address'] .= ', ' . $sublet['state'];
         }
         $sublet['proximity'] = isset($sublet['proximity']) ? $sublet['proximity'] : null;
         $sublet['summary'] = strmax($sublet['summary'], 100);
         $offset = 0.0001;
         $sublet['latitude'] = $sublet['geocode']['latitude'] + rand01() * $offset - $offset / 2;
         $sublet['longitude'] = $sublet['geocode']['longitude'] + rand01() * $offset - $offset / 2;
         return $sublet;
     }
     // Function for processing results and showing them
     function process($res, $sortby, $latitude, $longitude, $maxProximity)
     {
         $sublets = array();
         // Sort
         switch ($sortby) {
             case 'priceIncreasing':
                 $res->sort(array('price' => 1));
                 break;
             case 'priceDecreasing':
                 $res->sort(array('price' => -1));
                 break;
         }
         foreach ($res as $sublet) {
             $sublet['proximity'] = distance($latitude, $longitude, $sublet['geocode']['latitude'], $sublet['geocode']['longitude']);
             if ($maxProximity == 0 or $sublet['proximity'] <= $maxProximity) {
                 $sublets[] = processRaw($sublet);
             }
         }
         switch ($sortby) {
             case 'proximityIncreasing':
                 usort($sublets, function ($a, $b) {
                     if ($a['proximity'] < $b['proximity']) {
                         return -1;
                     }
                     if ($a['proximity'] > $b['proximity']) {
                         return 1;
                     }
                     return 0;
                 });
                 break;
         }
         return $sublets;
     }
     // Predefined searches
     $showSearch = true;
     if ($showSearch and !isset($params['search'])) {
         // If not searching for anything, then return last 6 entries
         $showMore = isset($_GET['showMore']);
         if ($showMore) {
             if (isset($_SESSION['showMore'])) {
                 $_SESSION['showMore'] += 6;
             } else {
                 $_SESSION['showMore'] = 12;
             }
             $showMore = $_SESSION['showMore'];
         } else {
             $_SESSION['showMore'] = 6;
         }
         $res = $MSublet->last($_SESSION['showMore']);
         $sublets = array();
         foreach ($res as $sublet) {
             $sublets[] = processRaw($sublet);
         }
         self::render('student/sublets/search/start', $this->dataSearchSetup());
         self::render('student/sublets/search/results', ['sublets' => $sublets, 'recent' => true, 'search' => 'housing', 'showMore' => $showMore]);
         return;
     }
     // Params to vars
     extract($data = $this->dataSearch(array_merge($this->dataSearchEmpty(), $params)));
     $this->startValidations();
     $this->validate(!is_null($geocode = Geocode::geocode($location)), $err, 'invalid location or daily search limit reached (come back tomorrow)');
     if ($this->isValid()) {
         $latitude = $geocode['latitude'];
         $longitude = $geocode['longitude'];
         $startdate = strtotime($startdate);
         $enddate = strtotime($enddate);
         $maxProximity = $proximity == null ? 50 : (int) $proximity;
         $minPrice = (double) $price0;
         $maxPrice = (double) $price1;
         $minOccupancy = (int) $occupancy;
         // Validate parameters
         if ($this->isValid()) {
             // Search query building and validations
             $query = array('publish' => true);
             $proximityDeg = distanceDeg($maxProximity);
             $query['geocode.latitude'] = array('$gte' => $latitude - $proximityDeg, '$lte' => $latitude + $proximityDeg);
             $query['geocode.longitude'] = array('$gte' => $longitude - $proximityDeg, '$lte' => $longitude + $proximityDeg);
             if (strlen($occupancy) > 0) {
                 $query['occupancy'] = array('$gte' => $minOccupancy);
             }
             if ($roomtype != 'Any') {
                 $query['roomtype'] = $roomtype;
             }
             if ($buildingtype != 'Any') {
                 $query['buildingtype'] = $buildingtype;
             }
             if ($gender != '' and $gender != 'other') {
                 $query['gender'] = array('$in' => array('', $gender));
             }
             if (count($amenities) > 0) {
                 $query['amenities'] = array('$all' => $amenities);
             }
             if (strlen($startdate) > 0) {
                 $query['startdate'] = array('$lte' => $startdate);
             }
             if (strlen($enddate) > 0) {
                 $query['enddate'] = array('$gte' => $enddate);
             }
             // Validate query
             $this->validateSearch($query, $err);
             if ($this->isValid()) {
                 // Performing search
                 $starttime = microtime(true);
                 $res = $MSublet->find($query);
                 $sublets = array();
                 $res = process($res, $sortby, $latitude, $longitude, $maxProximity);
                 foreach ($res as $sublet) {
                     $price = $sublet['price'];
                     switch ($sublet['pricetype']) {
                         case 'week':
                             $price *= 4.35;
                             break;
                         case 'day':
                             $price *= 30;
                             break;
                     }
                     if (strlen($price0) > 0 and $price < $price0) {
                         continue;
                     }
                     if (strlen($price1) > 0 and $price > $price1) {
                         continue;
                     }
                     $sublets[] = $sublet;
                 }
                 $delay = round((microtime(true) - $starttime) * 1000, 0);
                 self::render('student/sublets/search/results', ['sublets' => $sublets, 'delay' => $delay, 'latitude' => $latitude, 'longitude' => $longitude, 'maxProximity' => $maxProximity, 'showSearch' => $showSearch, 'data' => $data, 'search' => 'housing']);
                 // Send email notification of search to us
                 // $this->sendrequestreport("Search for sublets:", $sublets);
                 // Save search to db
                 global $MApp;
                 $MApp->recordSearch('sublets');
                 return;
             }
         }
     }
     self::error($err);
     self::render('partials/subletsearchform', ['data' => $data, 'search' => 'housing']);
 }
Exemplo n.º 11
0
 function adminapi()
 {
     global $MStudent, $MSocial;
     // make sure logged in
     if (!checkAdmin()) {
         return $this->errorString('permission denied');
     }
     $name = $_POST['name'];
     $json = $_POST['json'];
     switch ($name) {
         case 'load students':
             $students = $MStudent->find(array('hubs' => array('$exists' => true)));
             $ret = array();
             $counter = 0;
             foreach ($students as $student) {
                 $inc = true;
                 if (!isset($student['hubs']['geocode']) or is_null($student['hubs']['geocode'])) {
                     $city = $student['hubs']['city'];
                     $geocode = Geocode::geocode($city);
                     $student['hubs']['geocode'] = $geocode;
                     if (!is_null($geocode)) {
                         $MStudent->save($student);
                     } else {
                         $inc = false;
                     }
                 }
                 if ($inc) {
                     $ret[] = $student;
                 }
             }
             return $this->successString($ret);
         case 'create hub':
             $name = $json['name'];
             $location = Geocode::geocode($json['location']);
             $banner = $json['banner'];
             if ($location == null) {
                 return $this->errorString('location invalid');
             }
             $hub = array('name' => $name, 'location' => $location, 'banner' => $banner, 'members' => array(), 'posts' => array(), 'events' => array());
             $MSocial->save($hub);
             return $this->successString('hub created');
         case 'load hubs':
             $hubs = $MSocial->getAll();
             $ret = array();
             foreach ($hubs as $hub) {
                 $ret[] = $hub;
             }
             return $this->successString($ret);
             /**
              * JSON in form:
              *  {
              *      "students" : [ array of student IDs ]
              *      "hub" : // String containing the ID of the hub e.g. "55566d01172f559e8ece6c88"
              *  }
              */
         /**
          * JSON in form:
          *  {
          *      "students" : [ array of student IDs ]
          *      "hub" : // String containing the ID of the hub e.g. "55566d01172f559e8ece6c88"
          *  }
          */
         case 'add students to hub':
             $students = $json['students'];
             $hub = $json['hub'];
             if (!$hub || $hub == '') {
                 return $this->errorString('Please select a hub.');
             }
             foreach ($students as $student) {
                 $studententry = $MStudent->getById($student);
                 $name = $studententry['name'];
                 $email = $studententry['email'];
                 $hubentry = $MSocial->get($hub);
                 $hubname = $hubentry['name'];
                 $message = "\n              Hey {$name}\n              <br>\n              <br>\n              After the long wait, your hub is finally ready! Check out your hub <a href=\"https://sublite.net/hubs/hub.php?id={$hub}\">here</a>. In need of a new place to go out to eat this weekend? Use your hub to ask questions about your city and meet up with other interns! The possibilities are endless; just keep it civil and respectful.\n              <br><br>\n              Best,\n              <br>\n              Sublite Team\n            ";
                 sendgmail(array($email), "*****@*****.**", "Welcome to the {$hubname} social hub on Sublite!", $message);
                 $MSocial->joinHub($hub, $student);
             }
             return $this->successString();
     }
     return $this->errorString('invalid message');
 }
Exemplo n.º 12
0
 function data($data)
 {
     $title = clean($data['title']);
     $jobtype = clean($data['jobtype']);
     $deadline = clean($data['deadline']);
     $duration = str2float(clean($data['duration']));
     $startdate = clean($data['startdate']);
     $enddate = clean($data['enddate']);
     $salarytype = clean($data['salarytype']);
     $salary = clean($data['salary']);
     if ($salarytype != 'other') {
         $salary = str2float($salary);
     }
     if ($jobtype == 'fulltime' || $jobtype == 'parttime') {
         $duration = '';
         $enddate = '';
     }
     $company = $data['company'];
     $desc = clean($data['desc']);
     $location = clean($data['location']);
     $locationtype = '';
     if (isset($data['locationtype'])) {
         $locationtype = clean($data['locationtype']);
     }
     $geocode = Geocode::geocode($location);
     if ($locationtype) {
         $location = '';
         $geocode = '';
     }
     $requirements = clean($data['requirements']);
     return array('title' => $title, 'deadline' => $deadline, 'duration' => $duration, 'desc' => $desc, 'geocode' => $geocode, 'location' => $location, 'requirements' => $requirements, 'salary' => $salary, 'company' => $company, 'salarytype' => $salarytype, 'startdate' => $startdate, 'enddate' => $enddate, 'jobtype' => $jobtype, 'locationtype' => $locationtype);
 }
Exemplo n.º 13
0
 /**
  * Displays the map with the availiable screens
  */
 public function actionMap()
 {
     $model = Screen::model()->with('geocodes', 'yeshuv', 'commercials')->findAll();
     $array = array();
     date_default_timezone_set('Asia/Jerusalem');
     $now = new DateTime();
     $now = $now->modify("-10 minutes");
     $id = 0;
     $green = 0;
     foreach ($model as $m) {
         $color = "red";
         $screenAjax = ScreenAjax::model()->findByPk($m->id);
         if ($screenAjax) {
             $last = strtotime($screenAjax->last_date);
             if ($last > $now->getTimestamp()) {
                 $color = "green";
                 $green++;
             }
         }
         if (count($m->geocodes) < 1) {
             $geocode = new Geocode();
             $location = Screen::model()->geocodeLookup($m->name . ',' . $m->yeshuv->name_heb);
             $geocode->lat = $location['lat'];
             $geocode->lng = $location['lng'];
             if ($geocode->save()) {
                 $screenGeocode = new ScreenGeocodeAssignment();
                 $screenGeocode->screen_id = $m->id;
                 $screenGeocode->geocode_id = $geocode->id;
                 $screenGeocode->save();
             }
             $marker = array('id' => $id++, 'name' => $m->name . ', ' . $m->yeshuv->name_heb, 'url' => $m->webkey_nickname, 'lat' => $geocode->lat, 'lng' => $geocode->lng, 'commercial' => $m->commercials[0]->name, 'color' => $color);
             array_push($array, $marker);
         } else {
             $marker = array('id' => $id++, 'name' => $m->name . ', ' . $m->yeshuv->name_heb, 'url' => $m->webkey_nickname, 'lat' => $m->geocodes[0]->lat, 'lng' => $m->geocodes[0]->lng, 'commercial' => $m->commercials[0]->name, 'color' => $color);
             array_push($array, $marker);
         }
     }
     $this->render('map', array('markers' => $array, 'green' => $green));
 }
Exemplo n.º 14
0
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Screen();
     $weather = new Weather();
     $commercial = new Commercial();
     $theme = new Theme();
     $geocode = new Geocode();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Screen'])) {
         $model->attributes = $_POST['Screen'];
         if ($model->save()) {
             if (isset($_POST['Weather'])) {
                 $weather->attributes = $_POST['Weather'];
                 $screenWeather = new ScreenWeather();
                 $screenWeather->code = $weather->code;
                 $screenWeather->screen_id = $model->id;
                 if ($screenWeather->save()) {
                     Yii::app()->user->setFlash('success', Yii::t('screen', 'Weather code assigned successfully.'));
                 } else {
                     Yii::app()->user->setFlash('error', Yii::t('screen', 'Could not assign the Weather Code to the Screen.'));
                 }
             }
             if (isset($_POST['Commercial'])) {
                 $commercial->attributes = $_POST['Commercial'];
                 $screenCommercial = new ScreenCommercialAssignment();
                 $screenCommercial->commercial_id = $commercial->id;
                 $screenCommercial->screen_id = $model->id;
                 if ($screenCommercial->save()) {
                     Yii::app()->user->setFlash('success', Yii::t('screen', 'Commercial Area assigned successfully.'));
                 } else {
                     Yii::app()->user->setFlash('error', Yii::t('screen', 'Could not assign the Commercial Area to the Screen.'));
                 }
             }
             if (isset($_POST['Theme'])) {
                 $theme->attributes = $_POST['Theme'];
                 $screenTheme = new ScreenThemeAssignment();
                 $screenTheme->theme_id = $theme->id;
                 $screenTheme->screen_id = $model->id;
                 if ($screenTheme->save()) {
                     Yii::app()->user->setFlash('success', Yii::t('screen', 'Theme assigned successfully.'));
                 } else {
                     Yii::app()->user->setFlash('error', Yii::t('screen', 'Could not assign the theme to the Screen.'));
                 }
             }
             // Create geocode and insert the lng and lat and assign it to the screen
             $location = $model->geocodeLookup($model->name . ',' . $model->yeshuv->name_heb);
             $geocode->lat = $location['lat'];
             $geocode->lng = $location['lng'];
             if ($geocode->save()) {
                 $screenGeocode = new ScreenGeocodeAssignment();
                 $screenGeocode->screen_id = $model->id;
                 $screenGeocode->geocode_id = $geocode->id;
                 if ($screenGeocode->save()) {
                     Yii::app()->user->setFlash('success', Yii::t('screen', 'Geocode assigned successfully.'));
                 }
             } else {
                 Yii::app()->user->setFlash('error', Yii::t('screen', 'Could not assign the Geocode to the Screen.'));
             }
             Yii::app()->user->setFlash('success', Yii::t('screen', 'Screen created successfully.'));
             $this->redirect(array('view', 'id' => $model->id));
         }
     }
     $this->render('create', array('model' => $model, 'weather' => $weather, 'commercial' => $commercial, 'theme' => $theme));
 }
Exemplo n.º 15
0
 function __construct($msg = '')
 {
     error_reporting(E_ALL);
     Geocode::logger('error', $msg);
     throw new Exception($msg);
 }
Exemplo n.º 16
0
 private function geo_cinema($cinema)
 {
     $endereco = $cinema->address;
     $geocode = new Geocode($endereco);
     $cinema->address = $geocode->address();
     $cinema->lat = $geocode->lat();
     $cinema->long = $geocode->long();
     $cinema->city = $geocode->city();
     $estado = $geocode->state();
     if ($estado) {
         $cinema->state = $estado['name'];
         $cinema->state_code = $estado['short'];
     } else {
         $cinema->state = '';
         $cinema->state_code = '';
     }
     return $cinema;
 }