Posts tagged PHP

Yii Framework

EScriptBoost Extension for Yii

3

Introduction

Yii FrameworkProbably a lot of you would wonder why, having so many good extensions related to minifying/compressing/packing your javascript code and your css files at the Yii Extensions Repository, here comes this guy offering us another solution.

I did check out all the extension in our repository, just to name some of them:

All of them are great, but none were filling the requirements we had. I did not have any issue compressing all our files as our team, will use the YUI compressor jar file to create our compressed javascript versions and then use the wonderful mapping features of CClientScript. The issue was with the assets of external, or own developed, extensions and the javascript code that, even Yii own widgets, were writing to the POS_BEGIN, POS_END, POS_HEAD, POS_LOAD, POS_READY positions. Thats exactly what this library is doing: allowing Yii coders to minify those scripts.

I have created a GitHub repository for those willing to contribute on any of the extensions I created. Please, check the link at the bottom of this wiki.

Library

The library comes with three flavors:

  • EScriptBoost Component
  • EClientScriptBoost Extension
  • AssetManagerBoost Extension

EScriptBoost Component

This is a very easy to use component to compress your Javascript or CSS code at your will. The minifiers used are:

Usage

// this is a very simple example :)
// we use cache as we do not want to
// compress/minify all the time our
// script
$js = Yii::app()->cache->get('scriptID');
if(!$js)
{
     $cacheDuration = 30;
     $js = <<<EOD
     // my long and uncompressed code here
EOD;
     // $js = EScriptBoost::packJs($js);
     // $js = EScriptBoost::minifyJs($js, EScriptBoost::JS_MIN_PLUS);
     $js = EScriptBoost::minifyJs($js, EScriptBoost::JS_MIN);
     // see Cache guide for more options | dependencies
     Yii::app()->cache->set('scriptID', $cacheDuration);
}
Yii::app()->clientScript->registerScript('scriptID', $js);

That was troublesome right? No worries, if you don’t really care about using JS_MIN, or JS_MIN_PLUS, you can use its helper function registerScript, it will handle all of the above automatically:

$js = <<<EOD
    // my long and uncompressed code here
EOD;
EScriptBoost::registerScript('scriptID', $js);

EClientScriptBoost Extension

EScriptBoost was good for the javascript code written by me but what about the ones written by Yii widgets?EClientScriptBoost was developed to solve that:

Usage

On your main.php config file:

'import' => array(
// ... other configuration settings on main.php
// ... importing the folder where scriptboost is
    'application.extensions.scriptboost.*',
// ... more configuration settings
    ),
