Posts tagged How To

Yii Framework

Yii Learning Guide

2

Yii FrameworkI am a ‘plugged’ person, means that I am constantly connected to the net and being a member of a certain number of social networks and tools (I maybe a weirdo but *no facebook* account) and I am very surprised of the amount of people that are highly interested on Yii and asks information on what is the best way to learn the framework. In order to solve those doubts I would like to put my two cents on this matter by sharing with you what was my learning curve with Yii -this way I do not need to post in every social network I am involved with.

For this post I assume that you know PHP (beginner, intermediate) and some DB skills for whatever the DB Engine you prefer to work with (MySQL, Oracle, etc…)

Yii Learning Guide

When you first arrive to Yii’s website, even though is an amazingly easy to navigate and use Website, you will obviously feel lost and won’t know where to start working with, and this is the most important steps of them all: download and READ its Definitive Guide to Yii. Do not worry if you do not understand some concepts, but you need to read it all, do not let any episode without a look as you will soon understand everything and will get ‘hooked’ by the easiness and magic of Yii. If you prefer not to download it, an online version of the guide is also available. If you are new to MVC, then I also recommend the visit to Larry Ullman’s Learning Yii Series blog.

After the guide, you will have tons of questions to solve and, even though will become a great tool in the future, do not jump immediately on the forum to drop them all. You need to get your hands on a practical example and for that, the demo application of The Yii Blog Tutorial is the perfect playground. It is highly recommended that you have your preferred PHP editor with two projects open: one that is the full demo blog application that comes with the Yii Framework download package, and the practical project that you will create following the tutorial. There are a couple of lines of code that you need to discover in the builded demo application and there are not in the tutorial.

There is also a book, “Agile Web Application Development with Yii1.1 and PHP5“, that takes you step-by-step through the process of using a test-driven development (TDD) approach to develop a real world Web application with Yii, from initial concept through production-readiness. This is another good practical tutorial to follow. If you do buy the book, then I recommend you to subscribe to Yii’s forum and follow this discussion: http://www.yiiframework.com/forum/index.php?/topic/11920-identified-issues/.

If you have reached this far on the article and follow the above steps then you are already amazed of Yii’s power and probably started your first real-world project with the Framework. Real issues and challenges will arise, it is time to find out about Yii’s amazing network of people, register and subscribe to Yii’s forum. Ask and you will be answered, people are so helpful and polite, it is just unreal the response time of this community. If you prefer  to get immediate help, then use Yii’s live IRC chat.

Don’t think that your learning curve has stopped here, to be ‘plugged’ to the network is highly recommended, so ‘plug’ your self to the Wiki. Its articles are written by other fellow programmers, it is a programmers-to-programmers experience, and due to the nature of the people that are part of this network, the Wiki grows day-by-day. This is the reason that I am subscribed to its RSS. You can also stay up to date by following any of the next social networks accounts: TwitterFacebook or LinkedIn

Once you know the ins and outs of the Framework, one great learning resource are the Extensions written by other programmers. Use them in order to easy your tasks and solve your problems but also read at its guts, its code behind. You will be surprised on how much you can learn from that. If you do not understand something within that code, have *always* a browser window or a tab opened with Yii’s Class Reference.

If you are comfortable with PHP, then I also recommend that you look at the code of the Framework. For example, if you wish to display a radio button using CHtml::radioButton look at the function itself too. Lots of forum questions wouldn’t be posted if they follow this simple advice.

Final Words

There are other resources to take into account (resources directly extracted from Yii’s site):

Cheat Sheets

The Yii cheat sheet, created by Sebastián Thierer. This presents commonly used Yii classes, methods and properties in a single printable sheet.

Yii 1.1 validator cheatsheet: created by schmunk. This summarizes all of Yii’s built-in validators in a single printable sheet.

Yii Playground

The Yii Playground is a community-contributed demo application that uses the PHP Yii Framework to show some features of the framework by explicit example. It is great place to see how some of the features work, and learn the code behind them.

