Wednesday, October 30, 2013

Swing File Chooser Demo

[caption id="attachment_940" align="aligncenter" width="264"]Swing File Chooser Swing File Chooser[/caption]

[sourcecode language="java"]
package main;

import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class SwingFileChooser extends JPanel implements ActionListener{
private static final String newLine = "\n";
private JButton openButton,saveButton;
private JTextArea log;
private JFileChooser fc;

public SwingFileChooser(){
super(new BorderLayout());
initComponents();

}

private void initComponents(){
log = new JTextArea();
log.setMargin(new Insets(5, 5, 5, 5));
log.setEditable(false);
JScrollPane jsp = new JScrollPane(log);
fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
openButton = new JButton("Open File");
openButton.addActionListener(this);
saveButton = new JButton("Save File");
saveButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(saveButton);
add(buttonPanel,BorderLayout.NORTH);
add(jsp,BorderLayout.CENTER);
}

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == openButton){
int returnVal = fc.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
log.append("Opening " + file.getName() + newLine);
}else{
log.append("cancelled file opening" + newLine);
}
log.setCaretPosition(log.getDocument().getLength());

}else if(e.getSource() == saveButton){
int returnVal = fc.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
log.append("Saving " + file.getName() + newLine);
}else{
log.append("cancelled file saving" + newLine);
}
log.setCaretPosition(log.getDocument().getLength());
}
}

private static void createGUI(){
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("SwingFileChooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JComponent newContentPane = new SwingFileChooser();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
createGUI();
}
});

}
}

[/sourcecode]

Monday, October 7, 2013

OpenSource Directions API Demo - YOURS Navigation API

[caption id="attachment_935" align="aligncenter" width="621"]YOURS API Demo YOURS API Demo[/caption]

In this tutorial, I 'll introduce you to YOURS, an OpenSource directions API. There are few OpenSource directions APIs available such as MapQuest, GeoSmart, Nominatim in addition to YOURS. However in my opinion, YOURS is the best and a good alternative to Google Directions which is the most popular Directions provider obviously.

The flexibility of usage has given more power in YOURS over other APIs in the same family. MapQuest is nice but it is not working for many geographical locations of the world other than North America and Europe. Nominatim is poor in its functional level and has less support for geographical diversity.

According to YOURS doucmentation, the API provide following features.

  • Generate fastest or shortest routes in different modes:

    • using all available roads for Car, Bicycle and Pedestrians .

    • using only national, regional or local cycle routes/networks for Bicycle.



  • Unlimited via points (waypoints) to make complex routes.

  • Drag and drop waypoints moving.

  • Drag and drop waypoint ordering.

  • Geolocation: Lookup street- and placenames to determine their coordinates.

  • Reverse geolocation: Lookup coordinates to determing their street- and placenames.You can read other features in doucmentation.


Example URL


http://www.yournavigation.org/api/1.0/gosmore.php?format=kml&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik

This tutorial provides sample code for accessing the API in JavaScript. As JavaScript does not allow  cross domain requests we 're using a proxy which accepts requests from client, forward it to the API and send back server response. The proxy is written in PHP using CURL which is more safe than file_get_contents() and similar content loading functions.

We are using OpenLayers map with a vector layer which is going get features from server response. The route is drawn on map using vector data.

The API also provides travelling time, distance and turn by turn directions.

Demo

client.html

[sourcecode language="html"]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="description" content="OpenSource Directions API Demo - YOURS Navigation API">
<title>OpenSource Directions API Demo</title>
<link rel="stylesheet" href="http://demos.site11.com/assets/css/style.css">
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://openlayers.org/api/OpenLayers.js"></script>

<script type="text/javascript">
var lon = 0;
var lat = 0;
var zoom = 0;

var wgs84 = new OpenLayers.Projection("EPSG:4326");
var mercator = new OpenLayers.Projection("EPSG:900913");

