Get nearby locations using google places api in php/codeigniter - codeigniter

I have to fetch results of nearby locations within 2 km of my given latitude/longitude values. Have to do it using Google Places API. Details go here:
http://code.google.com/apis/maps/documentation/javascript/places.html
They have provided a sample code in javascript. But I need to have this in php. Can anyone give me any idea how may I achieve it? Or how may I use this same javascript code in my php controller class? [I am using code igniter framework]. I have been stuck on this issue for so many hours. It will be great if someone can provide a sample php code. Highly appreciate any assistance.
Here is the code of my controller class:
<?php
class Welcome extends CI_Controller {
public function index()
{
$config = "";
//$this->load->library('googlemaps');
$this->load->library('googlemaps');
$config['center'] = '37.4419, -122.1419';
$config['zoom'] = 'auto';
$config['places'] = TRUE;
$config['placesLocation'] = '37.4419, -122.1419';
$config['placesRadius'] = 200;
$this->googlemaps->initialize($config);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('map_view', $data);
}
}
?>
This is the error I encounter while I try to run the above code:
Fatal error: Using $this when not in object context in /Applications/XAMPP/xamppfiles/htdocs/ciplaces/application/controllers/mapcontroller.php on line 9
I am accessing my code using this url:
http://localhost/ciplaces/index.php/mapcontroller
Thanks

I've got a CodeIgniter library that has integration with the Google Maps and Places API. You can find information and download the library here:
http://biostall.com/codeigniter-google-maps-v3-api-library
A demo of the 'Places' integration can also be found below:
http://biostall.com/demos/google-maps-v3-api-codeigniter-library/places
Give me a shout if you have any questions or require any changes made to the library and I'll be happy to help out where I can.
Cheers

I have done something simular in PHP using the Lumb algorithm.
You should be able to get something from the code below (sits in my model, but you can put in anywhere).
public function search($start_latitude, $start_longitude, $radius, $radius_type, $offset, $limit)
{
$results = array();
$locations = array();
$sql = "SELECT `location_id`, `latitude`, `longitude` FROM `table`";
$query = $this->db->query($sql);
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$geo_data = $this->_bearing_distance_calc($start_latitude, $start_longitude, $row->latitude, $row->longitude, $radius_type);
$geo_data['radius_type'] = $radius_type;
if($geo_data['distance'] <= $radius)
{
// radial serach results
$locations[] = $row->location_id;
}
}
// return amount requested
$results['total'] = count($locations);
$results['locations'] = array_slice($locations, $offset, $limit);
return $results;
}
else
{
// no results
return FALSE;
}
}
/**
* Calculate Distance Between two points.
*
* This method is used to calculate the distance between to geographical points. <br />
* Used by the search method.
*
* #access private
*
* #param float $device_latitude
* #param float $device_longitude
* #param float $beach_latitude
* #param float $beach_longitude
* #param integer $radius_type
*
* #return array
*/
private function _bearing_distance_calc($start_latitude, $start_longitude, $building_latitude, $building_longitude, $radius_type)
{
// using Rhumb lines(or loxodrome)
// convert to rads for php trig functions
$start_latitude = deg2rad($start_latitude);
$start_longitude = deg2rad($start_longitude);
$building_latitude = deg2rad($building_latitude);
$building_longitude = deg2rad($building_longitude);
// testing variables
//$start_latitude = deg2rad(39.4422);
//$start_longitude = deg2rad(-122.0307);
//$building_latitude = deg2rad(49.4422);
//$building_longitude = deg2rad(-112.0307);
// calculate delta of lat and long
$delta_latitude = $building_latitude-$start_latitude;
$delta_longitude = $building_longitude-$start_longitude;
// earth radius
if ($radius_type == 'miles') // using miles
{
$earth_radius = 3959;
}
else // using kilometers
{
$earth_radius = 6371;
}
// now lets start mathing !!
// cast types
$dPhi = log(tan($building_latitude/2+M_PI/4)/tan($start_latitude/2+M_PI/4));
if ($dPhi != 0)
{
$q = $delta_latitude/$dPhi;
}
else
{
$q = cos($start_latitude);
}
//$q = (!is_nan($delta_latitude/$dPhi)) ? $delta_latitude/$dPhi : cos($start_latitude); // E-W line gives dPhi=0
// if dLon over 180° take shorter rhumb across 180° meridian:
if (abs($delta_longitude) > M_PI)
{
$delta_longitude = $delta_longitude>0 ? -(2*M_PI-$delta_longitude) : (2*M_PI+$delta_longitude);
}
$geo_data = array();
$geo_data['distance'] = sqrt($delta_latitude*$delta_latitude + $q*$q*$delta_longitude*$delta_longitude) * $earth_radius;
$bearing = rad2deg(atan2($delta_longitude, $dPhi));
if($bearing < 0)
{
$bearing = 360 + $bearing;
}
$geo_data['bearing'] = $bearing;
return $geo_data;
}

