Tag Archives: library

GMap.NET component : Moving Marker

WTH is GMap.NET?

Simply put: it’s an open source .net component that can show online mapping service (such as Google Map, Bing Map, OpenStreetMap) in your .NET app.
Download the binary here: http://greatmaps.codeplex.com/
Extract it. You’ll get the .net 2.0 and .net 4.0 version, since I’m using VS 2015, we’ll use the .net 4.0 version.

What will we do now is about how to move a marker inside the map (for tracking/visualizing object movement, etc). We’ll just move the marker randomly in this tutorial.

  • Create new VB Windows Form project
  • Add GMap.NET component into your project reference
GMap.NET component reference

GMap.NET component reference

  • Add GMap.NET component into your toolbar.
Add GMap.NET component step 1

Add GMap.NET component step 1

Add GMap.NET component step 2

Add GMap.NET component step 2

  • Now drag and drop the GMap.NET control into your Form, I name it myMap
  • We’ll also add another controls: 1 Button (name: btnMove), 1 Timer (name: tmr1), 1 Label (name: lblInfo)
List of components

List of components

I also add new bitmap resource into our project properties. This will be used as our marker symbol.

Resource for marker symbol

Resource for marker symbol

You can see the Form’s full source code at the bottom of this post. I’ll just point out some important parts:

  • Map initialization is on Form1_Load event code (zoom level, initial position, provider used, marker type, etc)
  • When you click on the btnMove, it’ll start generating new random position for our marker. The random change is happened in the timer event (tmr1_Tick)
  • The process to update the map visual is delegated into function update_map(), so it will run in different thread and the form still responsive
  • In this tutorial, we are using BingSatelliteMapProvider, you can use another provider such as GoogleMapProvider or OviSatelliteMapProvider. Just see MapProviders namespace to see all supported providers.

Running the app

Running the app

Here’s the full source code:

Imports GMap.NET
Imports GMap.NET.WindowsForms

Public Class Form1
    Private Delegate Sub UpdateFormDelegate()
    Private UpdateFormDelegate1 As UpdateFormDelegate

    Private copter_lat, copter_lon As Double
    Private WithEvents copter_marker As Markers.GMarkerGoogle
    Private WithEvents copter_layer As GMapOverlay

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        copter_lat = -7.076275
        copter_lon = 110.428952

        myMap.MinZoom = 5
        myMap.MaxZoom = 20
        myMap.Zoom = 17
        myMap.Position = New PointLatLng(-7.076275, 110.428952)
        myMap.MapProvider = MapProviders.BingSatelliteMapProvider.Instance
        myMap.Manager.Mode = AccessMode.ServerAndCache
        copter_layer = New GMapOverlay("copter_layer")
        copter_marker = New Markers.GMarkerGoogle(New PointLatLng(-7.076275, 110.428952), My.Resources.purple_drone)
    End Sub

    Private Sub tmr1_Tick(sender As Object, e As EventArgs) Handles tmr1.Tick
        Dim delta_lat As Double = ((100 * Rnd()) + 20) / 10000000.0
        Dim delta_lon As Double = ((100 * Rnd()) + 20) / 10000000.0
        Dim not_lat As Single = Rnd()
        Dim not_lon As Single = Rnd()

        If not_lat >= 0.5 Then
            copter_lat += delta_lat
            copter_lat -= delta_lat
        End If
        If not_lon >= 0.5 Then
            copter_lon += delta_lon
            copter_lon -= delta_lon
        End If

        UpdateFormDelegate1 = New UpdateFormDelegate(AddressOf update_map)
    End Sub

    Private Sub btnMove_Click(sender As Object, e As EventArgs) Handles btnMove.Click
        If tmr1.Enabled Then
            tmr1.Enabled = False
            MsgBox("Random Move stop")
            tmr1.Enabled = True
            MsgBox("Random Move start")
        End If
    End Sub

    Private Sub myMap_OnMapZoomChanged() Handles myMap.OnMapZoomChanged
        lblInfo.Text = "Info : Lat= " + CStr(copter_lat) + ", Lon= " + CStr(copter_lon) + ", Zoom Level= " + CStr(myMap.Zoom)
    End Sub

    Private Sub update_map()
        copter_marker.Position = New PointLatLng(copter_lat, copter_lon)
        lblInfo.Text = "Info : Lat= " + CStr(copter_lat) + ", Lon= " + CStr(copter_lon) + ", Zoom Level= " + CStr(myMap.Zoom)
    End Sub
