Thursday, July 19, 2012

How to Autocomplete world Cities

Demo

[sourcecode language="html"]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<link href="public/css/jquery.autocomplete.css" rel="stylesheet">
<script src="public/js/jquery.js"></script>
<script type="text/javascript" src="public/js/jquery.autocomplete.pack.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$("#city").autocomplete("http://ws.geonames.org/searchJSON", {
dataType: 'jsonp',
parse: function(data) {
var rows = new Array();
data = data.geonames;
for(var i=0; i<data.length; i++){
rows[i] = { data:data[i], value:data[i].name, result:data[i].name };
}
return rows;
},
formatItem: function(row, i, n) {
return row.name + ', ' + row.adminCode1;
},
extraParams: {
// geonames doesn't support q and limit, which are the autocomplete plugin defaults, so let's blank them out.
q: '',
limit: '',
featureClass: 'P',
style: 'full',
maxRows: 50,
name_startsWith: function () { return $("#city").val() }
},
max: 50
});

});
</script>
</head>

<body>
<form action="search.php" method="get" id="search_form">
What
<input type="text"  name="q" id="q">
Where
<input type="text"   name="city" id="city">
<button type="submit"  name="btnSearch" id="btnSearch">Search</button>
</form>
</body>
</html>


[/sourcecode]

Tuesday, July 17, 2012

Reverse Geocode with Google Map - PHP

[sourcecode language="php"]

<?php
// Get STATE from Google GeoData
function reverse_geocode($address) {
$address = str_replace(" ", "+", "$address");
$url = "http://maps.google.com/maps/api/geocode/json?

address=$address&sensor=false";
$result = file_get_contents("$url");
$json = json_decode($result);
foreach ($json->results as $result)
{
foreach($result->address_components as $addressPart) {
if((in_array('locality', $addressPart->types)) &&

(in_array('political', $addressPart->types)))
$city = $addressPart->long_name;
else if((in_array('administrative_area_level_1',

$addressPart->types)) && (in_array('political', $addressPart->types)))
$state = $addressPart->long_name;
else if((in_array('country', $addressPart->types)) &&

(in_array('political', $addressPart->types)))
$country = $addressPart->long_name;
}
}

if(($city != '') && ($state != '') && ($country != ''))
$address = $city.', '.$state.', '.$country;
else if(($city != '') && ($state != ''))
$address = $city.', '.$state;
else if(($state != '') && ($country != ''))
$address = $state.', '.$country;
else if($country != '')
$address = $country;


return "$country/$state/$city";
}


$myLocation = reverse_geocode("Arboretum Rd, Stanford, CA 94305, USA");
echo "$myLocation";

?>
[/sourcecode]

Reverse Geocode using Google Map - JavaScript

[sourcecode language="html"]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function reverse()
{
var lat = parseFloat(7.4706);
var lng = parseFloat( 80.0456);
var latlng = new google.maps.LatLng(lat, lng);
geocoder = geocoder = new google.maps.Geocoder();
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
if (results[1]) {
var indice=0;
for (var j=0; j<results.length; j++)
{
if (results[j].types[0]=='locality')
{
indice=j;
break;
}
}

console.log(results[j]);
for (var i=0; i<results[j].address_components.length; i++)
{
if (results[j].address_components[i].types[0] == "locality") {
//this is the object you are looking for
city = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "administrative_area_level_1") {
//this is the object you are looking for
region = results[j].address_components[i];
}
if (results[j].address_components[i].types[0] == "country") {
//this is the object you are looking for
country = results[j].address_components[i];
}
}


alert(city.long_name + " || " + region.long_name + " || " + country.short_name)


}


} else {
alert("No results found");
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
</script>
</head>

<body onLoad="reverse()">

</body>
</html>
[/sourcecode]

 

Monday, July 9, 2012

Display Information Window in Google Map

Demo

[sourcecode language="html"]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>codezone4 - Google Maps Simple Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

function initialize()
{
var latlng = new google.maps.LatLng(9.931544168615512,76.27632894178791);
var opt =
{
center:latlng,
zoom:10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableAutoPan:false,
navigationControl:true,
navigationControlOptions: {style:google.maps.NavigationControlStyle.SMALL },
mapTypeControl:true,
mapTypeControlOptions: {style:google.maps.MapTypeControlStyle.DROPDOWN_MENU}
};
var map = new google.maps.Map(document.getElementById("map"),opt);
var marker= new google.maps.Marker({
position: new google.maps.LatLng(6.9167,79.8333),
title: "codeZone4 Base",
clickable: true,
map: map
});


var infowindow = new google.maps.InfoWindow(
{
content: " We are here! "

});


google.maps.event.addListener(marker,'click',function(){
infowindow.open(map,marker);
});



}

</script>
</head>
<body onload="initialize()">
<div id="map" style="width:400px;height:300px;margin-top:10px;"></div>
</body>
</html>
[/sourcecode]

Wednesday, July 4, 2012

How to get innerHTML in a DIV with DOM

We need to get the content inside DIV container with the ID of test in get_geo_location.php.
content.php

[sourcecode language="html"]
<html>
<head></head>
<body>
<div id="test"><p>I like blogging</p></div>
</body>
</html>
[/sourcecode]

Output should be :  <p>I like blogging</p>

[sourcecode language="php"]
$content="content.php";
$source=new DOMdocument();
$source->loadHTMLFile($content);
$path=new DOMXpath($source);
$dom=$path->query("*/div[@id='test']");
if (!$dom==0) {
foreach ($dom as $dom2) {

$tmp_doc = new DOMDocument();
$tmp_doc->appendChild($tmp_doc->importNode($dom2,true));
$innerHTML .= $tmp_doc->saveHTML();
echo $innerHTML;
}
}
[/sourcecode]

Geocode IP Address with popular web services

hostip.info

using json API

[sourcecode language="php"]
$pageContent = file_get_contents('http://api.hostip.info/get_json.php?ip=70.85.226.228' );
$parsedJson  = json_decode($pageContent);
echo $parsedJson->country_name;
echo $parsedJson->city;
[/sourcecode]
[sourcecode language="php"]
$ip = '203.153.223.84';
$sturl = 'http://api.hostip.info/get_html.php?ip='.$ip;
$ch = curl_init($sturl);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_TIMEOUT,10);
$res = curl_exec($ch);
$resinfo = curl_getinfo($ch);
curl_close($ch);
preg_match('/City: ([a-zA-Z].+[a-zA-Z]+)/', $res, $r);
preg_match('/ \(([A-Z][A-Z])/', $res, $s);
$city = $r[1];
$country = $s[1];