Radio Podcasts

Yii Radio Podcasts, created by Imre Mehesz, covers hot topics and recent activities about the Yii framework.

Blogroll

The community-driven wiki page Yii Related Sites is collecting links to sites with useful tips and tutorials related to the Yii Framework.

The most important thing is that, once you get your hands on this amazing framework you get actively involved in the community (Forum, Wiki, Extensions), and share your projects so others can look at Yii’s real power and provide you with positive feedbacks.

I truly hope this article provides you with an easy guidance to get into Yii’s framework.



Tweet this!Tweet this!
Yii Framework

Custom Page Size for CGridView

4

Yii FrameworkThis post is actually something that, after permission granted from a Yii collegue Mike, was posted on Yii forum and I thought that was a *golden hint* too bad not to be shared among people interested on Yii: How to include a custom page size select box on your CGridView.

Step 1

First we need to modify the actionAdmin of the (CRUD) controller we want to include the select box that will change the page size of our CGridView. For the sake of this example, we are going to use the user controller which is created by default with Yii.

//
// page size drop down changed
if (isset($_GET['pageSize'])) {
//
// pageSize will be set on user's state
Yii::app()->user->setState('pageSize',(int)$_GET['pageSize']);
//
// unset the parameter as it
// would interfere with pager
// and repetitive page size change
unset($_GET['pageSize']);
}

Step 2

Now we have to modify the model’s search() function (e.g. model/User.php):

return new CActiveDataProvider(get_class($this),array(
'pagination'=>array(
//
// please check how we get the
// the pageSize from user's state
'pageSize'=> Yii::app()->user->getState('pageSize',
//
// we have previously set defaultPageSize
// on the params section of our main.php config file
Yii::app()->params['defaultPageSize']),
),
'criteria'=>$criteria,
));

Step 3

Finally, we need to change our view (e.g. views/user/admin.php) and we are done:

//
//
$pageSize=Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']);
// we use header of button column for the drop down
// so change the CButtonColumn in columns array like this:
...
array(
    'class'=>'CButtonColumn',
    'header'=>CHtml::dropDownList('pageSize',
        $pageSize,
        array(20=>20,50=>50,100=>100),
        array(
       //
       // change 'user-grid' to the actual id of your grid!!
        'onchange'=>
        "$.fn.yiiGridView.update('user-grid',{ data:{pageSize: $(this).val() }})",
    )),
),
...

Hope you find this hint as good as I thought it is. As Mike states, this information is to prove how easy is to enhance Yii components if you are not afraid of Javascript.

References

For futher reading please refer to original post.
Mike’s Forum Post

Happyiing!

Tweet this!Tweet this!
Yii Framework

How to create a Yii Behavior

4

Yii FrameworkFirst of all let’s find out what is exactly a behavior in Yii’s language (text extracted from Yii’s Definitive Guide):

A behavior is an object whose methods can be ‘inherited’ by its attached component through the means of collecting functionality instead of specialization (i.e., normal class inheritance). A component can be attached with several behaviors and thus achieve ‘multiple inheritance’.

Behavior classes must implement the [IBehavior] interface. Most behaviors can extend from the CBehavior base class. If a behavior needs to be attached to a model, it may also extend from CModelBehavior or CActiveRecordBehavior which implements additional features specifc for models.

This means that if we require additional features to the models we could extend them by using behaviors and also, that a model could actually implement more than one behavior thus extending endlessly its functionality.

Behaviors is the answer to those who wish to do things that differ from normal use and they need to be shared among other models but not to all of them. What that means? Well, IMHO, I think that if you need a special functionality that is shared among model objects then I suggest that would it better that you create a class that extends from the CActiveRecord and then extend your models from it.

I heard so many times that people wishes to create functions in controllers and we should stick to the MVC approach as it is, and not try to reinvent the wheel with things that come out our creative minds. If you need to do specific actions thing about a controller but if that action involves DB data then work with Models. This is a long discussion that could hold an article by itself; let’s be focus with this article.