End Class

Matrix operation library for CodeIgniter

This tips is useful if you someday handling web-based project that involving Matrix handling and you want to implement it using CodeIgniter. We’ll use PHPMath library for this.

  • Download the latest version of phpmath library from here: http://www.phpmath.com/build02/downloads/
  • Open the archive (build02.tar.gz) and see the content, you’ll see “build02” folder, go inside, you’ll see more folders there:
phpmath archive content

phpmath archive content

  • Because we only need the matrix handling and operation library, we just need the “JAMA” folder inside.
  • Extract this “JAMA” folder into your CodeIgniter’s application/third_party/ library, rename it to more meaningful folder, I prefer “phpmath”. Your third_party library will be look like this:
phpmath inside third_party folder

phpmath inside third_party folder

  • Go inside “phpmath” folder, you’ll see more folders there. We don’t need “docs”, “examples” and “tests” folder, we can delete them, your phpmath folder will be like this:
phpmath after deleting unnecessary folders

phpmath after deleting unnecessary folders

And you are done! (In this tips: not like mPDF and PHPExcel library, we don’t need to create a new file/class in the application/libraries folder)

How to use it?

Quite simple, check and test these code samples inside your controller:

// load the phpmath library

// define new matrix
     array(9, 10),
     array(11, 12)
     array(13, 14),
     array(15, 16)
// build the Matrix class
$mA=new Matrix($raw_matrix_a);
$mB=new Matrix($raw_matrix_b);
$mC=new Matrix($raw_matrix_c);
$mD=new Matrix($raw_matrix_d);

//get the matrix element
//set value
$mA->set(1,1, 0);
//get matrix dimension

$mE=$mD->plus($mC); //must have same dimension
$mE=$mD->inverse(); // must be square matrix

Easily integrate mPDF into CodeIgniter Framework

Got the tip from here: http://davidsimpson.me/2013/05/19/using-mpdf-with-codeigniter/
On this previous post, I tell you on how to easily integrate ezPDF into CodeIgniter but the problem is: the PDF generation is not template-based. So, you have to write a lot of codes just to generate simple PDF output.
By integrating mPDF into your CodeIgniter-based site, you can create a PDF output via templating system just as simple as loading a view and pass through some variables into it. mPDF also support CSS, so, you can style your HTML template as cool as you wish.
Here’s the steps-by-steps guide:

  • Download mPDF from http://www.mpdf1.com/mpdf/index.php?page=Download . Remember to download the “Full installation” first (a bit big) and then you can download the patch/upgrade (a little smaller size)
  • Extract it to your application/third_party/ folder of your CodeIgniter. Your third_party folder would be like this:

    mPDF in third_party folder

    mPDF in third_party folder

  • Create a new file in your application/libraries/ name it m_pdf.php and these are the contents:

  • Your library folder would be like this:
    mPDF in the library folder

    mPDF in the libraries folder

  • And it's done!

How to use it?
Create a CodeIgniter "view file", let's named it pdf_output.php:

load->view('header'); //let's assume that we already have 'header' view file
Hello, this just a simple HTML template.
I'm a variable passed from the controller, my content is
load->view('footer'); //let's assume that we already have 'footer' view file

Now, inside the controller, you can do this:

//this data will be passed on to the view
$data['the_content']='mPDF and CodeIgniter are cool!';

//load the view, pass the variable and do not show it but "save" the output into $html variable
$html=$this->load->view('pdf_output', $data, true); 

//this the the PDF filename that user will get to download
$pdfFilePath = "the_pdf_output.pdf";

//load mPDF library
//actually, you can pass mPDF parameter on this load() function
$pdf = $this->m_pdf->load();
//generate the PDF!
//offer it to user via browser download! (The PDF won't be saved on your server HDD)
$pdf->Output($pdfFilePath, "D");

Creating Ms Word Document using CodeIgniter and PHPWord