// ... other configuration settings on main.php
'components' => array(
     'clientScript' => array(
// ... assuming you have previously imported the folder
//     where EClientScriptBoost is
         'class'=>'EClientScriptBoost',
         'cacheDuration'=>30,
// ... more configuration settings

Done! now, every time you or other component on your application will be minified and cached as you specify on your cache settings. Easy right?

EAssetManagerBoost Extension

But there was one more challenge to solve. Some extensions, widgets, etc, do publish a whole bunch of files in our assets that are not minified. This is where EAssetManagerBoost comes handy.

This extension does only minify javascript/css files, and also makes sure that the, about to be compressed, file do not match any of its $minifiedExtensionFlags so minified/compressed files are not processed at all.

Usage

Make sure you have deleted your previous assets folder contents.

'import' => array(
// ... other configuration settings on main.php
// ... importing the folder where scriptboost is
    'application.extensions.scriptboost.*',
// ... more configuration settings
    ),
// ... other configuration settings on main.php
'components' => array(
    'assetManager' => array(
// ... assuming you have previously imported the folder
      'class' => 'EAssetManagerBoost',
      'minifiedExtensionFlags'=>array('min.js','minified.js','packed.js')
        ),
// ... more configuration settings

Important Note There is a small drawback to use EAssetManagerBoost and is that, the first time your application is requested, it will take a bit of time as it will go throughout all your asset files to be published and minify them.

Resources



Tweet this!Tweet this!
Yii Framework

Avoiding duplicate script download when using CActiveForm on Ajax calls

0

Yii Framework

Introduction

Sometimes the active form we wish to use to edit/add a new element on our database is too small and we believe that is much better to use an AJAX’ed dialog/slide form rather than reloading the page to just display one or two fields.

The only thing required is simple, we just need to create a view that will be partially rendered by a call to a controller (using renderPartial) and make sure that we process output -setting to true the parameter on the function. Everything will work as expected but…

The issue

If we open firebug (firefox), or developer tools (chrome), or whatever the tool you use in order to see the XmlHttpRequest object calls and resources downloaded, you will see that every time we do call the controller to display the active form, different Yii “core JS” files keeps being downloaded to the client. The JS files downloaded depends on your code but there are at least jquery.js, jquery-ui.js and jquery.yiiactiveform.js.

The solution

The solution is a bit tricky but simple. We need to pre-render the jquery.yiiactiveform.js on the view where we are going to place the AJAX functionality (the button that opens the modal dialog or slides/shows a layer with AJAX’ed form contents). For example, on index.php view file:

cs()->registerCoreScript('yiiactiveform');

Now, I assume that you have created your function to display the AJAX’ed active form and its contents are returned by a call to a controller’s action that will partially render a view. This is what we have to do in our action:

// Just before rendering the view that
// has our activeform
Yii::app()->clientScript->corePackages = array();

It is very important that we set corePackages to array() instead of null, as setting it to null will make CClientScript to reload the packages.php file (located in framework/web/js/) and we won’t stop the duplication of the script.

And that’s it, everything is working as it should.



Tweet this!Tweet this!
Offertutti

Offertutti

1

Coupon aggregator site I worked for. Duties I had for the company:

  • Consulting
  • CSS redesign
  • XML feeds development -Automation with PHP
  • RSS development and automatic marketing integration with Twitter and Facebook

 

Even though was not a Yii-job, I am more than happy to promote www.offertutti.com here as one of the most pleasant jobs I have ever had in my, already long -gosh how time pass, coding career.

The job was quite challenging, as any site developed by companies from certain countries, but managed to fulfill most of their expectations. Even though I am currently in the middle of a dream project, it continues to be a pleasure to help them out every now and then.

New design is coming…

Tweet this!Tweet this!
Yii Framework

Custom Autocomplete Display and Value Submission

4

Yii Framework

Introduction

How many of us has wondered how to create an autocomplete that will display the names of a related models but do require the id of that selected name to be submitted for model creation/update?

I was looking around wiki and found that was no approach as the one I did so I guessed this is worth to write.

Requirements

For our example, I want to be able to:

  • Have an autocomplete field in our form
  • Once user selects an item in the dropdown list and fill a hidden box with the id of the selected item for submission

Making the right choice

To setup the autocomplete was a very straight forward operation, but I couldn’t figure out how to get values from a custom JSON response and then fill the correspondent hidden fields.

CAutoComplete does has a way to do it, but I wanted to use CJuiAutoComplete to get all the cool features of its JQuery Ui and by looking at his code there was no method chain, something that is required to work with custom JSON responses as we need to override some methods.

My Solution

After doing some research I decided to:

  1. extend from CJuiAutoComplete
  2. include the required property for method chain and modify its ‘run’ function
  3. then initialize the newly created property with the javascript functions that handle my custom JSON

Extending from CJuiAutoComplete and make required modifications

Very simple, we are going to add a methodChain property and modify the run function to include it (zii is not a major concern to Yii, but main developers should think about this minor change).

class myAutoComplete extends CJuiAutoComplete
{
    /**
     * @var string the chain of method calls that would be appended at the end of the autocomplete constructor.
     * For example, ".result(function(...){})" would cause the specified js function to execute
     * when the user selects an option.
     */
    public $methodChain;
    /**
     * Run this widget.
     * This method registers necessary javascript and renders the needed HTML code.
     */
    public function run()
    {
        list($name,$id)=$this->resolveNameID();
        if(isset($this->htmlOptions['id']))
            $id=$this->htmlOptions['id'];
        else
            $this->htmlOptions['id']=$id;
        if(isset($this->htmlOptions['name']))
            $name=$this->htmlOptions['name'];
        if($this->hasModel())
            echo CHtml::activeTextField($this->model,$this->attribute,$this->htmlOptions);
        else
            echo CHtml::textField($name,$this->value,$this->htmlOptions);
        if($this->sourceUrl!==null)
            $this->options['source']=CHtml::normalizeUrl($this->sourceUrl);
        else
            $this->options['source']=$this->source;
        $options=CJavaScript::encode($this->options);
        $js = "jQuery('#{$id}').autocomplete($options){$this->methodChain};";
        $cs = Yii::app()->getClientScript();
        $cs->registerScript(__CLASS__.'#'.$id, $js);
    }
}

Using our widget

Now that we have our beautiful widget that handles method chain in our Autocomplete, let’s assume a couple of things:

  • We saved our class onto a folder in our application -ie protected/extensions
  • We have a hidden INPUT HTML element with model’s attribute_id
  • We have created an action on our testController named autocomplete that returns a JSON object on the following format:
// This function will echo a JSON object
// on this format:
// [{id:id, name: 'name'}]
public function actionAutocomplete(){
      $res = array();
      $term = Yii::app()->getRequest()->getParam('term', false);
      if ($term)
      {
         // test table is for the sake of this example
         $sql = 'SELECT id, name FROM {{test}} where LCASE(name) LIKE :name';
         $cmd = Yii::app()->db->createCommand($sql);
         $cmd->bindValue(":name","%".strtolower($term)."%", PDO::PARAM_STR);
         $res = $cmd->queryAll();
      }
      echo CJSON::encode($res);
      Yii::app()->end();
}

We have everything, let’s use our widget in our view:

// REMEMBER, we have a hidden
// input HTML element with model's attribute_id
<?php echo $form->hiddenField($model, 'attribute_id'); ?>
<?php
// ext is a shortcut for application.extensions
$this->widget('ext.myAutoComplete', array(
    'name' => 'test_autocomplete',
    'source' => $this->createUrl('test/autocomplete'),
// attribute_value is a custom property that returns the
// name of our related object -ie return $model->related_model->name
    'value' => $model->isNewRecord ? '': $model->attribute_value,
    'options' => array(
        'minChars'=>3,
        'autoFill'=>false,
        'focus'=> 'js:function( event, ui ) {
            $( "#test_autocomplete" ).val( ui.item.name );
            return false;
        }',
        'select'=>'js:function( event, ui ) {
            $("#'.CHtml::activeId($model,'attribute_id').'")
            .val(ui.item.id);
            return false;
        }'
     ),
    'htmlOptions'=>array('class'=>'input-1', 'autocomplete'=>'off'),
    'methodChain'=>'.data( "autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
            .data( "item.autocomplete", item )
            .append( "<a>" + item.name +  "</a>" )
            .appendTo( ul );
    };'
));
?>