Building and Using a Behavior

Our behavior will transform a model into a JSON array and as the Yii guide says, it implements the IBehavior interface as it extends from CBehavior. The code is extracted from my own extension behavior EJsonBehavior, here it is:

//
// EJsonBehavor extends from CBehavior
class EJsonBehavior extends CBehavior{
//
// this property will hold a reference to
// its owner - the model class that will
// have this behavior attached to it
private $owner;
//
// this property will reference the
// relations of the model class -owner
private $relations;
public function toJSON(){
//
// getting a reference to model class
// having this behavior attached to it
$this->owner = $this->getOwner();
//
// making sure it is a CActiveRecord descendant
if (is_subclass_of($this->owner,'CActiveRecord')){
//
// play with it!
//
// get model attributes
$attributes = $this->owner->getAttributes();
//
// if this model has related model classes
// get them attributes
$this->relations 	= $this->getRelated();
//
// structure the to-be-converted JSON
$jsonDataSource = array('jsonDataSource'=>array('attributes'=>$attributes,'relations'=>$this->relations));
//
// return the JSON result
return CJSON::encode($jsonDataSource);
}
return false;
}
//
// returns related model's attributes
private function getRelated()
{
$related = array();
$obj = null;
$md=$this->owner->getMetaData();
foreach($md->relations as $name=>$relation){
$obj = $this->owner->getRelated($name);
$related[$name] = $obj instanceof CActiveRecord ? $obj->getAttributes() : $obj;
}
return $related;
}
} // end of class

The important thing about the above code is not the funcitonality exposed, converting the model to a JSON array, but how we could get a hold to the behavior’s parent and access all its properties. That means, that by the same technique we could use that reference (owner) to play with the database referred by the object itself (check for example the code of the SLUG behavior).

Attaching the Behavior to a Model

This is the easiest part -yes, it is true, writing behaviors is a pretty easy thing with Yii. One way is the one referred on the wiki, which is the way I use it when I just need the use of a behavior certain times but the way I mostly use them is like this:

//
// This function is in the model
// where we want to attach the
// behavior too
public function behaviors() {
//
// needs to return an array
// of behavior objects
return array(
'EJsonBehavior'=>array(
//
// please check how it says to Yii
// where the class is located
'class'=>'application.behaviors.EJsonBehavior'
),
);
}

In the code above, you see how I tell Yii where the class is located in my applications folder; in this case I say to Yii to look for our behavior in the protected/behaviors folder and inside it there is a file EJsonBehavior.php which holds a behavior with a class name as the name of the file -EJsonBehavior.

Once we have attached the behavior to our model class, to use it is as simple as to call its public methods and/or properties. With our behavior above, we just do:

//
// pfff, so easy...
echo $model->toJSON();

After you have seen how easy is to create behaviors, having a look to the code of the Behaviors list at Yii’s site, will incredibly help your current learning curve. Hope this article has helped you to better understand behaviors.

Tweet this!Tweet this!
Captura de pantalla 2010-11-05 a las 20.05.08

How to use PHPExcel with Yii

4

Trying to learn and help some other programmers to find their solutions on the Yii Forum (I think is a superb way to learn the framework), I was facing one challenge with an external library that a fellow programmer wanted to use -quite good indeed: PHPExcel . And what is PHPExcel?

PHPExcel – OpenXML – Create Excel2007 documents in PHP – Spreadsheet engine

Project providing a set of classes for the PHP programming language, which allow you to write to and read from different file formats, like Excel 2007, PDF, HTML, … This project is built around Microsoft’s OpenXML standard and PHP.

Checkout the Features this class set provides, such as setting spreadsheet meta data (author, title, description, …), multiple worksheets, different fonts and font styles, cell borders, fills, gradients, adding images to your spreadsheet and much, much more!

The Challenge

