Example #1
0
 function getClosestHub($address, $maxMiles)
 {
     $geocode = geocode($address);
     $longitude = $geocode['longitude'];
     $latitude = $geocode['latitude'];
     $maxMeters = miles2meters($maxMiles);
     return $this->collection->findOne(array('geojson' => array('$near' => array('$geometry' => array('type' => 'Point', 'coordinates' => array($longitude, $latitude)), '$maxDistance' => $maxMeters))));
 }
Example #2
0
 public static function get($location)
 {
     $geocode = self::lookup($location);
     if (!is_null($geocode)) {
         return $geocode;
     }
     $geocode = geocode($location);
     if (is_null($geocode)) {
         return null;
     }
     self::record($location, $geocode);
     return $geocode;
 }
Example #3
0
function geo_town($address, $geocode = null)
{
    if (empty($geocode)) {
        $geocode = geocode($address);
    }
    if (empty($geocode['results'][0]['address_components'])) {
        return false;
    }
    $geocode = $geocode['results'][0]['address_components'];
    foreach ($geocode as $place) {
        if (in_array('locality', $place['types'])) {
            return $place['long_name'];
        }
    }
    return '';
}
Example #4
0
function test_function()
{
    $return = $_GET;
    $data_arr = geocode($_GET['street'], $_GET['city'], $_GET['state']);
    if ($data_arr == false) {
        exit("Google geocode api returns ZERO Results: Select correct address");
    }
    $latitude = $data_arr[0];
    $longitude = $data_arr[1];
    $furl = "https://api.forecast.io/forecast/96684c2d23e7643e7c49ecbcfa131e5f/{$latitude},{$longitude}?units={$_GET['degree']}&exclude=flags";
    //error_log($furl, 0);
    $resp_json = file_get_contents($furl);
    // decode the json
    $respjson = json_decode($resp_json, true);
    $return["json"] = json_encode($respjson);
    echo json_encode($return);
}
Example #5
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($location);
     if ($locationtype) {
         $location = '';
         $geocode = '';
     }
     $requirements = clean($data['requirements']);
     $link = clean($data['link']);
     if (!filter_var($link, FILTER_VALIDATE_EMAIL) && !preg_match('`^(https?:\\/\\/)`', $link)) {
         $link = "http://{$link}";
     }
     return array('title' => $title, 'deadline' => $deadline, 'duration' => $duration, 'desc' => $desc, 'geocode' => $geocode, 'location' => $location, 'requirements' => $requirements, 'link' => $link, 'salary' => $salary, 'company' => $company, 'salarytype' => $salarytype, 'startdate' => $startdate, 'enddate' => $enddate, 'jobtype' => $jobtype, 'locationtype' => $locationtype);
 }