One of my reader – Don Lafferty – told us that integrating PHPWord into CodeIgniter is also as easy as integrating PHPExcel into CodeIgniter. So, I decided to give it a try and it really does so simple.

What is PHPWord? From github:

[box type=”info”] PHPWord is a library written in PHP that create word documents. No Windows operating system is needed for usage because the result are docx files (Office Open XML) that can be opened by all major office software.[/box]

Notes: As I write this, PHPWord can create .docx, .rtf and .odt file.

  • Without more a do, go download the required package

[button link=”http://codeigniter.com/” newwindow=”yes” color=”orange”] Download CodeIgniter[/button]

[button link=”https://github.com/PHPOffice/PHPWord” newwindow=”yes” color=”black”]Download PHPWord[/button]

  • Extract PHPWord (only extract PHPWord.php and PHPWord folder) into your CodeIgniter’s application/third_party
ci phpword extract file

Only extract those two


Your application/third_party will look like this

ci third_party folder

Your new third_party folder after adding PHPWord

  • Now, create a new library inside your CodeIgniter’s application/libraries. Let’s call it Word.php. Here’s the full source:

  • OK, it's done.
  • Now we can call and use the Word library from within your controllers (examples are taken from PHPWord with minimal change):
  • Call/load the library and create new section (needed)
//our docx will have 'lanscape' paper orientation
$section = $this->word->createSection(array('orientation'=>'landscape'));
  • Adding some text and style it!
// Add text elements
$section->addText('Hello World!');
$section->addText('I am inline styled.', array('name'=>'Verdana', 'color'=>'006699'));
$this->word->addFontStyle('rStyle', array('bold'=>true, 'italic'=>true, 'size'=>16));
$this->word->addParagraphStyle('pStyle', array('align'=>'center', 'spaceAfter'=>100));
$section->addText('I am styled by two style definitions.', 'rStyle', 'pStyle');
$section->addText('I have only a paragraph style definition.', null, 'pStyle');
  • Adding some images! Watchout on how I add new image, don't use base_url or site_url, PHPWord only take an absolute path to your server (it also means that you can't insert image that isn't hosted on your server)
// Add image elements
$section->addImage(FCPATH.'/image/_earth.JPG', array('width'=>210, 'height'=>210, 'align'=>'center'));
$section->addImage(FCPATH.'/image/_mars.jpg', array('width'=>100, 'height'=>100, 'align'=>'right'));
  • Create a table and give some style
// Define table style arrays
$styleTable = array('borderSize'=>6, 'borderColor'=>'006699', 'cellMargin'=>80);
$styleFirstRow = array('borderBottomSize'=>18, 'borderBottomColor'=>'0000FF', 'bgColor'=>'66BBFF');
// Define cell style arrays
$styleCell = array('valign'=>'center');
$styleCellBTLR = array('valign'=>'center', 'textDirection'=>PHPWord_Style_Cell::TEXT_DIR_BTLR);
// Define font style for first row
$fontStyle = array('bold'=>true, 'align'=>'center');
// Add table style
$this->word->addTableStyle('myOwnTableStyle', $styleTable, $styleFirstRow);
// Add table
$table = $section->addTable('myOwnTableStyle');
// Add row
// Add cells
$table->addCell(2000, $styleCell)->addText('Row 1', $fontStyle);
$table->addCell(2000, $styleCell)->addText('Row 2', $fontStyle);
$table->addCell(2000, $styleCell)->addText('Row 3', $fontStyle);
$table->addCell(2000, $styleCell)->addText('Row 4', $fontStyle);
$table->addCell(500, $styleCellBTLR)->addText('Row 5', $fontStyle);
// Add more rows / cells
for($i = 1; $i <= 2; $i++) {
	$table->addCell(2000)->addText("Cell $i");
	$table->addCell(2000)->addText("Cell $i");
	$table->addCell(2000)->addText("Cell $i");
	$table->addCell(2000)->addText("Cell $i");
	$text = ($i % 2 == 0) ? 'X' : '';
  • Lastly, give the Ms Word document as .docx file to users without saving it to server's hard-disk.
$filename='just_some_random_name.docx'; //save our document as this file name
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache

$objWriter = PHPWord_IOFactory::createWriter($this->word, 'Word2007');
  • Example result (opened using Ms Word 2007 and zoomed 50%)
ci and phpword example result

This is what our code generate. CodeIgniter + PHPWord = MS Word 2007 document

Now our CodeIgniter become more complete, we can create Excel file, create a PDF file and, in this tutorial, creating Microsoft Word 2007 document!

Easily integrate ezPDF (a.k.a pdf-php) into CodeIgniter Framework

Got another spare time, so, another simple tips for you. Last post I already show how to easily integrate PHPExcel in CodeIgniter so you’ll be able to create downloadable XLS report easily. We will complete our CodeIgniter reporting capability by adding PDF output feature. (Yeah, I know PHPExcel can also create a PDF output, but it sucks big, the table is badly formatted)

Why ezPDF (now pdf-php)?

Well, there’s already a guide for integrating TCPDF and DOMPDF into CodeIgniter so I present you another option by using ezPDF (pdf-php)

What’s ezPDF not good for?

Don’t use ezPDF if you are planning to use CSS or HTML codes to style your PDF. As far as I know, ezPDF does not offer easy way to parse CSS or HTML (more like it doesn’t support it). I’m not saying that you can’t style your text, in fact, some primitive text styling is supported, such as: <b>,<i>,<u>. Please read ezPDF readme file to comprehend what ezPDF has and hasn’t.

What’s ezPDF good at?

Graphic functionality, drawing (line, curve, ellipse, box, polygon), advance page numbering, paging function, automatic table-of-content generation. (On my test, ezPDF/pdf-php failed to insert a PNG image with transparency/alpha-channel rendering corrupted PDF file)

  • Create pdf-php folder in your application/third_party/ folder (let’s separate it from PHPExcel). Extract fonts folder, class.pdf.php and class.ezpdf.php inside your pdf-php folder.
Files and folder need to be extracted from ezPDF

You only need to extract these files and folder

Your application/third_party/ folder will look like this

codeigniter application/third_party structure

codeigniter application/third_party/pdf-php/ structure with ezPDF .zip content extracted there

  • Create Pdf.php inside your application/libraries/. We will name our library as Pdf class. Here’s the full library code:

Your application/libraries/ folder will look like this:

codeigniter application/libraries/ structure

codeigniter application/libraries/ structure with our new ezPDF/pdf-php library

  • It's done. This is example on how to use our new ezPDF/pdf-php library (this code is inside a function within a controller):
public function index()
		error_reporting(0);  //suppress some error message
			'paper'=>'letter',   //paper size
			'orientation'=>'landscape',  //portrait or lanscape
			'type'=>'color',   //paper type: none|color|colour|image
			'options'=>array(0.6, 0.9, 0.8) //I specified the paper as color paper, so, here's the paper color (RGB)
		$this->load->library('pdf', $parameters);  //load ezPdf library with above parameters
		$this->pdf->selectFont(APPPATH.'/third_party/pdf-php/fonts/Helvetica.afm');  //choose font, watch out for the dont location!
		$this->pdf->ezText('Hello World!',20);  //insert text with size
		//get data from database (note: this should be on 'models' but mehhh..), we'll try creating table using ezPdf
		$q=$this->db->query('SELECT id, username, role FROM administrator');
                //this data will be presented as table in PDF
		foreach ($q->result_array() as $row) {
                //this one is for table header
			'id'=>'User ID',
			'username'=>'User Name',
		$this->pdf->ezTable($data_table, $column_header); //generate table
		$this->pdf->ezSetY(480);  //set vertical position
		$this->pdf->ezImage(base_url('images/test_noalpha.png'), 0, 100, 'none', 'center');  //insert image
		$this->pdf->ezStream(array('Content-Disposition'=>'just_random_filename.pdf'));  //force user to download the file as 'just_random_filename.pdf'

Example PDF output will be like this:

codeigniter and ezPDF output result

Example ezPDF output from above codes

On above example, I show you how to:

  • call the library, select paper size, paper orientation, paper color
  • select font type, and font size
  • insert a PNG image into the PDF
  • create a table from database
  • finally, force user to download the PDF file with specific file name

Once again, for more ezPDF/pdf-php features, please read the readme on your ezPDF/pdf-php download.