The fellow programmer (Jack Fiallos) had a problem of using the libraries within Yii. He was surprised that he could easily use the libraries outside of the framework but not within the framework itself. At first we didn’t think about it but suddenly we thought about the autoloading features of Yii and looked into the guts of PHPExcel to find out what was causing the problems.

We were right, PHPExcel has an autoloading feature itself that when a classes is called (i.e. PHPExcel_Shared_ZipStreamWrapper) the first part of the name is actually reflecting the folder’s path where the class is located (i.e. PHPExcel_Shared_ZipStreamWrapper = PHPExcel/Shared_ZipStreamWrapper.php). Please review the following code (extracted from PHPExcel_Autoloader class):

public static function Load($pObjectName){
    if ((class_exists($pObjectName)) || (strpos($pObjectName, 'PHPExcel') === False)) {
       return false;
    }
    // this is the code that shows what I am saying
    $pObjectFilePath =  PHPEXCEL_ROOT.
           str_replace('_',DIRECTORY_SEPARATOR,$pObjectName).'.php';
           if ((file_exists($pObjectFilePath) === false) || (is_readable($pObjectFilePath) === false)) {
		return false;
           }
	require($pObjectFilePath);
}	//	function Load()

Solution

The workaround to this problem (at least the one I know) is by making use of the spl_autoload_register and spl_autoload_unregister PHP’s functions. The following code shows how we got the library working -I assume that you have downloaded the PHPExcel files, unzipped its contents and place them into a phpexcel folder within your application’s protected/extensions folder:

//
// VERY DUMMY TEST CONTROLLER
// FOR THE SAKE OF THE EXAMPLE
// TEST IT AS http : / / <yourapplicationurl> / index.php ? r=test/test
class TestController extends Controller{
     // no layouts here
     public $layout = '';
     public function actionTest()
     {
     //
     // get a reference to the path of PHPExcel classes
     $phpExcelPath = Yii::getPathOfAlias('ext.phpexcel.Classes');
     // Turn off our amazing library autoload
      spl_autoload_unregister(array('YiiBase','autoload'));
     //
     // making use of our reference, include the main class
     // when we do this, phpExcel has its own autoload registration
     // procedure (PHPExcel_Autoloader::Register();)
    include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
     // Create new PHPExcel object
     $objPHPExcel = new PHPExcel();
     // Set properties
     $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
							 ->setLastModifiedBy("Maarten Balliauw")
							 ->setTitle("PDF Test Document")
							 ->setSubject("PDF Test Document")
							 ->setDescription("Test document for PDF, generated using PHP classes.")
							 ->setKeywords("pdf php")
							 ->setCategory("Test result file");
     // Add some data
     $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', 'Hello')
            ->setCellValue('B2', 'world!')
            ->setCellValue('C1', 'Hello')
            ->setCellValue('D2', 'world!');
      // Miscellaneous glyphs, UTF-8
     $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A4', 'Miscellaneous glyphs')
            ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');
      // Rename sheet
      $objPHPExcel->getActiveSheet()->setTitle('Simple');
      // Set active sheet index to the first sheet, so Excel opens this as the first sheet
     $objPHPExcel->setActiveSheetIndex(0);
      // Redirect output to a client’s web browser (Excel2007)
      header('Content-Type: application/pdf');
      header('Content-Disposition: attachment;filename="01simple.pdf"');
      header('Cache-Control: max-age=0');
      $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'PDF');
      $objWriter->save('php://output');
       //
       // Once we have finished using the library, give back the
       // power to Yii...
       spl_autoload_register(array('YiiBase','autoload'));
       }
}

Final Words

This post is using PHPExcel external library as an example, but this procedure should be taken into account when we encounter a problem like this. Whenever you find a library that you wish to include in your Yii application, check out its autoloading functions first.



Tweet this!Tweet this!
Yii Framework

How to use jQueryslidemenu with Yii’s CMenu

4