Done! Just make sure that when you do submit your form, you get the value from the hidden field instead of the autocomplete element :)

Final Notes

I do not know if there are other ways of doing the same thing (apart from pure Javascript) to have the same results. If you know, with CJuiAutoComplete widget, let us know here.

Hope you find this useful.

Cheers

Tweet this!Tweet this!
Yii Framework

Implementing a User Level Access System

2

Yii Framework

I would like to explain this time how easy is to implement a level access system with Yii framework.

Please note that this article is a simple example and good security should be taken into account when we play with authentication systems.

Step 1: Setting Up

a. Include a field on your user’s table named, yep you guessed, level
b. Create an object ‘LevelLookUp’ that will tell us who is who on this system

class LevelLookUp{
      const MEMBER = 0;
      const ADMIN  = 2;
      // For CGridView, CListView Purposes
      public static function getLabel( $level ){
          if($level == self::MEMBER)
             return 'Member';
          if($level == self::ADMIN)
             return 'Administrator';
          return false;
      }
      // for dropdown lists purposes
      public static function getLevelList(){
          return array(
                 self::MEMBER=>'Member',
                 self::ADMIN=>'Administrator');
	}
}

c.Modifying UserIdentity so we can store the user Model id on authentication, as CWebUser’s default id is set to the user Model’s username:

class UserIdentity extends CUserIdentity
{
	private $_id;
	/**
	 * Authenticates a user.
	 * @return boolean whether authentication succeeds.
	 */
	public function authenticate()
	{
		$username = strtolower($this->username);
                // from database... change to suite your authentication criteria
		$user = User::model()->find('LOWER(username)=?', array($username));
		if($user===null)
			$this->errorCode=self::ERROR_USERNAME_INVALID;
		else if(!$user->validatePassword($this->password))
			$this->errorCode = self::ERROR_PASSWORD_INVALID;
		else{
			$this->_id = $user->id;
			$this->username = $user->username;
			$this->errorCode = self::ERROR_NONE;
		}
		return $this->errorCode == self::ERROR_NONE;
	}
	public function getId()
	{
		return $this->_id;
	}
}