echo $city;
echo $country;
[/sourcecode]

freegeoip.net

[sourcecode language="php"]
$pageContent = file_get_contents('http://freegeoip.net/json/70.85.226.228' );
$parsedJson  = json_decode($pageContent);
echo $parsedJson->city;
echo $parsedJson->region_code;
echo $parsedJson->region_name;
echo $parsedJson->metrocode;
echo $parsedJson->zipcode;
echo $parsedJson->country_name;
echo $parsedJson->country_code;
echo $parsedJson->ip;
echo $parsedJson->latitude;
echo $parsedJson->longitude;
[/sourcecode]

Geoips.com

[sourcecode language="php"]
<?php
function freegeoip_locate($ip) {
$url = "http://api.geoips.com/ip/".$ip."/key/<<your key>>/output/json/timezone/true/hostname/true";
$geo = json_decode(file_get_contents($url), true);
return $geo;
}

$geo = freegeoip_locate($_SERVER['REMOTE_ADDR']);

echo "ip: " . $geo['ip'];
echo "host name: ". $geo['hostname'];
echo "owner: ". $geo['owner'];
echo "continent_name: ". $geo['continent_name'];
echo "continent_code: ". $geo['continent_code'];
echo "country_name: ". $geo['country_name'];
echo "country_code: ". $geo['country_code'];
echo "region_name: ". $geo['region_name'];
echo "region_code: ". $geo['region_code'];
echo "county_name: ". $geo['county_name'];
echo "city_name: ". $geo['city_name'];
echo "latitude: ". $geo['latitude'];
echo "longitude: ". $geo['longitude'];
echo "timezone: ". $geo['timezone'];
?>
[/sourcecode]

Send JSON via AJAX request

This tutorial demonstrates how to make an AJAX request in javaScript and process JSON in PHP. The data sent by the HTTP Post request is used to create a session after JSON decoding finished.

For this, we need following .js file.

https://github.com/douglascrockford/JSON-js/blob/master/json2.js

[sourcecode language="javascript"]
function abc()
{
var jsonObj = {"lat": 56  ,"long": 78  ,"city": 'Wohiyo' };

// Lets convert our JSON object
var postData = JSON.stringify(jsonObj);

// Lets put our stringified json into a variable for posting
var postArray = {json:postData};

$.ajax({
type: 'POST',
url: "Server.php",
data: postArray,
success: function(data){
alert("success");
}
});
}
[/sourcecode]

Server.php

[sourcecode language="php"]
<?php
session_start();
header("Expires: Mon, 26 Jul 2000 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

if(isset($_POST["json"])){
$json = stripslashes($_POST["json"]);
$output = json_decode($json);

$_SESSION['city'] = $output->{'city'};
}
?>

[/sourcecode]

complete source code

[sourcecode language="html"]
<?php session_start();?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script src="jquery-1.7.js"></script>
<script src="json2.js"></script>

<script type="text/javascript">
function abc()
{
var jsonObj = {"lat": 56  ,"long": 78  ,"city": 'Wohiyo' };

// Lets convert our JSON object
var postData = JSON.stringify(jsonObj);

// Lets put our stringified json into a variable for posting
var postArray = {json:postData};

$.ajax({
type: 'POST',
url: "Server.php",
data: postArray,
success: function(data){
alert("success");
}
});
}
</script>
</head>

<body onLoad="abc()">
<?php echo $_SESSION['city'];?>
</body>
</html>
[/sourcecode]

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...