Yii FrameworkYii makes it really easy for all to use their already made objects that automate everything we do. It provides also great power of flexibility and styling but hey, we programmers tend to complicate our lives and push a little more the power of our tools.

This tutorial makes use of the jqueryslidemenu plugin to give us a cool featured slidemenu with just a little bit of effort taking advantage of the way Yii’s CMenu widget renders its items.

Installation of Script

Once we download the plugin we are going to place its contents to their correspondent folders (i.e. styles on the css folder, js files on scripts folder, images -yes you guessed right, the images folder). Nevertheless is up to you how you order the files as long as the images and styles have their image paths correctly set.

Creating the Menu

We are going to use it in our main.php layout file for the sake of the example -and because it is the place where we, most of us, will use it.

First we register the required css and js files for our menu.

// remember that you can actually point to the js files directly if
// your script file is outside of protected/subfolders
$jqueryslidemenupath = Yii::app()
     ->assetManager
     ->publish(Yii::app()->basePath.'/scripts/jqueryslidemenu/');
//Register jQuery, JS and CSS files
Yii::app()
     ->clientScript
     ->registerCoreScript('jquery');
Yii::app()
     ->clientScript
     ->registerCssFile($jqueryslidemenupath.'/jqueryslidemenu.css');
Yii::app()
     ->clientScript
     ->registerScriptFile($jqueryslidemenupath.'/jqueryslidemenu.js');

And finally we create our menu. Please note that our menu is wrapped with a layer ‘div’ and one its classes to jqueryslide menu.

<div id="myslidemenu" class="jqueryslidemenu">
<?php $this->widget('zii.widgets.CMenu',array(
   'items'=>array(
      array('label'=>'Home', 'url'=>array('/site/index')),
      array('label'=>'About', 'url'=>array('/site/page', 'view'=>'about')),
      array('label'=>'Contact', 'url'=>array('/site/contact')),
      array('label'=>'jqSlideMenuTest', 'url'=>array('#'),
        'items'=>array(
           array('label'=>'Home',
                    'url'=>array('/site/index')),
           array('label'=>'About',
                    'url'=>array('/site/page', 'view'=>'about')),
           array('label'=>'Contact',
                    'url'=>array('/site/contact'),
                   'items'=>array(
                      array('label'=>'Home',
                               'url'=>array('/site/index')),
                      array('label'=>'About',
                               'url'=>array('/site/page', 'view'=>'about')),
                      array('label'=>'Contact',
                              'url'=>array('/site/contact'),
                              'items'=>array(
                                   array('label'=>'Home',
                                            'url'=>array('/site/index')),
                                   array('label'=>'About',
                                            'url'=>array('/site/page', 'view'=>'about')),
                                   array('label'=>'Contact',
                                            'url'=>array('/site/contact')),
                       )),
                  )),
              )),
       array('label'=>'Login',
                'url'=>array('/site/login'),
                'visible'=>Yii::app()->user->isGuest),
       array('label'=>'Logout ('.Yii::app()->user->name.')',
                'url'=>array('/site/logout'),
                'visible'=>!Yii::app()->user->isGuest)),
     )); ?>
</div><!-- mainmenu -->

That’s it… quite easy right? You can change its style to suit your ‘design’ needs.

Download Example Files

Our colleague programmer Trejder has compiled an example for all of you to play with it. download files

Just make sure that you have the runtime and assets’s folders permissions to be writable and correct the index.php file Yii path’s to the correct one on your computer.

Tweet this!Tweet this!
open-source

Adding Content to an iFrame and Print its Contents

0

I was working on a project and I had to create a print friendly version of a bill and even though it sounds so easy to do, I had to face some browser problems. For some reason, that I couldn’t find, there was no universal solution to it -or at least I couldn’t find one that worked with every browser.

After breaking my head towards the wall and throwing some darts to Microsoft’s IE Browser poster I found one that worked.