d. Modify CWebUser’s application in order to hold the ‘level’ property. We are going to call it EWebUser and will extend from CWebUser, and save it on protected/components to be loaded automatically by our default’s configuration file.

class EWebUser extends CWebUser{
    protected $_model;
    function isAdmin(){
        $user = $this->loadUser();
        if ($user)
           return $user->level==LevelLookUp::ADMIN;
        return false;
    }
    // Load user model.
    protected function loadUser()
    {
        if ( $this->_model === null ) {
                $this->_model = User::model()->findByPk( $this->id );
        }
        return $this->_model;
    }
}

e. Modify our main.php config file (this file is in protected/config folder)

// go to the 'user' section
// application components
	'components'=>array(
		'user'=>array(
                        // There you go, use our 'extended' version
			'class'=>'application.components.EWebUser',
			// enable cookie-based authentication
			'allowAutoLogin'=>true,
		),

Step 2: Putting everything together

Now that we know, who logged, we could easily find out if it is just a member or an administrator and render the elements by checking the level as simple as this:

// for normal content
if(Yii::app()->user->isAdmin())
     echo 'Is administrator';
// for CMenus
$this->widget('zii.widgets.CMenu',array(
    array('label'=>'Categories',
           'url'=>array('/category/index'),
           'visible'=>(Yii::app()->user->isAdmin()),
     //... More stuff
     //...
// for data chuncks
<?php if(Yii::app()->user->isAdmin():?>
<b>My HTML</b>
<?php endif;?>
// for access rules
return array(
      array('allow',
        'actions'=>array('create','delete','update'),
        'expression'=>'$user->isAdmin()'
      ),
// ...



Tweet this!Tweet this!
Overlays

EGMaps 2.0 News: Layers, Polygons and Rectangles

3

Overlays

The new version of EGMaps 2.0 is about to see the light. In the meantime new features have been included and are available through the SVN source at google’s code. Even though we are planning many more features, the following  are the list of the newly inserted features of the Yii extension till date:

  • Polygons (committer Matthias Kay)
  • Rectangles
  • Circles
  • Bicycling Layer
  • Traffic Layer
  • Panoramio Layer

Polygon Example

Yii::import('ext.egmap.*');
$gMap = new EGMap();
$gMap->setWidth(588);
$gMap->setHeight(345);
$gMap->zoom = 3;
$gMap->mapTypeControlOptions = array(
 'position'=> EGMapControlPosition::RIGHT_TOP,
 'style'=>EGMap::MAPTYPECONTROL_STYLE_DROPDOWN_MENU
);
$gMap->setCenter(34.04924594193164, -118.24104309082031);
$coords = array();
$coords[] = new EGMapCoord(25.774252, -80.190262);
$coords[] = new EGMapCoord(18.466465, -66.118292);
$coords[] = new EGMapCoord(32.321384, -64.75737);
$coords[] = new EGMapCoord(25.774252, -80.190262);
$polygon = new EGMapPolygon($coords);
$gMap->addPolygon($polygon);
$gMap->centerOnPolygons();
$gMap->zoomOnPolygons(0.1);
$gMap->renderMap(array(),'en','ES');

Circle and Rectangle Example

Yii::import('ext.egmap.*');
$gMap = new EGMap();
$gMap->setWidth(588);
$gMap->setHeight(345);
$gMap->zoom = 3;
$gMap->mapTypeControlOptions = array(
 'position'=> EGMapControlPosition::RIGHT_TOP,
 'style'=>EGMap::MAPTYPECONTROL_STYLE_DROPDOWN_MENU
);
$gMap->setCenter(34.04924594193164, -118.24104309082031);
$circle = new EGMapCircle(new EGMapCoord(34.04924594193164, -118.24104309082031));
$circle->radius = 300000;
// we can even attach info windows to the overlay!
$circle->addHtmlInfoWindow(new EGMapInfoWindow('Hey! I am a circlel!'));
$gMap->addCircle($circle);
$bounds = new EGMapBounds(new EGMapCoord(25.774252, -80.190262),new EGMapCoord(32.321384, -64.75737) );
$rec = new EGMapRectangle($bounds);
$rec->addHtmlInfoWindow(new EGMapInfoWindow('Hey! I am a rectangle!'));
$gMap->addRectangle($rec);
$gMap->renderMap(array(),'en','ES');

Panoramio Layer Example

$gMap = new EGMap();
$gMap->setWidth(588);
$gMap->setHeight(345);
$gMap->zoom = 3;
$gMap->mapTypeControlOptions = array(
 'position'=> EGMapControlPosition::RIGHT_TOP,
 'style'=>EGMap::MAPTYPECONTROL_STYLE_DROPDOWN_MENU
);
$gMap->setCenter(34.04924594193164, -118.24104309082031);
// we can also use the same way TRAFFIC and BICYCLING layers
$gMap->setLayer(new EGMapLayer(EGMapLayer::PANORAMIO));
$gMap->renderMap(array(),'en','ES');

The extension has also been updated its reverse geocoding (committer Say_Ten).

Please, remember that in order to work with the above examples you require to download the svn source from the google code, not the zipped package on Yii’s repository. The extension will be updated when we reach the following goals:

  • Elevation Paths
  • Polylines
  • Ground Overlays
  • Animations
  • Map Styling

 

 

Tweet this!Tweet this!
Yii Framework

How to use a Widget as an Action Provider

2

Yii FrameworkAt the Yii forum there a good question about this matter, and most of us where curious on how this feature actually works.

As usual in the API docs it was clearly written but sometimes the text just sounds like a test for a car driver license. Nevertheless, after creating a test scenario, I found the solution and this is article is to show you exactly how this is done.

Why would I need an action provider?

Well, imagine you have lots of general actions that could be shared among controllers. It is true that by setting the actions() function to point to the external CAction classes files but just imagine that those functions are encapsulated by just a class (a widget in this case) and you just need a line of code to import all of its actions.

First Step: Create your Action

For the sake of the article we creating an action named getData that supposed to be shared among the whole project and saved with the name getData.php on our protected/components/actions folder.

<?php
class getData extends CAction{
	public function run(){
		echo 'HELLO WORLD';
	}
}

Second Step: configure the Widget

To transform a Widget into an action provider is quite easy (once you know of course). The only thing we need to do is to set the static method actions(). As you will see on the following code, we name the action as GetData and that is the action that will be called in our route. We are going to save the following widget in our protected/components/ folder with the name testProvider.php.

class testProvider extends CWidget{
	public static function actions(){
		return array(
                   // naming the action and pointing to the location
                   // where the external action class is
		   'GetData'=>'application.components.actions.getData',
		);
	}
}

Step 3: Configure our Controller

Finally we set our controller’s actions() function to point to our actions provider.

// This function is in this example
// on SiteController
public function actions()
{
        return array(
        // test. is the prefix we are going to use
        // for all action within the actionProvider class
        // we point to the location where the provider
        // is
	'test.'=>'application.components.testProvider',
	);
}

Now we can call the action as controllerID/actionPrefix.actionID

index.php?site/test.GetData


Agile Web Application Development with Yii 1.1 and PHP5



Tweet this!Tweet this!
Yii Framework

Yii News: Query Caching

5

Yii FrameworkStarting from version 1.1.7 Yii Framework will include a really great feature: query caching. This new feature is built on top of data caching, query caching stores the result of a DB query in cache and may thus save the DB query execution time if the same query is requested in future, as the result can be directly served from the cache -After this, I truly would like to see some proper benchmarks versus other frameworks out there on query requests.

Using Query Caching with DAO

We need to use CDbConnection::cache() method in order to perform DB queries. The following example specifies that the query results should remain valid in cache for 1000 seconds. If we execute the same lines of code within the next 100 seconds one more time, the query results will be returned from cache without executing the SQL statement again.

$sql = 'SELECT * FROM tbl_post LIMIT 20';
$rows = Yii::app()->db->cache(1000)->createCommand($sql)->queryAll();

We can also specify a cache dependency for the cached query result so if there is any changes to the table, then we can invalidate the query results. In the next code, we create a dependency which checks the maximum `update_time` of all records in a table. If the value has any change, it means the table data is changed and we should invalidate the query cache.

$sql = 'SELECT * FROM tbl_post LIMIT 20';
$dependency = new CDbCacheDependency('SELECT MAX(update_time) FROM tbl_post');
$rows = Yii::app()->db->cache(1000, $dependency)->createCommand($sql)->queryAll();

Using Query Caching with CActiveRecord

This new feature can also be used with CActiveRecord

$posts = Post::model()->cache(1000)->findAll();
// query caching can also be used with relations
$posts = Post::model()->cache(1000)->with('author')->findAll();

If you wish to have a look at this cool feature, go and grab the SVN repository on google: http://code.google.com/p/yii/source/checkout



Tweet this!Tweet this!
Reverse-geolocator-EGMap-Yii

A Reverse Geolocator Tool with EGMap 2.0 Extension

1

I have been requested to create an article about a reverse geolocator tool, that is a tool to find out the latitude and longitude of a location, to include on our CMS, and here it is.

Styling, Javascript and HTML

First of all, we are going to write the HTML that will work with this example, it won’t styled as the example picture displayed, which is the tool I created for a project I am working now, but don’t you worry as this article will provide you with the scripts and routines to create your own.

Write the following style on the HEAD section of your HTML page:

<style>
  div#map {
    position: relative;
  }
  div#crosshair {
    position: absolute;
/*
     the top will be half of the width of the map
     less 50% of its size more or less
     to center the image correctly on the map
*/
    top: 192px;
    height: 19px;
    width: 19px;
    left: 50%;
    margin-left: -8px;
    display: block;
/* we are going to borrow a crosshair gif from google */
    background: url(http://gmaps-samples-v3.googlecode.com/svn/trunk/geocoder/crosshair.gif);
    background-position: center center;
    background-repeat: no-repeat;
}
</style>

Now, some Javascript functions that will allow us to get the information from the map

<script type="text/javascript">
  //
  // function to get the latitude and longitude
  // and place them on the test fields
  function setLatLngToClass(){
	if(document.getElementById('test_latitude'))
	 	document.getElementById('test_latitude').value = map.getCenter().lat();
	if(document.getElementById('test_longitude'))
		document.getElementById('test_longitude').value = map.getCenter().lng();
  }
  //
  // function to get Centered Latitude and Longitude points
  function getCenterLatLngText() {
    return '(' + map.getCenter().lat() +', '+ map.getCenter().lng() +')';
  }
  //
  // function to call when the center of the map
  // has changed. Center information will be
  // collected and displayed on the document
  // elements
  function centerChanged() {
    centerChangedLast = new Date();
    var latlng = getCenterLatLngText();
    document.getElementById('latlng').innerHTML = latlng;
    document.getElementById('formatedAddress').innerHTML = '';
    currentReverseGeocodeResponse = null;
  }
  //
  // Collects reverse center location
  function reverseGeocode() {
    reverseGeocodedLast = new Date();
    geocoder.geocode({latLng:map.getCenter()},reverseGeocodeResult);
  }
  //
  // Displays collected reverse geocoded results
  // and displays them on document elements
  function reverseGeocodeResult(results, status) {
    currentReverseGeocodeResponse = results;
    if(status == 'OK') {
      if(results.length == 0) {
        document.getElementById('formatedAddress').innerHTML = 'None';
      } else {
        document.getElementById('formatedAddress').innerHTML = results[0].formatted_address;
      }
    } else {
      document.getElementById('formatedAddress').innerHTML = 'Error';
    }
  }
  //
  // geocodes the address inserted
  function geocode() {
    var address = document.getElementById("address").value;
    geocoder.geocode({
      'address': address,
      'partialmatch': true}, geocodeResult);
  }
  function geocodeResult(results, status) {
    if (status == 'OK' && results.length > 0) {
      map.fitBounds(results[0].geometry.viewport);
    } else {
      alert("Geocode was not successful for the following reason: " + status);
    }
  }
 //
 // adds marker to the center of the map
  function addMarkerAtCenter() {
    var marker = new google.maps.Marker({
        position: map.getCenter(),
        map: map
    });
    var text = 'Lat/Lng: ' + getCenterLatLngText();
    if(currentReverseGeocodeResponse) {
      var addr = '';
      if(currentReverseGeocodeResponse.size == 0) {
        addr = 'None';
      } else {
        addr = currentReverseGeocodeResponse[0].formatted_address;
      }
      text = text + '<br>' + 'address: <br>' + addr;
    }
    var infowindow = new google.maps.InfoWindow({ content: text });
    google.maps.event.addListener(marker, 'click', function() {
      infowindow.open(map,marker);
    });
  }
</script>

Our HTML on this example will be the following one:

<body style="background:white">
<div class="form">
Find by address:
 <input type="text" id="address" style="width:300px"/>
 <button type="button" class="small"onclick="geocode()">Go to Address</button>
  <ul>
     <li>Lat/Lng:&nbsp;<span id="latlng"></span></li>
     <li>Address:&nbsp;<span id="formatedAddress"></span></li>
     <li>Zoom Level:&nbsp;<span id="zoom_level"><?php echo $zoom;?></span></li>
 </ul>
</div>
<div id="map">
    <div id="map_canvas" style="width:100%; height:400px"></div>
    <div id="crosshair"></div>
</div>
<div style="overflow:hidden;width:100%;text-align:right">
<button type="button" class="small" onclick="setLatLngToClass()">Set Latitude & Longitude</button>
<button type="button" class="small" onclick="addMarkerAtCenter()">Add Marker at Center</button>
</div>
<hr>
Latitude: <input id="test_latitude" value=""/> Longitude: <input id="test_longitude" value=""/>
</hr>
</body>

Using EGMap 2.0 Extension

Finally, we are going to use EGMap 2.0 extension to automate the rest of the tasks to render our map.

Yii::import('ext.gmaps.*');
// center the map
// wherever you want
$latitude = 39.72098197183251;
$longitude = 2.9115524999999964;
$zoom = 8;
$gMap = new EGMap();
$gMap->setJsName('map');
$gMap->width = '100%';
$gMap->height = '400';
$gMap->setCenter($latitude, $longitude);
$gMap->zoom = 8;
$gMap->addGlobalVariable('geocoder');
$gMap->addGlobalVariable('centerChangedLast');
$gMap->addGlobalVariable('reverseGeocodedLast');
$gMap->addGlobalVariable('currentReversGeocodeResponse');
$gMap->addEvent(
     new EGMapEvent(
             'zoom_changed',
             'document.getElementById("zoom_level").innerHTML = map.getZoom();'));
$gMap->addEvent(new EGMapEvent('center_changed','centerChanged',false));
$gEvent = new EGMapEvent('dblclick','map.setZoom(map.getZoom() +1)');
$gMap->appendMapTo('#map_canvas');
$gMap->renderMap(array(
    'geocoder = new google.maps.Geocoder();',
    $gEvent->getDomEventJs('crosshair'),
    'reverseGeocodedLast= new Date();',
    'centerChagedLast = new Date();',
    'setInterval(function(){
        if((new Date()).getSeconds() - centerChangedLast.getSeconds() > 1) {
        if(reverseGeocodedLast.getTime() < centerChangedLast.getTime())
          reverseGeocode();
      }
    },1000);',
    'centerChanged();'
));

Important

If you are going to run this example, please be aware that in order to display it properly in a controller, all of the above have to be the content of a layout, otherwise, if you are using renderPartial (that you can), make sure you force to true the parameter ‘processOutput’ of the mentioned function (ie $this->renderPartial(‘view’,null,false,true) )



Tweet this!Tweet this!
EGMap Example 1

EGMap Google Maps Extension for Yii

10

Yii Framework

Introduction

I had to develop a Google maps extension for my current personal project and I did some research in order not to re-invent the wheel.

The best of them all was a Symphony plugin developed by Fabrice Bernhard. I didn’t want to create a wrapper so I decided to modify its code -in some cases rewriting the whole class, in order to create a full Extension built with Yii.

The features of this extension are very large to explain, therefore I will concentrate my next posts to fully explain by example the wonders of this extension.

Requirements

Developed with latest stable version of Yii (1.5)

Usage

Unzip its contents and place the gmaps folder into your protected/extensions folder.

A Reallly Easy Example

Displaying a Marker with an Info window.

Note: This example was written in a view file.

    // import the library
    Yii::import('ext.gmaps.*');
    $gMap = new EGMap();
    $gMap->setZoom(13);
    $gMap->setCenter(39.721089311812094, 2.91165944519042);
    // Create GMapInfoWindow
    $info_window = new EGMapInfoWindow('<div>I was living here as a kid!</div>');
    // Create marker
    $marker = new EGMapMarker(39.721089311812094, 2.91165944519042, array('title' => '"My Town"'));
    $marker->addHtmlInfoWindow($info_window);
    $gMap->addMarker($marker);
    $gMap->renderMap();

Result

 

Resources

Download the Extension
Bug Reports & Positive Feedback



Tweet this!Tweet this!
Go to Top