$(document).ready(function(){
layer = new OpenLayers.Layer.OSM("OSM");
geojson_layer = new OpenLayers.Layer.Vector("GeoJSON", {
styleMap: new OpenLayers.StyleMap({
strokeColor: "#F00",
projection: mercator
}),
strategies: [new OpenLayers.Strategy.Fixed()],
protocol: new OpenLayers.Protocol.HTTP({
url: 'proxy.php?flat=6.9344&flon=79.8428&tlat=7.2844590&tlon=80.637459&v=motorcar&fast=1&layer=mapnik',
format: new OpenLayers.Format.GeoJSON()

})
});

var options = {
div : "map",
projection : wgs84,
units: "dd",
numZoomLevels : 7
};
var map = new OpenLayers.Map(options);

map.addLayers([layer,geojson_layer]);
map.setCenter(new OpenLayers.LonLat(79.8428, 6.9344).transform(wgs84,mercator), 12);

//Get Directions
$.ajax({
type: 'GET',

dataType: 'json',
url: 'proxy.php?flat=6.9344&flon=79.8428&tlat=7.2844590&tlon=80.637459&v=motorcar&fast=1&layer=mapnik',
cache: false,
success: function(response){
$("#travel_time").html(response.properties.traveltime);
$("#distance").html(response.properties.distance + ' miles');
$("#directions").html(response.properties.description);
},error: function(){

}
});

});

</script>

<style type="text/css">
#map{
width: 800px;
height: 400px;
border: 2px solid black;
padding:0;
margin:0;
}
</style>

</head>
<body>

<div id="map" style="width: 700px; height: 300px;margin-bottom : 50px;" align="center"></div>



<b>Travel Time</b>
<div id="travel_time"></div>



<b>Distance</b>
<div id="distance"></div>



<b>Directions</b>
<div id="directions"></div>

</body>
</html>

[/sourcecode]

Proxy.php

[sourcecode language="php"]
<?php $flat = $_GET['flat']; $flon = $_GET['flon']; $tlat = $_GET['tlat']; $tlon = $_GET['tlon']; $v = $_GET['v']; $fast = $_GET['fast']; $layer = $_GET['layer']; $myURL = "http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&instructions=1&flat=".$flat."&flon=".$flon."&tlat=".$tlat."&tlon=".$tlon."&v=".$v."&fast=".$fast."&layer=".$layer; $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $myURL

));

$resp = curl_exec($curl);
curl_close($curl);
echo $resp;
?>

[/sourcecode]

Saturday, October 5, 2013

How to store an array in localStorage

This tutorial assumes that you are already familiar with HTML5  localStorage.

Although HTML5  localStorage is very useful, its usage is restricted to key value mechanism. Key and value is stored in string format despite what we need. For an instance, though you can specify a boolean type (either true or false) as the value, it is stored as a string.

What if we need to store multiple items as the value for a certain key. This can be little bit tricky if you gonna place an array directly as the value. When we scratch the surface of localStorage basic principles this is not possible. However you can come up with your own solutions that might work for you.

This tutorial demonstrates a simple way of handling above problem using json. We gonna store array as a json string. So nothing new here.

First add jQuery library as we are using some jQuery functions.

[sourcecode language="javascript"]
<script type="text/javascript">
var favorites_str = localStorage.getItem('my_favorites');
if(favorites_str == null) {
favorites = [];
favorites.push({ "name":"keshi", "id":"6" });
} else{
favorites = JSON.parse(favorites_str);
favorites.push({ "name":"sara", "id":"6" });

}
localStorage.setItem('my_favorites',JSON.stringify(favorites));
</script>

[/sourcecode]

To verify that above script is functioning please copy and run below script. It will make things easy, if you put this code in  a separate file.

[sourcecode language="javascript"]
<script type="text/javascript">
var data = localStorage.getItem('my_favorites');
if(data == null){
alert("0 favorites");
}else{
favorites = JSON.parse(data);
$.each(favorites, function(index,item){
alert(item.name);

});
}
</script>

[/sourcecode]

Tuesday, October 1, 2013

OpenSource PHP Graph libraries

[caption id="attachment_930" align="alignnone" width="645"]PHP Graphs PHP Graphs[/caption]

There are so many PHP graph projects which you can find on internet. At the time of writing this post, JpGraph, phpgraphlib and pChart should appear in top Google search results. In my experience, phpgraphlib is developer-friendly and easy to use whereas JpGraph is more robust than others. pChart seems to be little bit outdated though they have updated their project.

JpGraph

phpgraphlib


 

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...