Friday, 27 November 2015

Add extra field in migration after creating table in Laravel 5.1

Hi Everybody,

In this blog we will discuss about how to add an extra field in migration after creating a table.

First time we create a table's migration & execute migration command. After this , we realize that we have to add a new field in database.

For this, we can modify table by this easy way.

Firstly run this command for create a new migration file.


php artisan make:migration add_fb_id_in_users_table

It will create a new file in migration file. Write in its up() function the following lines.

 Schema::table('users', function ($table) {
            $table->string('fb_id');
          });


and in down() function write the following lines:

Schema::table('users', function ($table) {
            $table->drop_column('fb_id');
          });


Make sure you put the same table name which you want to edit.

Now run migration command for this file.

php artisan migrate

Thanks.

Friday, 20 November 2015

How to crop image with jquery and php

Hi Everybody,

Today I am going to write this tutorial how to crop images with jQuery and PHP. I have used jCrop JavaScript library to perform this task with PHP its a very easy to implement and very useful for thumbnail generation. Hope you love this tutorial.

Requirement

Download the current version of Jcrop
Place the files on your web server so you can request them from your page
You also must have jQuery installed and included!

PHP Methods to save image:

crop.php

<?php
$targ_w = $targ_h = 150;
$jpeg_quality = 90;

$src = 'demo_files/pool.jpg';
$img_r = imagecreatefromjpeg($src);
$dst_r = ImageCreateTrueColor( $targ_w, $targ_h );

imagecopyresampled($dst_r,$img_r,0,0,$_POST['imgX1'],$_POST['imgY1'],
$targ_w,$targ_h,$_POST['imgWidth'],$_POST['imgHeight']);

header('Content-type: image/jpeg');
imagejpeg($dst_r,null,$jpeg_quality);
?>

This will simply show image on crop if you want to save that image in some directory then make changes in last two line as below.

//header('Content-type: image/jpeg');
imagejpeg($dst_r,PATH_TO_SAVE_IMAGE,$jpeg_quality);


Html JavaScript Configurations:

write below html after php code in crop.php

<!DOCTYPE html>
<html lang="en">
<head>
<title>Live Cropping Demo</title>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
<script src="js/jquery.min.js"></script>
<script src="js/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
<script type="text/javascript">
    $(function(){
    $(\'#cropbox\').Jcrop({
    aspectRatio: 1,
    onSelect: SetCoordinates,
//    minSize:[200,200], start minimum image size
//    maxSize:[200,200], max size should be...
    });
});

function SetCoordinates(c) {
    $('#imgX1').val(c.x);
    $('#imgY1').val(c.y);
    $('#imgWidth').val(c.w);
    $('#imgHeight').val(c.h);
    showPreview(c);
}