Related

Passing multiple values using

I want to pass multiple values in single column of database.
I have two tables (Schedule & Days). In form I select days when I select multiple days then I should add in db multiple. But it add only one day
public function store(Request $request)
{
$schedule = new menu;
$days = new day;
$sensor = new sensor;
$schedule->scheduleName = $request->name;
$schedule->start_time = $request->start_time;
$schedule->end_time = $request->end_time;
$schedule->timestamps = false;
$schedule->s_daytime = $request->s_daytime;
$schedule->e_daytime = $request->e_daytime;
$days->days = $request->days;
$days->timestamps = false;
$sensor->timestamps = false;
$sensor->sensor = $request->sensor;
$schedule->save();
$days->schedule_id = $schedule->id;
$days->save();
$sensor->schedule_id = $schedule->id;
$sensor->save();
return view('store');
}
What you can do is you can pass multiple days in an array and store the array in json format on your DB. here is the snippets.
$days_list = $request->days_list;
//for edit previous data
if(!empty($days->days_list)){
$arr = json_decode($days->days_list);
if(in_array($request->days, $arr)){
$data['success'] = false;
$data['message'] = 'This Day is already on your schedule
list.';
return $data;
}
array_push($arr, $days_list);
$days->days_list = json_encode($arr);
}
// for adding new data
else{
$days->days_list = json_encode(array($request->days_list));
}
$days->save();
```

why we use $this__("Some text") instead simple echo magento

I am working with magento and have a question in mind that why we use $this__("Some text") instead simple echo magento. can anyone ?
When you call
echo $this->__("some text");
You can start by looking at Mage_Core_Helper_Abstract
/**
* Translate
*
* #return string
*/
public function __()
{
$args = func_get_args();
$expr = new Mage_Core_Model_Translate_Expr(array_shift($args), $this->_getModuleName());
array_unshift($args, $expr);
return Mage::app()->getTranslator()->translate($args);
}
Next is Mage_Core_Model_App
/**
* Retrieve translate object
*
* #return Mage_Core_Model_Translate
*/
public function getTranslator()
{
if (!$this->_translator) {
$this->_translator = Mage::getSingleton('core/translate');
}
return $this->_translator;
}
Which is handed to Mage_Core_Model_Translate
/**
* Translate
*
* #param array $args
* #return string
*/
public function translate($args)
{
$text = array_shift($args);
if (is_string($text) && ''==$text
|| is_null($text)
|| is_bool($text) && false===$text
|| is_object($text) && ''==$text->getText()) {
return '';
}
if ($text instanceof Mage_Core_Model_Translate_Expr) {
$code = $text->getCode(self::SCOPE_SEPARATOR);
$module = $text->getModule();
$text = $text->getText();
$translated = $this->_getTranslatedString($text, $code);
}
else {
if (!empty($_REQUEST['theme'])) {
$module = 'frontend/default/'.$_REQUEST['theme'];
} else {
$module = 'frontend/default/default';
}
$code = $module.self::SCOPE_SEPARATOR.$text;
$translated = $this->_getTranslatedString($text, $code);
}
//array_unshift($args, $translated);
//$result = #call_user_func_array('sprintf', $args);
$result = #vsprintf($translated, $args);
if ($result === false) {
$result = $translated;
}
if ($this->_translateInline && $this->getTranslateInline()) {
if (strpos($result, '{{{')===false || strpos($result, '}}}')===false || strpos($result, '}}{{')===false) {
$result = '{{{'.$result.'}}{{'.$translated.'}}{{'.$text.'}}{{'.$module.'}}}';
}
}
return $result;
}
which returns the resulting text. This is a quick walkthrough of how everything would be handled, you should view the classes themselves to get a more in-depth understanding.
In simple when you call echo $this->__('some text') it look up same
text in CSV file which is located in
app>locale
or
app>design>frontend>YOUR_PACKAGE>YOUR_THEME_NAME>locale>translate.csv
file if the same word exist then it translate a word
means it is very useful in multi-language website
$this->__("Some text")
Used for translation purpose

Computation Inside Model Codeigniter

Good day everyone. I just wanna know if it's possible to do computations inside a model, disregarding the database? If it is, how will I do it? If not, can someone explain? Thanks.
Example:
var $monthly = '';
var $annually = '';
var $quarterly = '';
var $semiannual = '';
function computation($price, $quantity){
$this->monthly = $price * $quantity;
$this->annually = $price * $quantity * 12;
$this->quarterly = $price * $quantity * 3;
$this->semiannual = $price * $quantity * 6;
}
Models are just regular classes - you write methods to do your calculation and then call them from the controllers as needed. See example below:
class Circle extends CI_Model {
public function area($rad) {
return 3.14 * $rad * $rad;
}
}
class CircleCtrl extends CI_Controller {
public function calc_area() {
$this->load->model('Circle');
$area = $this->circle->area(10);
}
}

AS3 random algorithm

I need a suggestion. I want to have a function that returns random numbers from let say 1 to 100, with condition to not repeat the chosen number. It is something like chess table that will be filled with something random and not one thing over another thing... If someone can tell a suggestion I'll be very happy. Thanks.
Create an Array of 100 numbers (1..100), then 'sort' the Array by 'random'. You can then pull out the numbers one at a time working your way through the array.
I haven't tested the code below but I had these snippets available that you could piece together to achieve the intended result.
public static function randomNumber(min:Number, max:Number):Number{
var rnd:Number = Math.floor((Math.random()*((max+1)-min))+min);
return rnd;
}
public static function randomize(arr:Array):Array{
var len:Number = arr.length;
var rnd:Number;
var tmp:Object;
for(var i:Number=0;i<len;i++){
rnd = randomNumber(0,(len-1));
tmp = arr[i];
arr[i] = arr[rnd];
arr[rnd] = tmp;
}
return arr;
}
var setOfNumbers:Array = new Array();
for(var i:int=0;i<100;i++){
setOfNumbers[i] = (i+1);
}
var shuffledSetOfNumbers:Array = randomize(setOfNumbers);
Notes:
For the purists this "randomizing" isn't "truly" random (if you're writing a Card shuffler for a Vegas gambling machine you'll want to use something different - case in point!)
My randomNumber and randomize functions above are static as I've typically included them that way in the apps I've needed them but you don't have to use it this way
My original lib used Number vs int or uint for some of the variables for more options when used but feel free to clean that up
also like that...
package
{
import flash.display.Sprite;
import flash.events.Event;
/**
* ...
* #author Vadym Gordiienko
*/
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
var startArray:Array = generateNumberArray(100);
var randomArray:Array = randomArray(startArray);
trace("startArray = " + startArray);
trace("randomArray = " + randomArray);
}
/**
* generate Array of numbers by length
* #param length
* #return Array of numbers
*/
public static function generateNumberArray(length:int):Array
{
var numberArray:Array = [];
for (var i:int = 0; i < length; i++)
{
numberArray[i] = i+1;
}
return numberArray;
}
/**
* generate randomly mixed array by input array
* #param inputArray - simple not mixed array
* #return Array - mixed array
*/
public static function randomArray(inputArray:Array):Array
{
var randomArray:Array = [];
var tempArray:Array = [];
for (var i:int = 0; i < inputArray.length; i++)
{
tempArray.push(inputArray[i]);
}
while (tempArray.length)
{
var randomNumber:int = Math.round(Math.random() * (tempArray.length - 1));// get random number of left array
randomArray.push( tempArray[randomNumber] );
tempArray.splice(randomNumber, 1); // remove randomed element from temporary aarray
}
tempArray = null;
delete [tempArray];
return randomArray;
}
}
}

Using codeigniter image lib - converting images

Using codeigniter image lib is it possible to just change an image type? Trying to convert from * -> PNG.
The below doesn't work!
$config = array();
$config['source_image']='uploads/'.$name.'.'.$m[1];
$config['new_image']='uploads/'.$name.'.'.$png;
$objImage = new CI_Image_lib($config);
Many thanks! All help very appreciated!
Currently just using, but would like to use image lib and support all image types.
$sourceImage = imagecreatefromjpeg('uploads/'.$name.'.'.$m[1]);
imagepng($sourceImage, 'uploads/'.$name.'.png');
After reading many different solutions, I settled to give up on CodeIgniter's library and instead use a very simple class given here
(was originally posted on http://www.white-hat-web-design.co.uk/blog/resizing-images-with-php/ but was removed in the meantime).
Pasting it here for posterity:
<?php
/* * File: SimpleImage.php * Author: Simon Jarvis * Copyright: 2006 Simon Jarvis * Date: 08/11/06 * Link: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: * http://www.gnu.org/licenses/gpl.html * */
class SimpleImage
{
var $image;
var $image_type;
function load($filename)
{
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if ($this->image_type == IMAGETYPE_JPEG) {
$this->image = imagecreatefromjpeg($filename);
} elseif ($this->image_type == IMAGETYPE_GIF) {
$this->image = imagecreatefromgif($filename);
} elseif ($this->image_type == IMAGETYPE_PNG) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type = IMAGETYPE_JPEG, $compression = 75, $permissions = null)
{
if ($image_type == IMAGETYPE_JPEG) {
imagejpeg($this->image, $filename, $compression);
} elseif ($image_type == IMAGETYPE_GIF) {
imagegif($this->image, $filename);
} elseif ($image_type == IMAGETYPE_PNG) {
imagepng($this->image, $filename);
}
if ($permissions != null) {
chmod($filename, $permissions);
}
}
function output($image_type = IMAGETYPE_JPEG)
{
if ($image_type == IMAGETYPE_JPEG) {
imagejpeg($this->image);
} elseif ($image_type == IMAGETYPE_GIF) {
imagegif($this->image);
} elseif ($image_type == IMAGETYPE_PNG) {
imagepng($this->image);
}
}
function getWidth()
{
return imagesx($this->image);
}
function getHeight()
{
return imagesy($this->image);
}
function resizeToHeight($height)
{
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width, $height);
}
function resizeToWidth($width)
{
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width, $height);
}
function scale($scale)
{
$width = $this->getWidth() * $scale / 100;
$height = $this->getheight() * $scale / 100;
$this->resize($width, $height);
}
function resize($width, $height)
{
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
?>
For a CI based extension, look here: http://www.robertmullaney.com/2010/09/18/codeigniter-image_lib-convert-jpg-gif-png/
I think that you have to use ImageMagick
$config['image_library'] = 'ImageMagick';
$config['library_path']='/usr/bin';
$config['source_image']='uploads/'.$name.'.'.$m[1];
$config['new_image']='uploads/'.$name.'.'.$png;
$objImage = new CI_Image_lib($config);

Resources