function iPrint( contentToPrint )
{
	// I have a hidden IFRAME within the document called
        // pfiframe (if you try to use jQuery here fails
	var oIframe = document.getElementById('pfiframe');
        // get a reference to the document
	var oDoc = (oIframe.contentWindow || oIframe.contentDocument);
	if (oDoc.document) oDoc = oDoc.document;
        // now we write an entire HTML doc with the
        // contents we want to print in its body
	oDoc.write("<html><head><title>title</title>");
	oDoc.write("</head><body>");
       // check the function to print that we
       // include here
	oDoc.write( contentToPrint +
		"<script type='text/javascript'>function printIt(){window.print();return false}</" + "script></body></html>");
	oDoc.close();
       // again, I am not using jQuery here
       // for unknown reason, it fails to call
       // differently as it is here
	window.frames[0].printIt();
}

See? Easy right? Well I spent quite a lot of minutes to realize that! Hope this discovery help you guys out there.



Tweet this!Tweet this!
Picture-121-300x157

Speed Up Your Pages With Lazy Load JQuery Plugin

2

I would like to introduce you this simple but very efficient plugin that will help us speed up the downloading time of our web pages. I am talking about mr Mika Tuupola’s Lazy Load JQuery Plugin.

This plugin loads the images of a web page as the user scrolls to their position, that is, images wont load until they are not within the visible viewport margins of the window.

How to use

First we need to insert the following references into our code

<!-- insert a reference to jquery and the jquery.lazyload plugin -->
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.lazyload.js" type="text/javascript"></script>

And now this few lines of code in our document.ready function

<script type="text/javascript">
$(function() {
          $("img").lazyload({
              placeholder : "img/grey.gif",
              effect      : "fadeIn"
           });
       });
< /script>

And that’s it! Easy right?

Tweet this!Tweet this!
 

Handling Timeouts with PHP5 SoapClient Extension

0

I was breaking my head towards a silly thing around SoapClient Calls. My actual project requires Soap Calls to certain providers and everytime I was calling the external server, I had to wait for the server response (if any) and if the server failed to respond accordingly… damn… Warnings and/or Errors displayed and boom… My great application just looked like… well, forget it, I just used the try and catch statements for that… not big deal.

So I jump over Google’s horse and looked around implementing timeouts! because that was a true issue. Can you imagine? A user makes a request I looked around my DB and suddenly that single SOAP call takes me one minute to respond. No good, time for a solution.

Found the way to do it, by setting a hidden parameter (not documented) named ‘connection_timeout’:

//
// setting a connection timeout (five seconds on the example)
//
$client = new SoapClient($wsdl, array("connection_timeout"=>15));

The above says wait 15 seconds before returning a fault if you cannot connect properly to the host. The parameter ‘connection_timeout’ addresses the time it takes to wait to connect to your host.

As Jim Plush’s said:

You’d have two timeouts set in your application one for how long it should take to actually connect to your remote host and a timeout for how long the socket connection should wait for a response from the server.

So, now we need to set the time we wait for a server response with the following:

ini_set('default_socket_timeout', 180);

With these two configuration options we control the time to wait for a Soap host connection and the time waiting for a Soap Service response. Just perfect.

Tweet this!Tweet this!
 

Get Latitude and Longitude with Google Maps V3

7

I would like to share with you a little piece of code that I find quite useful in my applications. I do create lots of guides that require a small utility to find out the latitude and longitude of a business location from a control panel in order to display the maps appropiately on the Web. Here I will do my best to explain a step procedure on how to do that -once you know the procedure, it is easy to create plugins or whatever you wish to do.

Step 1

First of all, lets make a reference to the new version of Google Maps. Check that we have to specify a parameter sensor=false. To find out more about this parameter please follow this link.

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

Step 2

Now we are going to write the HTML tags on the BODY of our document that will hold the map and the controls that will hold latitude, longitude and zoom level references. Also, see the CSS that control the size of the map holder.