function showPreview(coords)
{
var rx = 100 / coords.w;
var ry = 100 / coords.h;

$('#preview').css({
width: Math.round(rx * 500) + 'px',
height: Math.round(ry * 370) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
</script>
</head>
<body>

<form action="crop.php" method="post">
<div class="modal-body text-center" >
<div><img src="demo_files/pool.jpg" id="cropbox"/></div>
<div style="width: 405px; height: 200px;" id="preview"><img src="demo_files/sago.jpg" style="display:'none'"/>
</div>
<div class="clearfix"></div>
<div class="modal-footer">
<input type="submit" id="btnCrop"  class="btn btn-success" value="Crop"/>
<input type="button" id="btnUpload" class="btn btn-failure" value="Cancel"/>
<input type="hidden" name="PicimgX1" id="PicimgX1" />
<input type="hidden" name="PicimgY1" id="PicimgY1" />
<input type="hidden" name="PicimgWidth" id="PicimgWidth" />
<input type="hidden" name="PicimgHeight" id="PicimgHeight" />
</div>
</form>
</body>
</html>

If you face any problem feel free to post your doubt or suggestion in comment box.
Thanks

Friday, 13 November 2015

Managing markers with the Same Coordinates in a Google Map

Hi Everybody,

In this blog we will discuss about managing multiple markers with the exact same location.
Google Maps API is an awesome tool, even though it has enough cons to hate it, it still has more pros to enjoy. In 3d revision of the API Google introduced new feature called clusters, which allows you to unite multiple markers in certain location and display a cluster instead, with a number of places it includes. Clicking on a cluster leads to zooming in, which reveals hidden markers and cluster disappears.

It works great, although there is an issue which is not covered by the library yet. When you have multiple markers with the exact same location, no matter how deep you zoom in, you won’t get a chance to see markers. If you remove clustering on a certain zoom levels (or remove it at all), you’ll see only one marker there(the top one), others will remain hidden underneath, since they stack on top of each other.

Solution


I’ve found couple of solutions out there in the web, but this one works best for me so far.

The idea is to iteratively check if existing markers match the coordinates of the new marker, if some of them do – than we add an offset to their coordinates.

I assume you already have a working application, which uses Google Maps API.

In your createMarker function add this code:

function createMarker(number, address, lat, lng) {
    var contentString = address;
    var newLat = lat + (Math.random() -.5) / 1500;// * (Math.random() * (max - min) + min);

    var newLng = lng + (Math.random() -.5) / 1500;// * (Math.random() * (max - min) + min);
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(newLat, newLng),
        map: map,
        icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld='+number+'|FF0000|000000'
    });

    google.maps.event.addListener(marker, 'click', function () {
        infowindow.setContent(contentString);
        infowindow.open(map, marker);
    });
    bounds.extend(marker.position);
}

(Math.random() -.5) / 1500 is about 100m, feel free to tweak an offset however you want.

    (Math.random() -.5) / 750 ~ 50m
    (Math.random() -.5) / 3000 ~ 200m

Note:-It’s not the cleanest solution, since your slightly corrupt data and some applications simply can’t afford it. I’d like to do this later on, but for a quick fix this solution will work just fine.

Friday, 6 November 2015

How to set custom image and label of marker on google map using jquery

Hi Everybody,

First of all wish you a very happy Diwali.

In this blog we will discuss how to set custom image and label of marker on google map using Jquery.

Html and css code

<html>
<head>
  html, body, #map-canvas {
        height: 100%;
        margin: 0px;
        padding: 0px
      }
   .labels {
     color: white;
     background-color: red;
     font-family: "Lucida Grande", "Arial", sans-serif;
     font-size: 10px;
     text-align: center;
     white-space: nowrap;
   }
</head>
    <title>Simple Map</title>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.1.9/src/markerwithlabel.js"></script>
  <body>
    <div id="map-canvas"></div>
  </body>
      

Jquery Code

  var mapOptions = {
    zoom: 8,
    center: new google.maps.LatLng(-34.397, 150.644)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

var marker = new MarkerWithLabel({
       position: new google.maps.LatLng(-34.397, 151.244),
       map: map,
       icon: "https://maps.gstatic.com/mapfiles/ms2/micons/marina.png",
       draggable: true,
       raiseOnDrag: true,
       labelContent: "1",
       labelAnchor: new google.maps.Point(-5, 35),
       labelClass: "labels", // the CSS class for the label
       labelInBackground: false
});

Output



If you face any problem in implement this, feel free to post your doubt in comment section.

Friday, 30 October 2015

How to calculate latitude and longitude for a given address and vise-versa in php

Hi Everybody,

In this blog we will discuss about how to calculate latitude and longitude for a given address and vise-versa in php.

Get latitude and longitude from a  given address(Geocode):-


        $address = "790 Castro St, Mountain View, CA";

        $formAddr = str_replace(' ','+',$address);

        $geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$formAddr.'&sensor=false');

        $output= json_decode($geocode);

        if(is_array($output )&& $output ['Status']['code']==200) {

                    $latitude = $output->results[0]->geometry->location->lat;

                    $longitude = $output->results[0]->geometry->location->lng;

       }

Get address from latitude and longitude(Reverse Geocode):-


       $lat = 37.3874353;
        $lng = -122.0835459;
        $revGeocode = file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$lng&sensor=false");
        $output = json_decode($revGeocode);
        if(is_array($output )&& $output ['Status']['code']==200) {
                    $address = $output->results[0]->formatted_address;
        }

Let me know if you face any problem in this.
Thanks.

Friday, 23 October 2015

How to change format of mobile number in US format (XXX) XXX-XXXX using Jquery

Hi Everybody,

In this blog we will discuss about how to change format of mobile number in US format (XXX) XXX-XXXX using Jquery.