Example #6
0
//if the form is submitted == if there are post variables
if (!empty($_POST)) {
    // print_r($_POST); // pour debug
    // print_r($_FILES); //for debug too
    // Récupération et traitement des variables du formulaire d'ajout/modification
    //loc_id ; //auto incremented at creation?!
    $loc_name = isset($_POST['loc_name']) ? trim($_POST['loc_name']) : '';
    $loc_adr = isset($_POST['loc_adr']) ? trim($_POST['loc_adr']) : '';
    $loc_city = isset($_POST['loc_city']) ? trim($_POST['loc_city']) : '';
    $loc_cp = isset($_POST['loc_cp']) ? intval(trim($_POST['loc_cp'])) : 0;
    $loc_desc = isset($_POST['loc_desc']) ? trim($_POST['loc_desc']) : '';
    //$loc_img est probablemnt a changer vu qu'on va devoir importer un fichier blob...
    $loc_img = isset($_POST['loc_img']) ? trim($_POST['loc_img']) : '';
    $loctype_typ_id = isset($_POST['loctype_typ_id']) ? intval(trim($_POST['loctype_typ_id'])) : 0;
    // coordonnées latitude & longitude
    $locXY = geocode($_POST['loc_adr'] . "," . $_POST['loc_city']);
    //for uploading image
    if (count($_FILES) > 0) {
        $loc_img = file_get_contents($_FILES['loc_img']['tmp_name']);
    }
    //sql for adding location
    if (!isset($_GET['id'])) {
        $add_loc_sql = "\n\t\tINSERT INTO locations (loc_name,loc_adr ,loc_city ,loc_cp ,loc_desc ,loc_img ,loctype_typ_id, loc_x, loc_y)\n\t\tVALUES (:name,:adr ,:city ,:cp ,:desc ,:img ,:typ_id ,:loc_x ,:loc_y)\n\t\t";
        $pdoStatement = $pdo->prepare($add_loc_sql);
        // Je bind toutes les variables de requête
        $pdoStatement->bindValue(':name', $loc_name);
        $pdoStatement->bindValue(':adr', $loc_adr);
        $pdoStatement->bindValue(':city', $loc_city);
        $pdoStatement->bindValue(':cp', $loc_cp);
        $pdoStatement->bindValue(':desc', $loc_desc);
        $pdoStatement->bindValue(':img', $loc_img);
    <style>
	
    #map_canvas{
        width:100%;
        height: 30em;
		}
		

    </style>
 
</head>
<body>
 
<?php 
if ($_GET) {
    $data = geocode($_GET['address']);
    $zoom = $_GET['zoom'];
    if (!$zoom) {
        $zoom = 14;
    }
    $mapaddress = urlencode($_GET['address']);
    $mapurl = "http://[YOUR DOMAIN HERE]/embedmap.php?address={$mapaddress}&zoom={$zoom}";
    // proceeds only if address is geocoded
    if ($data) {
        $latitude = $data[0];
        $longitude = $data[1];
        $address = $data[2];
        ?>
	
    <div id="map_canvas">Geocoding address...</div><br>
    
Example #8
0
	private function submit($post_data)
	{
		global $db, $template, $config, $user;
		
		
		$license_plate_input = (isset($post_data['license_plate_input'])) ? $post_data['license_plate_input'] : ''; //Errorno 1
		$location_input = (isset($post_data['location_input'])) ? $post_data['location_input'] : ''; //Errorno 2
		$date_input = (isset($post_data['date_input'])) ? explode('-', $post_data['date_input']) : ''; //Errorno 3
		$comments_input = (isset($post_data['comments_input'])) ? $post_data['comments_input'] : 'Geen comment'; //Errorno 4
		$upload_input = (isset($_FILES['photoupload'])) ? $_FILES['photoupload'] : '';
		
		if(get_licenseplate_sidecode($license_plate_input) == false)
		{
			return 1;
		}
		
		$location = geocode($location_input);
		
		if($location == false)
		{
			return 2;
		}
		
		$location_coords = $location[0];
		$location_readable = $location[1];
		
		if(sizeof($date_input) != 3)
		{
			return 3;
		}
		
		$timestamp = mktime(0,0,0,$date_input[1],$date_input[0],$date_input[2]);
		
		if($timestamp == false)
		{
			return 3;
		}
		
		$uploadname = '';
		
		if(!empty($upload_input))
		{
		
			if(!move_uploaded_file($_FILES['photoupload']['tmp_name'], 
			'/home/smartiechick/public_html/roadsterspot/uploads/spots/' . $_FILES['photoupload']['name']))
			{
				return 4;
			}
			else
			{
				$uploadname = $_FILES['photoupload']['name'];
			}
		}
		
        $roadster_id = 0;
        
        $sql = "SELECT * 
        	FROM roadster 
        	WHERE roadster_license_plate = '" . $db->sql_escape($license_plate_input) . "'";
		$result = $db->sql_query($sql);       
		$roadster = $db->sql_fetchrow($result);

		$roadster_id = $roadster['roadster_id'];

		if(empty($roadster))
		{
		    //Add new roadster
		    $sql = "INSERT INTO roadster 
		    	(roadster_license_plate) 
		    	VALUES ('" . $db->sql_escape($license_plate_input) . "')";
			$db->sql_query($sql);
		    
			$roadster_id = $db->sql_nextid();
		    //return 1;
		}
		
		//Add spot to the database
		$sql = "INSERT INTO spots 
			(user_id, roadster_id, spot_coordinates, spot_location_readable, spot_date, spot_comments, spot_photo) 
			VALUES ('" . $user->uid . "',
			'" . $roadster_id . "', 
			'" . $db->sql_escape($location_coords) . "', 
			'" . $db->sql_escape($location_readable) . "', 
			'" . $db->sql_escape($timestamp) . "', 
			'" . $db->sql_escape($comments_input) . "', 
			'" . $db->sql_escape($uploadname) . "')";
		$db->sql_query($sql);
		
		return 0;
	}
Example #9
0
        height:30em;
    }
     
    #map-label,
    #address-examples{
        margin:1em 0;
    }
    </style>
 
</head>
<body>
 
<?php 
if (isset($_POST['add'])) {
    // get latitude, longitude and formatted address
    $data_arr = geocode($_POST['res_add']);
    // if able to geocode the address
    if ($data_arr) {
        $latitude = $data_arr[0];
        $longitude = $data_arr[1];
        $formatted_address = $data_arr[2];
        ?>
 
    <!-- google map will be shown here -->
    <div id="gmap_canvas">Loading map...</div>
    <div id='map-label'>Map shows approximate location.</div>
 
    <!-- JavaScript to show google map -->
    <script type="text/javascript" src="http://maps.google.com/maps/api/js"></script>    
    <script type="text/javascript">
        function init_map() {
Example #10
0
$area_site = $details["area_site"];
$active_site = $details["active_site"];
// check to see if lat/lng are absent, and if so, geocode the city/state and
// temp store into $lat_site and $long_site so you get a general location pin
// on the map
if ($lat_site == null || $long_site == NULL) {
    // first check for city, state
    if (isset($city_site) && isset($state_site)) {
        $addr = $city_site . ", " . $state_site;
        // otherwise, if area has a value, use that
    } else {
        if (isset($area_site)) {
            $addr = $area_site;
        }
    }
    $coords = geocode($addr);
    // make sure we got a good result
    if ($coords) {
        $lat_site = $coords[0];
        $long_site = $coords[1];
    }
}
if ($active_site > 0 || permissions("Sites") >= 3) {
    //TODO: Indicate if site is inactive
    if ($street_site != NULL) {
        $address = $street_site . ", " . $city_site . ", " . $state_site . " " . $zip_site;
    } else {
        $address = $area_site;
    }
    if ($facilities_site == NULL) {
        $facilities_site = "No information on file";
<?php 
if ($_POST) {
    include_once '../Database/Database_Connection.php';
    $databaseConnection = new Database_Connection();
    $databaseConnection->createDatabase();
    $_store_name = $_POST['_store_name'];
    if (!empty($_store_name)) {
        $_store_rating = $_POST['_store_rating'];
        $_store_category = $_POST['_store_category'];
        $_default_address_street = $_POST['_default_address_street'];
        $_default_address_city = $_POST['_default_address_city'];
        $_default_address_state = $_POST['_default_address_state'];
        $_default_address_zip = $_POST['_default_address_zip'];
        $_default_address_country = $_POST['_default_address_country'];
        // get latitude, longitude and formatted address
        $data_arr = geocode($_default_address_street . ',' . $_default_address_city . ',' . $_default_address_state . ',' . $_default_address_zip . ',' . $_default_address_country);
        // if able to geocode the address
        if ($data_arr) {
            $latitude = $data_arr[0];
            $longitude = $data_arr[1];
            $databaseConnection->addStoreInfo($_store_name, $_store_rating, $_store_category, $latitude, $longitude, $_default_address_street, '', $_default_address_city, $_default_address_state, $_default_address_zip, $_default_address_country);
            echo "<script>window.location.reload()</script>";
        } else {
            echo "The address does not exist, please try again!";
        }
    } else {
        $delete_store_name = $_POST['_delete_store'];
        $databaseConnection->deletStoreInfo($delete_store_name);
    }
}
?>
Example #12
0
function spyview($from_date = "", $to_date = "", $rows = "999", $spytype = "")
{
    global $wpdb;
    $whereis = "";
    if ($spytype == 'spider') {
        $whereis = " AND spider!=''";
    } elseif ($spytype == 'nospider') {
        $whereis = " AND spider=''";
    } elseif ($spytype == 'spam') {
        $whereis = " AND spam>0";
    } elseif ($spytype == 'nospam') {
        $whereis = " AND spam=0";
    } elseif ($spytype == 'nospamspider') {
        $whereis = " AND spam=0 AND spider=''";
    } elseif ($spytype == 'searchengine') {
        $whereis = " AND searchengine!='' AND search!=''";
    } elseif ($spytype == 'referrer') {
        $whereis = " AND referrer!='' AND referrer NOT LIKE '%{$wpurl}%' AND searchengine='' AND search=''";
    } elseif ($spytype == 'comauthor') {
        $whereis = " AND comment_author!=''";
    } elseif ($spytype == 'loggedin') {
        $whereis = " AND username!=''";
    }
    //check for arguments...
    if (empty($to_date)) {
        $to_date = wassup_get_time();
    }
    if (empty($from_date)) {
        $from_date = $to_date - 5;
    }
    $table_tmp_name = $wpdb->prefix . "wassup_tmp";
    if (function_exists('get_option')) {
        $wassup_settings = get_option('wassup_settings');
    }
    if (!empty($wassup_settings['wassup_screen_res'])) {
        $screen_res_size = (int) $wassup_settings['wassup_screen_res'];
    } else {
        $screen_res_size = 670;
    }
    $max_char_len = $screen_res_size / 10;
    if (function_exists('get_bloginfo')) {
        $wpurl = get_bloginfo('wpurl');
        $siteurl = get_bloginfo('siteurl');
    }
    $qryC = $wpdb->get_results("SELECT id, wassup_id, max(timestamp) as max_timestamp, ip, hostname, searchengine, urlrequested, agent, referrer, spider, username, comment_author FROM {$table_tmp_name} WHERE timestamp BETWEEN {$from_date} AND {$to_date} {$whereis} GROUP BY id ORDER BY max_timestamp DESC");
    if (!empty($qryC)) {
        //restrict # of rows to display when needed...
        $row_count = 0;
        //display the rows...
        foreach ($qryC as $cv) {
            if ($row_count < (int) $rows) {
                $timestamp = $cv->max_timestamp;
                $ip = @explode(",", $cv->ip);
                if ($cv->referrer != '') {
                    if (!eregi($wpurl, $cv->referrer) or $cv->searchengine != "") {
                        if (!eregi($wpurl, $cv->referrer) and $cv->searchengine == "") {
                            $referrer = '<a href="' . $cv->referrer . '" target=_"BLANK"><span style="font-weight: bold;">' . stringShortener($cv->referrer, round($max_char_len * 0.8, 0)) . '</span></a>';
                        } else {
                            $referrer = '<a href="' . $cv->referrer . '" target=_"BLANK">' . stringShortener($cv->referrer, round($max_char_len * 0.9, 0)) . '</a>';
                        }
                    } else {
                        $referrer = __('From your blog', 'wassup');
                    }
                } else {
                    $referrer = __('Direct hit', 'wassup');
                }
                // User is logged in or is a comment's author
                if ($cv->username != "") {
                    $unclass = "-log";
                    $map_icon = "marker_loggedin.png";
                } elseif ($cv->comment_author != "" and $cv->username == "") {
                    $unclass = "-aut";
                    $map_icon = "marker_author.png";
                } elseif ($cv->spider != "") {
                    $unclass = "-spider";
                    $map_icon = "marker_bot.png";
                } else {
                    $map_icon = "marker_user.png";
                }
                // Start getting GEOIP info
                $geo_url = "http://api.hostip.info/get_html.php?ip=" . $ip[0] . "&position=true";
                $data = file($geo_url);
                if (eregi("unknown", $data[0])) {
                    $loc_country = eregi_replace("country: ", "", $data[0]);
                }
                if (eregi("unknown", $data[1])) {
                    $loc_city = eregi_replace("city: ", "", $data[1]);
                }
                $geoloc = $loc_country . " " . $loc_city;
                if ($wassup_settings['wassup_geoip_map'] == 1) {
                    $gkey = $wassup_settings['wassup_googlemaps_key'];
                    if ($geoloc != "") {
                        $geocode = geocode($geoloc, $gkey);
                        if ($geocode[0] != 200) {
                            $lat = explode(":", $data[2]);
                            $lat = $lat[1];
                            $lon = explode(":", $data[3]);
                            $lon = $lon[1];
                        } else {
                            $lat = $geocode[2];
                            $lon = $geocode[3];
                        }
                    } else {
                        $lat = 0;
                        $lon = 0;
                    }
                }
                $location = $data[0] . " - " . $data[1];
                ?>
		   <div class="sum-spy">
		   <span class="sum-box<?php 
                print $unclass;
                ?>
">
		   	<?php 
                print $ip[0];
                ?>
</span>
		   <div class="sum-det-spy"><span class="det1">
		   <?php 
                print '<a href="' . wAddSiteurl(htmlspecialchars(html_entity_decode($cv->urlrequested))) . '" target="_BLANK">';
                print stringShortener(html_entity_decode($cv->urlrequested), round($max_char_len * 0.9, 0));
                ?>
		   </a></span><br />
		   <span class="det2"><strong><?php 
                print gmdate("H:i:s", $timestamp);
                ?>
 - </strong>
		   <?php 
                print $referrer;
                ?>
		   <?php 
                print "<br />" . $location;
                //DEBUG ."$geocode[0]." / ".$lat." / ".$lon;
                ?>
		   </span>
		   </div></div>
<?php 
                // Print the JS code to add marker on the map
                if ($wassup_settings['wassup_geoip_map'] == 1) {
                    if ($lat != 0 && $lon != 0) {
                        $item_id = $cv->id;
                        $img_dir = $wpurl . '/wp-content/plugins/' . WASSUPFOLDER . '/img';
                        echo "\n                <script type=\"text/javascript\">\n                var icon{$item_id} = new GIcon();\n                icon{$item_id}.image = '" . $img_dir . "/" . $map_icon . "';\n                icon{$item_id}.shadow = '{$img_dir}/shadow.png';\n                icon{$item_id}.iconSize = new GSize(20.0, 34.0);\n                icon{$item_id}.shadowSize = new GSize(38.0, 34.0);\n                icon{$item_id}.iconAnchor = new GPoint(10.0, 17.0);\n                icon{$item_id}.infoWindowAnchor = new GPoint(10.0, 17.0);\n                var point = new GLatLng({$lat},{$lon});\n                var marker{$item_id} = new GMarker(point, icon{$item_id});\n                map.addOverlay(marker{$item_id});\n                GEvent.addListener(marker{$item_id}, 'click', function() {\n                marker{$item_id}.openInfoWindowHtml('<div style=\"white-space:nowrap\"><div class=\"bubble\">Ip: " . $ip[0] . "<br />Hour: " . gmdate('H:i:s', $timestamp) . "<br />Request: <a href=" . wAddSiteurl(htmlspecialchars(html_entity_decode($cv->urlrequested))) . " target=\"_BLANK\">" . stringShortener(html_entity_decode($cv->urlrequested), round($max_char_len * 0.9, 0)) . "</a><br />" . "</div></div>');\n                });\n                map.panTo(new GLatLng({$lat},{$lon}),3);\n                </script>";
                    }
                }
            }
            //end if row_count
            $row_count = $row_count + 1;
        }
        //end foreach
    } else {
        //display "no activity" periodically so we know spy is running...
        if ((int) $to_date % 7 == 0) {
            echo '<div class="sum-spy"><span class="det3">' . gmdate("H:i:s", $to_date) . ' - ' . __("No visitor activity", "wassup") . ' &nbsp; &nbsp; :-( &nbsp; </span></div>';
        }
    }
    //end if !empty($qryC)
}
Example #13
0
switch ($task2) {
    case 'savecoord':
        savecoord();
        jexit();
        break;
    case 'saveaddress':
        saveaddress();
        jexit();
        break;
    case 'getlistings':
        $count = JRequest::getInt('count', 25);
        getlistings($count);
        jexit();
        break;
    default:
        geocode();
}
function savecoord()
{
    $db =& JFactory::getDBO();
    $link_ids = JRequest::getVar('link_id', array(), 'post');
    JArrayHelper::toInteger($link_ids, array(0));
    $lats = JRequest::getVar('lat', array(), 'post');
    $lngs = JRequest::getVar('lng', array(), 'post');
    $coordinates = array();
    $done_link_ids = array();
    if (empty($link_ids)) {
        echo '';
    } else {
        foreach ($link_ids as $link_id) {
            if ($lats[$link_id] && !empty($lats[$link_id]) && $lngs[$link_id] && !empty($lngs[$link_id])) {
Example #14
0
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
require 'header.php';
require 'navbar.php';
$address = $_POST['address'];
$db = connect();
$geo_var = geocode($address);
$latitude = $geo_var[0];
$longitude = $geo_var[1];
$city = $geo_var[2];
$api_results = get_api_results($latitude, $longitude);
$insert_api_results = insert_api_results($db, $api_results);
$pop_var = populate_variables($db, $latitude, $longitude);
function page_title()
{
    $title = 'Heatery';
    if (isset($title) && is_string($title)) {
        print_r($title);
    } else {
        print_r('Circle Squared Data Labs');
    }
}
Example #15
0
echo $pop3->numMsg() . " message(s) in mailbox\n";
// print message headers
if ($pop3->numMsg() > 0) {
    for ($x = 1; $x <= $pop3->numMsg(); $x++) {
        $hdrs = $pop3->getParsedHeaders($x);
        print_r($hdrs);
        //echo $hdrs['From'] . "\n" . $hdrs['Subject'] . "\n" . $hdrs['Message-Id'] . "\n\n";
        $count = 0;
        // Only process emails from xxx.
        //        if (preg_match('/evoldir\@evol.biology.mcmaster.ca/', $pop3->getBody($x)))
        if (preg_match('/evoldir\\@evol.biology.mcmaster.ca/', $hdrs['From'])) {
            $id = store_message($hdrs, $pop3->getBody($x));
            if ($id != '') {
                // It's a new message
                // geocode
                $latlng = geocode($pop3->getBody($x));
                if ($latlng) {
                    print_r($latlng);
                    store_latlng($id, $latlng);
                }
                // generate Tinyurl
                $url = 'http://tinyurl.com/api-create.php?url=http://bioguid.info/services/evoldir/get.php?id=' . $id;
                $tiny = get($url);
                $status = $hdrs['Subject'] . ' ' . $tiny;
                echo $status . "\n";
                // Send message to twitter
                if ($config['oauth']) {
                    $parameters = array('status' => $status);
                    $status = $connection->post('statuses/update', $parameters);
                    print_r($status);
                } else {
Example #16
0
 function update_post($id)
 {
     // delete_post_meta($id, '_geopress_id');
     global $wpdb;
     $postdata = $wpdb->get_row("SELECT * FROM {$wpdb->posts} WHERE ID = '{$id}'");
     $addr = $_POST['addr'];
     $geometry = $_POST['geometry'];
     $locname = $_POST['locname'];
     // Allow the location to be set within the post body
     if (preg_match_all('/GEOPRESS_LOCATION\\((.+)\\)/', $postdata->post_content, $matches) > 0) {
         // $locname = $matches[1];
         $addr = $matches[1][0];
     } elseif (preg_match_all('/geo:lat=([-\\d\\.]+)(.*)?geo:lon[g]?=([-\\d\\.]+)/', $postdata->post_content, $matches) > 0) {
         // $locname = $matches[1];
         $addr = "[" . $matches[1][0] . "," . $matches[3][0] . "]";
     } else {
     }
     // $map_format = $_POST['geopress_map_format'];
     // $map_zoom = $_POST['geopress_map_zoom'];
     // $map_type = $_POST['geopress_map_type'];
     if ($addr) {
         // if just lat/lon coordinates were given, don't geocode
         if (!preg_match('/\\[(.+),[ ]?(.+)\\]/', $addr, $matches)) {
             // If the user set the coordinates via the web interface (using the geocoder), don't change it here.
             if (preg_match('/(.+),[ ]?(.+)/', $geometry, $matches)) {
                 $lat = $matches[1];
                 $lon = $matches[2];
             } else {
                 list($lat, $lon) = geocode($addr);
             }
         } else {
             $lat = $matches[1];
             $lon = $matches[2];
         }
         list($warn, $mapurl) = yahoo_mapurl($addr);
         $coords = "{$lat} {$lon}";
         $coord_type = "point";
         // Create a new loc - therefore -1
         $geo_id = GeoPress::save_geo(-1, $locname, $addr, $coords, $coord_type, $warn, $mapurl, 1, $map_format, $map_zoom, $map_type);
         $updated = update_post_meta($id, '_geopress_id', $geo_id);
         if (!$updated) {
             add_post_meta($id, '_geopress_id', $geo_id);
         }
     }
 }
Example #17
0
function simpleGeocode($tlat, $tlong)
{
    $host = "maps.google.com";
    $addr = $tlat . "," . $tlong;
    $datas = explode(",", geocode($addr, $host, GOOGLE_API_KEY));
    //print_r($datas);
    //if (! ($datas && $datas['Status']['code'])) {
    //		return null;
    //	}
    //	$statusCode = $datas['Status']['code'];
    //	if ($statusCode == "602" || ! $datas['Placemark']) {
    //		return array();
    //	} else if ($statusCode != "200") {
    //		return null;
    //	}
    //	$result = array();
    //	for ($t=0;$t<count(datas);$t++) {
    //	   $result[] = $datas['Placemark'][$t]['address'];
    //	   //$placemark['address'];
    //	   //echo $datas['Placemark'][$t]['address'];
    //	}
    return $datas[2] . "-" . $datas[3] . "-" . $datas[4] . "-" . $datas[5];
}
Example #18
0
<?php

global $MJob;
$jobs = $MJob->getAll();
foreach ($jobs as $job) {
    $job['geocode'] = geocode($job['location']);
    $MJob->save($job, false);
}
}
function splitAddress($addr)
{
    $lines = explode("<br>", $addr);
    $street = strip_tags($lines[0]);
    $city = preg_replace('/[^a-z ]/i', '', strip_tags($lines[1]));
    return array($street, $city);
}
$html = scraperWiki::scrape("http://www.kosherinfrance.com/liste-restau.php?Action=chercher&pageEncours=1&chercher=1&Nom=&Ville=&Arrondissement=&Departements=0&Regions=11&Specialites=0&Restaurations=0&Certifications=0&chercher2=Submit");
require 'scraperwiki/simple_html_dom.php';
$dom = new simple_html_dom();
$dom->load($html);
foreach ($dom->find(".listResult") as $restaurant) {
    $name = $restaurant->find(".name h3", 0);
    $link = $name->find("a", 0);
    $addr = $restaurant->find(".name .place", 0);
    $logo = $restaurant->find(".thumb img", 0);
    $cuisines = $restaurant->find(".type .spec");
    $cert = $restaurant->find(".surveillance", 0);
    $cleanCuisines = array_map(function ($c) {
        return utf8_encode(trim($c->plaintext));
    }, $cuisines);
    if ($link->href != '') {
        $latLng = geocode($addr);
        if (!empty($latLng)) {
            $address = utf8_encode($addr->plaintext);
            $record = array('url' => 'http://www.kosherinfrance.com/' . $link->href, 'name' => utf8_encode(array_pop(explode('Kosher Restaurant ', $name->plaintext))), 'originalAddress' => $address, 'address' => $latLng[2], 'lat' => $latLng[0], 'lng' => $latLng[1], 'logo' => 'http://www.kosherinfrance.com/' . $logo->src, 'cuisine' => implode(", ", $cleanCuisines), 'certification' => utf8_encode($cert->plaintext));
            scraperwiki::save(array('url'), $record);
        }
    }
}
Example #20
0
        ?>
		<div class="col-md-8 col-sm-6 col-xs-12 show-search">
      <ul class="row" id="list-map">
		<?php 
        $jsonData = array();
        while ($my_the_query->have_posts()) {
            $my_the_query->the_post();
            $attachment_id = get_post_thumbnail_id(get_the_ID());
            if (!empty($attachment_id)) {
                $img = get_the_post_thumbnail(get_the_ID(), array($width, $height));
            } else {
                $img = '<img src="' . get_stylesheet_directory_uri() . '/images/default.jpg" alt="' . get_the_title() . '" title="' . get_the_title() . '">';
            }
            // create json map
            $address = get_field('address');
            $dataLatLng = geocode($address);
            //			if(wpmd_is_notdevice()){
            //				$des = '<p class="address">'.the_excerpt_max_charlength(25).'</p>';
            //			}else{
            //				$des = '';
            //			}
            $url = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
            $total_comment = getFacebookDetails($url);
            $jsonData[] = array('title' => get_the_title(), 'lng' => $dataLatLng[0], 'lat' => $dataLatLng[1], 'address' => '', 'vote' => '<p><span>Bình chọn:</span>' . the_ratings() . '</p>', 'comment' => '<p class="review">Bình luận: <span>' . $total_comment . '</span></p>', 'img' => $img, 'baseurl' => get_the_permalink());
            ?>
        
		<?php 
        }
        ?>
			</ul>
			<?php 
Example #21
0
 <i> *-Mandatory fields. </i><td>

            </form>
<div style="text-align: center; margin-top: 10px; font-weight:bold" id="footer">

  <a href="http://forecast.io/" title="url"><u>Powered by Forecast.io</u></a>
</div>
        </div>


<?php 
//if($_POST['address'] != null or $_POST['address'] != "") {
if ($_POST) {
    // get latitude, longitude and formatted address
    $data_arr = geocode($_POST['address'], $_POST['city'], $_POST['state']);
    //$data_arr = geocode($_POST['address']);
    if ($data_arr == false) {
        //echo "Google geocode reurns ZERO Results";
        exit("Google geocode api returns ZERO Results: Select correct address");
    }
    // if able to geocode the address
    if ($data_arr) {
        $latitude = $data_arr[0];
        $longitude = $data_arr[1];
        $furl = "https://api.forecast.io/forecast/96684c2d23e7643e7c49ecbcfa131e5f/{$latitude},{$longitude}?units={$_POST['unit']}&exclude=flags";
        //echo $furl;
        // get the json response
        $resp_json = file_get_contents($furl);
        // decode the json
        $respjson = json_decode($resp_json, true);
Example #22
0
    $lat_site = $_POST[$varname];
} else {
    $lat_site = $site[$varname];
}
$varname = "long_site";
if (isset($_POST[$varname]) && is_string($_POST[$varname])) {
    $long_site = $_POST[$varname];
} else {
    $long_site = $site[$varname];
}
//check to see if either lat or lng is NULL and update if the address is not null
if (($site['lat_site'] == NULL or $site['long_site'] == NULL) && $street_site != NULL) {
    //combine the address fields into a standard USPS address
    $address = $street_site . ", " . $city_site . ", " . $state_site . " " . $zip_site;
    //pass $address to geocode()
    $result = geocode($address);
    //store the results in the appropriate variables
    //you give one variable and it returns an array containing two items: a lat
    //value and a long value.
    $lat_site = $result[0];
    $long_site = $result[1];
}
echo '<div class="form-group"><label for=' . $varname . '>Latitude:</label><input type="number" step="any" ' . 'name="' . $varname . '" value="' . $lat_site . '">
     <br/>Format: 29.1234567</div>' . "\n";
echo '<div class="form-group"><label for=' . $varname . '>Longitude:</label><input type="number" step="any" ' . 'name="' . $varname . '"  value="' . $long_site . '"> <br/>Format: -90.1234567
     </div>' . "\n";
/*****************************************************************************/
$varname = "active_site";
// Note: $_POST["active_site" is *only* set if the checkbox is ticked.
if (isset($_POST['id'])) {
    // So check if this was a submission
Example #23
0
function mm_map()
{
    wp_enqueue_script('maps-api');
    wp_enqueue_script('init-script');
    $map_settings = get_option('mm_plugin_settings');
    if (isset($map_settings['scroll'])) {
        $scroll = true;
    } else {
        $scroll = false;
    }
    if (isset($map_settings['controls'])) {
        $controls = true;
    } else {
        $controls = false;
    }
    $map_options = [];
    $map_options[] = [$map_settings['zoom'], $scroll, $controls, $map_settings['styles']];
    $locations_a = [];
    $args = array('post_type' => 'mm', 'post_status' => 'publish', 'posts_per_page' => -1);
    $loop = new WP_Query($args);
    while ($loop->have_posts()) {
        $loop->the_post();
        $mm_title = get_the_title();
        $the_post_id = get_the_ID();
        $mm_longitude = get_post_meta(get_the_ID(), 'mm_longitude', true);
        $mm_latitude = get_post_meta(get_the_ID(), 'mm_latitude', true);
        $mm_address = get_post_meta(get_the_ID(), "mm_address", true);
        $mm_city = get_post_meta(get_the_ID(), "mm_city", true);
        $mm_zip = get_post_meta(get_the_ID(), "mm_zip", true);
        $mm_country = get_post_meta(get_the_ID(), "mm_country", true);
        $mm_url = get_post_meta(get_the_ID(), "mm_url", true);
        $mm_featured = get_post_meta(get_the_ID(), "mm_featured", true);
        $mm_description = get_post_meta(get_the_ID(), "mm_description", true);
        $mm_icon = get_post_meta(get_the_ID(), "mm_icon", true);
        $mm_featured_animation = get_post_meta(get_the_ID(), "mm_featured_animation", true);
        $mm_info_window = get_post_meta(get_the_ID(), 'mm_info_window', true);
        $mm_show_address = get_post_meta(get_the_ID(), 'mm_show_address', true);
        $mm_show_zip = get_post_meta(get_the_ID(), 'mm_show_zip', true);
        $mm_show_city = get_post_meta(get_the_ID(), 'mm_show_city', true);
        $mm_show_country = get_post_meta(get_the_ID(), 'mm_show_country', true);
        $mm_show_description = get_post_meta(get_the_ID(), 'mm_show_description', true);
        $mm_show_url = get_post_meta(get_the_ID(), 'mm_show_url', true);
        $mm_info_window_data = "";
        $mm_info_window_data .= '<strong>' . $mm_title . '</strong>' . '</br>';
        if ($mm_address !== "" && $mm_show_address == "yes") {
            $mm_info_window_data .= $mm_address . '</br>';
        }
        if ($mm_zip !== "" && $mm_show_zip == "yes") {
            $mm_info_window_data .= $mm_zip . '</br>';
        }
        if ($mm_city !== "" && $mm_show_city == "yes") {
            $mm_info_window_data .= $mm_city . '</br>';
        }
        if ($mm_country !== "" && $mm_show_country == "yes") {
            $mm_info_window_data .= $mm_country . '</br>';
        }
        if ($mm_description !== "" && $mm_show_description == "yes") {
            $mm_info_window_data .= '<h6>' . $mm_description . '</h6> </br>';
        }
        if ($mm_url !== "" && $mm_show_url == "yes") {
            $mm_info_window_data .= '<a href="' . $mm_url . '" class="mm_location_url" target="_blank">Website</a>';
        }
        $locations_a[] = [$mm_longitude, $mm_latitude, $mm_featured, $mm_icon, $mm_featured_animation, $mm_info_window, $mm_info_window_data];
    }
    wp_reset_postdata();
    $option_check = get_option('mm_plugin_center_check');
    if ($option_check['city'] != $map_settings['city'] || $option_check['zip'] != $map_settings['zip'] || $option_check['country'] != $map_settings['country'] || $option_check['address'] != $map_settings['address']) {
        $center_at = geocode($map_settings['zip'] . ', ' . $map_settings['city'] . ', ' . $map_settings['country'] . ', ' . $map_settings['address']);
        update_option('mm_center_longitude', $center_at[0]);
        update_option('mm_center_latitude', $center_at[1]);
        $option_check['zip'] = $map_settings['zip'];
        $option_check['city'] = $map_settings['city'];
        $option_check['country'] = $map_settings['country'];
        $option_check['address'] = $map_settings['address'];
        update_option('mm_plugin_center_check', $option_check);
    } else {
        $center_at = array(get_option('mm_center_longitude'), get_option('mm_center_latitude'));
    }
    ?>
<script>  
  var location_marker = <?php 
    echo json_encode($locations_a);
    ?>
;
  var map_options = <?php 
    echo json_encode($map_options);
    ?>
; 
  var center_at = <?php 
    echo json_encode($center_at);
    ?>
; 
</script>
<?php 
    $mm_shortcode = '<div id="googleMap" style="width:100%;height:' . $map_settings['height'] . 'px;"></div>';
    return $mm_shortcode;
}
Example #24
0
// get csv file from tmp upload dir
$csv = $_FILES['csv']['tmp_name'];
// parse csv into array
$csvAsArray = array_map('str_getcsv', file($csv));
$gps = array();
$columns = array($_POST['col1'], $_POST['col2'], $_POST['col3'], $_POST['col4'], $_POST['col5']);
$streetIndex = array_search('Street', $columns);
$cityIndex = array_search('City', $columns);
$stateIndex = array_search('State', $columns);
$catIndex = array_search('Category', $columns);
foreach ($csvAsArray as $key => $value) {
    // loop through each row in the csv, parse the values
    $address = $value[$streetIndex] . ' ' . $value[$cityIndex] . ', ' . $value[$stateIndex];
    $category = $value[$catIndex];
    $coords = geocode($address);
    $lat = $coords['lat'];
    $lon = $coords['lon'];
    $gps[$key]['lat'] = $lat;
    $gps[$key]['lon'] = $lon;
    // gets the color based on a truncated md5 hex of the category
    $gps[$key]['img'] = substr(md5($category), 0, 6);
    // the google maps geocode api has a 10 req/sec limit, so a delay between each loop prevents
    // the code from failing
    usleep(100000);
}
echo json_encode($gps);
//echo json_encode($csvAsArray);
// TODO
// GEOCODE ADDRESSES IN THE LOOP LIKELY IN THIS PAGE
// RETURN DATA FORMATTED DIRECTLY FOR MAP MARKERS FROM THIS PAGE
Example #25
0
 $details = test_input($_POST['details']);
 $status = "valid";
 $time = date("Y-m-d H-i-s");
 $address1 = test_input($_POST['address1']);
 $address2 = test_input($_POST['address2']);
 $city = test_input($_POST['city']);
 $state = test_input($_POST['state']);
 $country = test_input($_POST['country']);
 $zipcode = test_input($_POST['zipcode']);
 $address = trim($address1 . $address2 . $city . $state . $country);
 //format the date
 $start_date = new DateTime($start_date);
 $start_date = date_format($start_date, 'Y-m-d');
 $end_date = new DateTime($start_date);
 $end_date = date_format($end_date, 'Y-m-d');
 $data_arr = geocode($address);
 // if able to geocode the address
 if ($data_arr) {
     $latitude = $data_arr[0];
     $longitude = $data_arr[1];
     $formatted_address = $data_arr[2];
 } else {
     //if not set lat and lng to 0;
     $latitude = 0;
     $longitude = 0;
     $formatted_address = $address1 . $address2 . ',' . $city . ', ' . $state . $zipcode . ',' . $country;
 }
 //Image properties
 //if user upload a image, process it.
 if (!empty($_FILES['image'])) {
     $file = $_FILES['image'];
Example #26
0
function mm_save_settings_box($post_id, $post, $update)
{
    if ((!isset($_POST["meta-box-nonce1"]) || !wp_verify_nonce($_POST["meta-box-nonce1"], basename(__FILE__))) && (!isset($_POST["meta-box-nonce2"]) || !wp_verify_nonce($_POST["meta-box-nonce2"], basename(__FILE__))) && (!isset($_POST["meta-box-nonce3"]) || !wp_verify_nonce($_POST["meta-box-nonce3"], basename(__FILE__)))) {
        return $post_id;
    }
    if (!current_user_can("edit_post", $post_id)) {
        return $post_id;
    }
    if (defined("DOING_AUTOSAVE") && DOING_AUTOSAVE) {
        return $post_id;
    }
    $slug = "mm";
    if ($slug != $post->post_type) {
        return $post_id;
    }
    $meta_mm_address = "";
    $meta_mm_city = "";
    $meta_mm_zip = "";
    $meta_mm_country = "";
    $meta_mm_longitude = "";
    $meta_mm_latitude = "";
    $meta_mm_url = "";
    $meta_mm_featured = "";
    $meta_mm_featured_animation = "";
    $meta_mm_description = "";
    $meta_mm_icon = "";
    $meta_mm_info_window = "";
    $meta_mm_show_address = "";
    $meta_mm_show_city = "";
    $meta_mm_show_zip = "";
    $meta_mm_show_country = "";
    $meta_mm_show_description = "";
    $meta_mm_show_url = "";
    if (isset($_POST["mm_address"])) {
        $meta_mm_address = $_POST["mm_address"];
        update_post_meta($post_id, "mm_address", $meta_mm_address);
        $geo_address = $meta_mm_address;
    }
    if (isset($_POST["mm_city"])) {
        $meta_mm_city = $_POST["mm_city"];
        update_post_meta($post_id, "mm_city", $meta_mm_city);
        $geo_city = $meta_mm_city;
    }
    if (isset($_POST["mm_zip"])) {
        $meta_mm_zip = $_POST["mm_zip"];
        update_post_meta($post_id, "mm_zip", $meta_mm_zip);
        $geo_zip = $meta_mm_zip;
    }
    if (isset($_POST["mm_country"])) {
        $meta_mm_country = $_POST["mm_country"];
        update_post_meta($post_id, "mm_country", $meta_mm_country);
        $geo_country = $meta_mm_country;
    }
    $address = $geo_zip . ', ' . $geo_city . ', ' . $geo_address . ', ' . $geo_country;
    $lat_lon = geocode($address);
    if ($lat_lon) {
        update_post_meta($post_id, "mm_longitude", $lat_lon[0]);
        update_post_meta($post_id, "mm_latitude", $lat_lon[1]);
    }
    if (isset($_POST["mm_url"])) {
        $meta_mm_url = $_POST["mm_url"];
        update_post_meta($post_id, "mm_url", $meta_mm_url);
    }
    if (isset($_POST["mm_featured"])) {
        $meta_mm_featured = $_POST["mm_featured"];
        update_post_meta($post_id, "mm_featured", $meta_mm_featured);
    } else {
        update_post_meta($post_id, "mm_featured", 'no');
    }
    if (isset($_POST["mm_featured_animation"])) {
        $meta_mm_featured_animation = $_POST["mm_featured_animation"];
        update_post_meta($post_id, "mm_featured_animation", $meta_mm_featured_animation);
    }
    if (isset($_POST["mm_info_window"])) {
        $meta_mm_info_window = $_POST["mm_info_window"];
        update_post_meta($post_id, "mm_info_window", $meta_mm_info_window);
    } else {
        update_post_meta($post_id, "mm_info_window", 'no');
    }
    if (isset($_POST["mm_description"])) {
        $meta_mm_description = $_POST["mm_description"];
        update_post_meta($post_id, "mm_description", $meta_mm_description);
    }
    if (isset($_POST["mm_icon"])) {
        $meta_mm_icon = $_POST["mm_icon"];
        update_post_meta($post_id, "mm_icon", $meta_mm_icon);
    }
    if (isset($_POST["mm_show_address"])) {
        $meta_mm_show_address = $_POST["mm_show_address"];
        update_post_meta($post_id, "mm_show_address", $meta_mm_show_address);
    } else {
        update_post_meta($post_id, "mm_show_address", 'no');
    }
    if (isset($_POST["mm_show_city"])) {
        $meta_mm_show_city = $_POST["mm_show_city"];
        update_post_meta($post_id, "mm_show_city", $meta_mm_show_city);
    } else {
        update_post_meta($post_id, "mm_show_city", 'no');
    }
    if (isset($_POST["mm_show_zip"])) {
        $meta_mm_show_zip = $_POST["mm_show_zip"];
        update_post_meta($post_id, "mm_show_zip", $meta_mm_show_zip);
    } else {
        update_post_meta($post_id, "mm_show_zip", 'no');
    }
    if (isset($_POST["mm_show_country"])) {
        $meta_mm_show_country = $_POST["mm_show_country"];
        update_post_meta($post_id, "mm_show_country", $meta_mm_show_country);
    } else {
        update_post_meta($post_id, "mm_show_country", 'no');
    }
    if (isset($_POST["mm_show_description"])) {
        $meta_mm_show_description = $_POST["mm_show_description"];
        update_post_meta($post_id, "mm_show_description", $meta_mm_show_description);
    } else {
        update_post_meta($post_id, "mm_show_description", 'no');
    }
    if (isset($_POST["mm_show_url"])) {
        $meta_mm_show_url = $_POST["mm_show_url"];
        update_post_meta($post_id, "mm_show_url", $meta_mm_show_url);
    } else {
        update_post_meta($post_id, "mm_show_url", 'no');
    }
}
Example #27
0
    </div>
    <!-- /.container-fluid -->

</nav><!-- /.navbar-default -->
<div class="container-fluid" id="main">
        <div class="row">
            <div class="col-xs-12" id="left">
                <div id="info_panel" class="panel panel-default">
                    <div id="info_card"></div>
                 </div><!--@end .panel-heading-->
            </div><!--@end .col-xs-4-->
        </div><!--@end .row-->

<?php 
if ($_POST) {
    $data_arr = geocode($_POST['address']);
    $limit = $_POST['limit'];
    $distance = $_POST['distance'];
    if ($data_arr) {
        $latitude = number_format($data_arr[0], 2);
        $longitude = number_format($data_arr[1], 2);
        $city = $data_arr[2];
        date_default_timezone_set("America/New_York");
        $today = date('l, F jS');
        $client_id = "LUDUFON05OQ3US4C0FT0TEKWXKSD0NHIPVGKF0TGUZGY4YUR";
        $client_secret = "F2E3NQTQKY3WS1APVGFVA31ESHW2ONNPVNJ11NPYVBV05W2I";
        require '/Users/admin/Documents/credentials/connect.php';
        $conn1 = new mysqli($servername, $username, $password, $dbname);
        if ($conn1->connect_error) {
            die("Connection failed:" . $conn1->connect_error);
            exit;
Example #28
0
$sql = mysql_query("SELECT * FROM tb_rm") or die(mysql_error());
$kenyamanan = get_bobot(round($_POST['kenyamanan']));
$kebersihan = get_bobot_dua(round($_POST['kebersihan']));
$harga = get_bobot_tiga($_POST['harga']);
$pelayanan = get_bobot_dua(round($_POST['pelayanan']));
$jarak = get_bobot_empat($_POST['jarak']);
array_push($w, $kenyamanan);
array_push($w, $kebersihan);
array_push($w, $harga);
array_push($w, $pelayanan);
array_push($w, $jarak);
$alamat = $_POST['lokasi'];
$lat_lokasi = $_POST['latitude'];
$lng_lokasi = $_POST['longitude'];
if ($alamat != '') {
    $geo_alamat = geocode($alamat);
} else {
    $geo_alamat = array($_POST['latitude'], $_POST['longitude']);
}
?>

<script type="text/javascript" src = "http://maps.googleapis.com/maps/api/js?sensor=false";></script>
<script type="text/javascript" src = "js/infobox.js";></script>

<div class="container">                 
	<div class="accordion with-marker" data-role="accordion" data-closeany="false">
	    <div class="accordion-frame">
	        <a class="heading bg-Blue fg-white" href="#">Tampilkan/Sembunyikan Log</a>
	        <div class="content bg-white">
	            <p>Diketahui Bobot (W) = <?php 
echo '(' . $kenyamanan . ', ' . $kebersihan . ', ' . $harga . ', ' . $pelayanan . ', ' . $jarak . ')';
Example #29
0
     $descrip = $result['descrip'];
     $incorrect = $result['incorrect'];
     $node_type_id = $result['node_type_id'];
     $select_node = '<select id="id">';
     $select_node .= '<option value="' . clean($_GET['node_id']) . '" SELECTED">' . $node_id . '</option>';
     $select_node .= '</select>';
 } else {
     if ($_GET['act'] == 'n_node') {
         $city_id = clean($_GET['city_id']);
         pg_query("UPDATE " . $table_node . " SET is_new = 'f'::boolean WHERE address IS NOT NULL");
         // забить в полный адрес с геокодирования
         $sql = "SELECT id, ST_X(ST_astext(the_geom)) AS lon, ST_Y(ST_astext(the_geom)) AS lat FROM " . $table_node . " WHERE is_new = true AND address_full IS NULL";
         $result = pg_query($sql);
         if (pg_num_rows($result)) {
             while ($row = pg_fetch_assoc($result)) {
                 pg_query("UPDATE " . $table_node . " SET address_full='" . geocode($row['lon'] . ',' . $row['lat']) . "' WHERE id=" . $row['id']);
                 //echo "UPDATE ".$table_node." SET address_full='".geocode($row['lon'].','.$row['lat'])."' WHERE id=".$row['id'];
             }
         }
         $sql = "SELECT * FROM " . $table_node . " WHERE is_new = true AND address_full IS NOT NULL AND address IS NULL ORDER BY address_full";
         $result = pg_query($sql);
         if (pg_num_rows($result)) {
             $select_node = '<select id="id">';
             $select_node .= '<option value="0">Выберите новый узел</option>';
             while ($row = pg_fetch_assoc($result)) {
                 $select_node .= '<option value="' . $row['id'] . '"';
                 if (@$location_id == $row['id']) {
                     $select_node .= " SELECTED";
                 }
                 $select_node .= '>' . $row['address_full'] . ' id: ' . $row['id'] . '</option>';
             }
Example #30
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['dirpre'] . '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);
         }
         $this->render('subletsearchstart', $this->dataSearchSetup());
         $this->render('subletsearchresults', array('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($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);
                 $this->render('subletsearchresults', array('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;
             }
         }
     }
     $this->error($err);
     $this->render('partials/subletsearchform', array_merge($data, array('search' => 'housing')));
 }