<style>
div#gmap {
width: 100%;
height: 300px;
}
</style>
<body>
<center>
<!-- MAP HOLDER -->
<div id="gmap"></div>
<!-- REFERENCES -->
lat:<span id="lat"></span> lon:<span id="lon"></span><br/>
zoom level: <span id="zoom_level"></span>
</center>
</body>

Step 3

Now, we are going to write the function that will display the map when the document loads. The function, that we will call ‘initialize’ has different parts that we will describe now:

Part 1

Setting the map zoom level and its position in the world:

var myLatlng = new google.maps.LatLng(38.971154274048345,1.415863037109375); // IBIZA :)
var myOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("gmap"), myOptions);

Part 2

Placing a marker on the map specifying its center position (please refer to above code for LatLon location).

// marker refers to a global variable
marker = new google.maps.Marker({
position: myLatlng,
map: map
});

Part 3

Now, the events that will take control of the marker center re-positioning and placing the information on the correspondent document objects (lat, lon, and zoom level).

// if center changed then update lat and lon document objects
google.maps.event.addListener(map, 'center_changed', function() {
var location = map.getCenter();
document.getElementById("lat").innerHTML = location.lat();
document.getElementById("lon").innerHTML = location.lng();
// call function to reposition marker location
placeMarker(location);
});
// if zoom changed, then update document object with new info
google.maps.event.addListener(map, 'zoom_changed', function() {
zoomLevel = map.getZoom();
document.getElementById("zoom_level").innerHTML = zoomLevel;
});
// double click on the marker changes zoom level
google.maps.event.addListener(marker, 'dblclick', function() {
zoomLevel = map.getZoom()+1;
if (zoomLevel == 20) {
zoomLevel = 10;
}
document.getElementById("zoom_level").innerHTML = zoomLevel;
map.setZoom(zoomLevel);
});

Part 4

Initialize the document objects with default information

document.getElementById("zoom_level").innerHTML = 16;
document.getElementById("lat").innerHTML = 38.971154274048345;
document.getElementById("lon").innerHTML = 1.415863037109375;

Step 4

Finally, we have to write the function that will reposition the marker on ‘zoom_changed’ map event and call the ‘initialize’ function on window load event.

function placeMarker(location) {
var clickedLocation = new google.maps.LatLng(location);
marker.setPosition(location);
}
window.onload = function(){initialize()};

And that’s it, we have a great utility to plug onto our projects in order to find out the latitude and longitude of an address.

DOWNLOAD

I have included the working version of this tutorial for you to download. If you make any changes on the code in order to improve/add more functionality to it (that is easy fellows), please share it here with us.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: Get Lat Lon Finder (1.41KB)
added: 22/01/2010
clicks: 2680
Tweet this!Tweet this!
 

Fixing 500 Internal Error on Xampp

1

First of all, let’s talk about XAMPP a bit. XAMPP is an easy to install Apache distribution containing MySQL, PHP and Perl. XAMPP is really very easy to install and to use – just download, extract and start.

There are three types of distribution (Windows, Linux and Mac). I am not going to discuss anything about XAMPP, I think that with a visit to their site you will all the info required to install and run this wonderful package.

What I want to concentrate on is that when trying to use a regular .htaccess in a specific folder, Apache fires a beautiful and really annoying (it is not very well explained why this error happens when it happens) 500 Internal Error.

Finding the problem

Well, I went to the httpd.conf file to see what was going on and found the problem. The problem is that XAMPP Apache version has a very strict security on allowing users to modify its default settings -and its default settings are AllowOverride None:

AllowOverride AuthConfig

Solution

Just go to the Directory directive and change AllowOverride AuthConfig to AllowOverride All and thats it.

<Directory "/Applications/xampp/xamppfiles/htdocs">
Options Indexes FollowSymLinks ExecCGI Includes
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
# AllowOverride AuthConfig
AllowOverride All
Order allow,deny
Allow from all
</Directory>
Tweet this!Tweet this!
Go to Top