For this we have to code our Html and Jquery, given below

Html Code


<form id="example-form" name="my-form">
    <label>Phone number:</label><br />
    <!-- I used an input type of text here so browsers like Chrome do not display the spin box -->
    <input id="phone-number" name="phone-number" type="text" maxlength="14" placeholder="(XXX) XXX-XXXX" /><br /><br />
    <input type="button" value="Submit" />
</form>

Jquery Code

$('#phone-number', '#example-form')

.keydown(function (e) {
var key = e.charCode || e.keyCode || 0;
$phone = $(this);

// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}

// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 || 
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});

Note:-After change mobile number in this format, best practice is this you have to save only 10 digit mobile number in your database(without (, ), and space).

For this if your server side script written in php then use below code to convert this US format mobile number to simple 10 digit number(for save in database) .

PHP Code

preg_replace("/[^0-9]/","",$mobile)

here $mobile is mobile input field you receive by Get or Post method after submit this form.

Thanks for read this blog, if you any question or suggestion please type in comment box.

Friday, 16 October 2015

Auto populate city and state using zip code(USA) in Laravel 5.1

Hi Everybody,

In this blog we will discuss how to auto populate USA city and state using zip code in Laravel 5.1.
For this we have to use google api for find city and state using zip code.

1. Routes


routes.php
Route::post('get/citystate', 'CityStateController@getCityState');

2. Controller

CityStateController.php

<?php

namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;

class AccountController extends Controller
{
 public function getCityState($blnUSA = true) {
        $data = Input::all();
        $zip = $data['zip'];
        $url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";
        $address_info = file_get_contents($url);
        $json = json_decode($address_info);
        $city = "";
        $state = "";
        $country = "";
        $arrReturn = array();
        if (count($json->results) > 0) {
            //break up the components
            $arrComponents = $json->results[0]->address_components;

            foreach($arrComponents as $index=>$component) {
                $type = $component->types[0];

                if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
                    $city = trim($component->long_name);
                }
                if ($state == "" && $type=="administrative_area_level_1") {
                    $state = trim($component->short_name);
                }
                if ($country == "" && $type=="country") {
                    $country = trim($component->short_name);

                    if ($blnUSA && $country!="US") {
                        $city = "";
                        $state = "";
                        break;
                    }
                }
                if ($city != "" && $state != "" && $country != "") {
                    //we're done
                    break;
                }
            }
        }
        return $arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);
    }

}

3. View

citystate.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery.js"></script>
<script>

function is_int(value){
    if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
        return true;
    } else {
        $("#city").val(''); /* Fill the data */
        $("#state").val('');
        return false;
    }
}

$("#zip").keyup(function() {
    $(".zip-error").hide(); /* In case they failed once before */
    var el = $(this);
    if ((el.val().length == 5) && (is_int(el.val()))) {
        $.ajax({
            url: '/get/citystate',
            type: "POST",
            data: "zip=" + el.val(),
            success: function(result, success) {
                $("#city").val(result['city']); /* Fill the data */
                $("#state").val(result['state']);
                if($("#city").val()=="" || $("#state").val()==""){
                    $(".zip-error").show(); /* Ruh row */
                }else{
                    $(".zip-error").hide(); /* In case they failed once before */
                }
            },
            error: function(result, success) {
                $(".zip-error").show(); /* Ruh row */
            }
        });
    }else{
        $(".zip-error").show(); /* Ruh row */
    }
});
</script>
</head>
<body>
<div class="container">
<div class="form-group">
<div class="row">
    <div class="col-md-4 mrgn_t_10">
        <input type="text" pattern="[0-9]*"  maxlength="5" class="form-control indent_zero" id="zip" placeholder="ZIP" name="zip" value=""><p class="zip-error" style="display: none">Not a real zip code.</p></div>

  <div class="col-md-4 mrgn_t_10">
  <input type="text" class="form-control indent_zero" id="city" placeholder="CITY" name="city" value=""></div>
  
  <div class="col-md-4 mrgn_t_10">
      <input type="text" class="form-control indent_zero" id="state" placeholder="STATE" name="state" value=""></div>
</div>
</div>
</div>
</body>
</html>

If you have any query you can post it in comment.
Thanks.