Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: JavaScript

Web Development and Design | Tutorial for Java, PHP, HTML, Javascript: JavaScript
Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

JavaScript Calculate Distance Between Two Addresses

JavaScript Calculate Distance Between Two Addresses

 
javascript distance matrix api

In Previous Demo We See How To Use Auto Complete Location, Now From That Example I create a Another Demo Example For How To Calculate Distance Between Two Address.

 ( Note  : Address Must Be Exist in Google Autocomplete Address)

Let's Start!.

First You Need Api Key.

For New Users They Don't Know How To Get Api Key Please Visit this Link to Get YOUR API Key   

Link :  Api Key Link   

Step 1 : I create a html page with two input fields.
Start Address : <input type="text" placeholder="Start Address" id="startaddress">
<br>
End Address : <input type="text" placeholder="End Address" id="endaddress">
Step 2 : Adding a JavaScript function for Adding Google Auto Complete Location Event on Input Fields. On Our Page Ready I call this Function.
	function AutoComplete() {
                 //=============Input Fields 1 and Select it========
               var input1 = document.getElementById('startaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input1);

                 //=============Input Fields 2 and Select it========
               var input2 = document.getElementById('endaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input2);
	}

//===========================Call The Autocomplete Function of Our Page Ready===============
	    google.maps.event.addDomListener(window, 'load', AutoComplete);
Step 3 : Adding Distance Matrix JavaScript Api for Calcuating Distance and Time Taken.
function getDistance(){

	  var distanceService = new google.maps.DistanceMatrixService();
        distanceService.getDistanceMatrix({
                origins: [document.getElementById('startaddress').value],
                destinations: [document.getElementById('endaddress').value],
                travelMode: "DRIVING",
                unitSystem: google.maps.UnitSystem.METRIC,
                durationInTraffic: true,
                avoidHighways: false,
                avoidTolls: false
            },
            function (response, status) {
                if (status !== google.maps.DistanceMatrixStatus.OK) {
                    console.log('Error:', status);
                } else {
                    console.log(response);
                   //=======================Our Text View Where i Display Distance and Time Values===================
                    document.getElementById('distance').innerHTML=response.rows[0].elements[0].distance.text;
                    document.getElementById('distance2').innerHTML=response.rows[0].elements[0].distance.value;
                    document.getElementById('time1').innerHTML=response.rows[0].elements[0].duration.text;
                    document.getElementById('time2').innerHTML=response.rows[0].elements[0].duration.value;

                }
            });
    }
Complete Example Code :
<!DOCTYPE html>
<html>
<head>
	<title>Google Place</title>
	<style type="text/css">
		#distance,#distance2,#time1,#time2{
			background: yellow;
width: 160px;
display: inline-block;
height: 15px;
		}
	</style>
</head>
<body>
Start Address : <input type="text" placeholder="Start Address" id="startaddress">
<br>
End Address : <input type="text" placeholder="End Address" id="endaddress">
<br>
Distance : - In Text Format Value <span id="distance"></span> Only Numeric Value in Metres <span id="distance2"></span>
<br>
Time : - In Text Format Value <span id="time1"></span> Only Numeric Value in Seconds <span id="time2"></span>

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&key= YOUR_API_KEY_HERE"></script>
<script type="text/javascript">

function getDistance(){
	
	  var distanceService = new google.maps.DistanceMatrixService();
        distanceService.getDistanceMatrix({
                origins: [document.getElementById('startaddress').value],
                destinations: [document.getElementById('endaddress').value],
                travelMode: "DRIVING",
                unitSystem: google.maps.UnitSystem.METRIC,
                durationInTraffic: true,
                avoidHighways: false,
                avoidTolls: false
            },
            function (response, status) {
                if (status !== google.maps.DistanceMatrixStatus.OK) {
                    console.log('Error:', status);
                } else {
                    console.log(response);
                    document.getElementById('distance').innerHTML=response.rows[0].elements[0].distance.text;
                    document.getElementById('distance2').innerHTML=response.rows[0].elements[0].distance.value;
                    document.getElementById('time1').innerHTML=response.rows[0].elements[0].duration.text;
                    document.getElementById('time2').innerHTML=response.rows[0].elements[0].duration.value;

                }
            });
    }


	function AutoComplete() {
                 //=============Input Fields 1 and Select it========
               var input1 = document.getElementById('startaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input1);

                 //=============Input Fields 2 and Select it========
               var input2 = document.getElementById('endaddress');
            //===============adding google location search event=================
            new google.maps.places.Autocomplete(input2);
	}

//======================Register Focus out Listener on Input Fields so we calculate distance and Time
document.getElementById("startaddress").addEventListener("focusout", getDistance);
document.getElementById("endaddress").addEventListener("focusout", getDistance);



//===========================Call The Autocomplete Function of Our Page Ready===============
	    google.maps.event.addDomListener(window, 'load', AutoComplete);

</script>
</body>
</html>

Note : I Calculating Time For DRIVING you can this values by WALKING,BICYCLING. Need To Change Here Only : - travelMode: "DRIVING",


 

Javascript Autocomplete Location Tutorial

Javascript Autocomplete Location Tutorial

JavaScript AutoComplete Location

Sometimes we need a autocomplete Textfield in Web Development where we enter only some values then address will show suggestion now we can implement this Types of Input fields.?

Lets Start Today!.

Step  1 : Visit Google Developer Console .



Google Maps Developer


Step 2 : Select  "Google Places API JavaScript Library"

     LinkGoogle Place Api
Google Place Library


Step 3 : Click on Get Key Then .


Google Api key

Step 4 : Create a new project

Google map project

Step 5 : Copy Key .

Api key

Now Let's Start Our Code . 

index.html

 
<!DOCTYPE html>
<html>
<head>
 <title>Google Place</title>
</head>
<body>
 <input type="text" placeholder="Searc place" id="autocomplete">

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&key=YOUR_API_KEY"></script>
<script type="text/javascript">

 //===================function for set input to google auto complete===================
 function AutoComplete() {
       var input = document.getElementById('autocomplete');
            new google.maps.places.Autocomplete(input);
 }

     //=============Call  function when our page load completes====================
     google.maps.event.addDomListener(window, 'load', AutoComplete);

</script>
</body>
</html>
 
 
autocomplete location input
 Thanks!
0

JavaScript Alternatives Method SetInterval and ClearInterval in Android

JavaScript Alternatives Method SetInterval and ClearInterval in Android

 
Javascript Setinterval

Hello Friends as We know Switching from Web Developers to Android we Stuck in Some Situation of Methods and How we use Such Methods.

Here i Give a simple Method of JavaScript Which is.

SetInterval = for Creating Task Multiple Times Until we Not Stop it.
Clearinterval = For Stoping SetInterval Task.

Lets Create a Demo page and see How it Works?


<!DOCTYPE html>
<html>
<head>
 <title>Set Interval and Clear interval in JavaScript</title>
</head>
<body>
<p>Example of Set interval and Clear interval</p>
<div id="data">
 
</div>
<script type="text/javascript">
 var myHtmlDiv=document.getElementById("data");
 var loop=0;
 var s=setInterval(function(){
  myHtmlDiv.innerHTML+='A Text After 1 seconds <br>';
 
  if(loop==10){
   //stop my setinterval function after 10 times if you want infinte times executing then remove the if condition means no clearinterval method
   clearInterval(s);
  }
  loop++;
 },1000);
</script>
</body>
</html>


Result :

Javascript Setinterval



Now Lets How We Use this Methods in Android?

So We Can use This Method Simply in Android by Using this Methods

 
      final Timer timer= new Timer();
        timer.scheduleAtFixedRate(new TimerTask(){
            @Override
            public void run(){
                testi++;
                if(testi==5){
                    Log.i("Complete","TaskComplete");
                    timer.cancel();
                }
                Log.i("tag", "A Kiss every 5 seconds");
            }
        },0,5000);
0

Jquery (js) validation For 10 Digit Mobile Numbers

Jquery (js) validation For 10 Digit Mobile Numbers




After Testing All Answer not getting success . Some times input take alpha character also.
Here is the last full working code With Only number input also keeping in mind backspace button key event for user if something number is incorrect.

html : 

<input name="phone" id="phone" placeholder="Mobile Number" class="form-control" type="number" required>

Js :

<script>
$("#phone").keydown(function(event) {
k=event.which;
if((k>=96 && k<=105) || k==8)
{
     if($(this).val().length==10)
     {
         if(k==8)
         {
             return true;
         }
         else
        {
             event.preventDefault();
             return false;

         }
    }
}
else
{
     event.preventDefault();
     return false;
}

});
</script>
7

Jquery selectors and basic part 1





Jquery selectors and basics part 1




In this tutorial i will show you how to use jquery selector to select element in DOM (Document Object Model which is our Html Document) and get the value of element ,text of element ,add new value or text or html element to Dom elements.

Let's Get Started.

Example 1 :  id selector
id selector is unique it select only one element in DOM . if we created multiple id element with same name then it will select only select first id element in DOM.

<html>
<head>
<script src=”js/jquery.min.js”></script>

<!--calling local jquery script →

</head>
<body>
<p>Hello</p>
<p id=”demo1”>Jquery</p>
<p id=”demo”>Here this text we will be change by using jquery selector and functions.</p>
<script>
$(document).ready(function(){


$(“#demo”).text(“This is new text “);

//Here # Represent the id and .text() method is used to set text in demo.

$(“#demo1”).html(“<span>World</span>”);

//since .text method only change text if we want to.add html elements inside selected elements then we will use .html() method.

});

//Every jquery function we will not call until our DOM is not ready (document).ready is a function we call our all function inside this .this function defines that our dom is ready now we are ready to call function inside (document).ready.

</script>
</body>
</html>


Example 2 : Class selector
Class is not unique so we can select all element having same class and change text or what we want.


<html>
<head>
<script src=”js/jquery.min.js”></script>

<!--calling local jquery script →

</head>
<body>
<p class=”mdemo”>Hello</p>
<p class=”demo”>Jquery</p>
<p class=”demo”>Here this text we will be change by using jquery selector and functions.</p>
<p class=”mdemo1”>Jquery Class also supports multiple class selector we can select multiple class in a single selector.</p>
<script>
$(document).ready(function(){


$(“.demo”).text(“This is new text “);

//Here (.) Represent the class and .text() method is used to set text in demo.

$(“.mdemo1,.mdemo”).text(“This text change by multiple class selector”);

//multiple class selector can be use by class names separated by comma (,)

});


</script>
</body>
</html>

Example 3 : Element Selector

Element selector selects all element in DOM .

<html>
<head>
<script src=”js/jquery.min.js”></script>

<!--calling local jquery script →

</head>
<body>
<p>Hello</p>
<p id=”demo1”>Jquery</p>
<p id=”demo”>Here this text we will be change by using jquery selector and functions.</p>
<h2>Jquery Multiple element selector </h2>
<span>This text all change using multiple selector</span>
<script>
$(document).ready(function(){


$(“p”).text(“This is new text added in all p tag elements “);

//Here p Represent the tag name  and .text() method is used to set text in demo.

$(“h2,span”).text(“This is multiple text selector “);

//This is multiple jquery selector where elements are separated by comma (,).

});

</script>
</body>
</html>


Example 4 : first last first-child selector

:first - select only first element in dom
:last - select only last element in dom
:first-child - select all elements of first child elements

<script src="js/jquery.min.js"></script>

<!--calling local jquery script -->
</head>

<body>

<br />


<div id="demo1">
Jquery</div>
<div id="demo">
Here this text we will be change by using jquery selector and functions.</div>
<div>

Hello i am first-child selector element

This text not change<br />


</div>
<div>

Hello i am first-child selector element again<br />


This text not change<br />


</div>
<script>

$(document).ready(function(){

$("p:first").text("This is new text added in first p tag element ");

$("p:last").text("this is text added in last p elements");

$("div:first-child").text("This is first child selector first child in div element");
//Here p Represent the tag name  and .text() method is used to set text in demo.


});

</script>
4

PHP , Javascript (JS) Array Basics Create And Print

 
PHP , Javascript (JS) Array Basics Create And Print 


What is Array?

Array is a special type of variable which stores multiple value in a single variable by its different index number.

Graphical Array value Storage View.


How To Declare or Create in PHP and Javascript?

In PHP – $a=array(1,2,3,4,5);
PHP Create Array by Keyword array and value inside its parenthesis seperated by comma (,).
Here We can Access value of a by using its its like if we use $a[0] we get
value equal to 1. Since Zero index value is 1.

In Javascript – var a=[1,2,3,4,5];
Javascript Creates Array By using Square Bracket and value separated by comma (,)
Here We can Access value of a by using its its like if we use a[0] we get
value equal to 1. Since Zero index value is 1.

Example 1. How to Decalare and get value of array .

IN PHP

<?php
$a = array(1,2,3,4); //Creating array

//printing values of array using simple method 1
echo "Index 0 Value is" . $a[0]."</br>";
echo "Index 1 Value is" . $a[1]."</br>";
echo "Index 2 Value is" . $a[2];

//printing values of array using for loop method 2

$count=count($a); //Here Count Function Counts The Array Of Length

for($i=0;$i<$count;$i++)
{
echo "Index ".$i." Value is" . $a[$i]."</br>";
}

//printing values of array using foreach loop method 2

foreach($a as $key => $value)
{
echo "Index ".$key." Value is" . $value."</br>";
}
?>

IN Javascript

<html>
<body>
</body>
<script>
var a = [1,2,3,4]; //Creating array

//printing values of array using simple method 1
console.log( "Index 0 Value is" +a[0]);
console.log( "Index 1 Value is" +a[1]);
console.log( "Index 2 Value is" +a[2]);

//printing values of array using for loop method 2

var count=a.length; //Here .length Function Counts The Array Of Length

for(var i=0;i<count;i++)
{
console.log( "Index "+i+" Value is" +a[i]);
}

//printing values of array using foreach loop method 2

for(var key in a)
{
console.log("Index "+key+" Value is" +a[key]);
}
</script>
</html>

Thank You
9

Javascript Basics


Javascript Basics



Javascript is a client side popular language used in many things like in our website, Hybrid Mobile Application, etc.

In Earlier Javascript is used only in websites But now a days javascript is very and used in many devices.

What Javascript Can Do?

Javascript in Web Can Change HTML tags ,CSS Style, HTML Attributes, HTML Contents, HIDE Elements, Show Elements.

Javascript in Mobile Application Can Call Native Java Functions, Swift function , C# functions and Methods of different programing languages.

Where to Put javascript Codes?

Javascript can be Call in web Page by two methods : -

1. By using Internally
Javascript Codes Must be Inside in Script tag

Example :-

<html>
<head>
<!--Adding javascript in our page-->
<script>
alert(“Calling javascript”); //calling alert function
</script>
</head>
<body>
<h2>Javascript Basics</h2>
</body>
</html>

2.By using Externally

Example :-

page.html

<html>
<head>
<!--Adding javascript in our page-->
<script src=”script.js”></script>
</head>
<body>
<h2>Javascript Basics</h2>
</body>
</html>
script.js

alert(“Calling javascript”); //calling alert function


Note :- Javascript is must different from java

Javascript Outputs

JavaScript can display data in different Such Ways :
  • Writing into an alert box, using alert().
  • Writing into the HTML output using document.write().
  • Writing into an HTML element, using innerHTML.
  • Writing into the browser console, using console.log().


Using alert
<html>
<body>
<h2>Javascript basics</h2>

<script>
alert(Hello Js);
</script>

</body>
</html>


Using document.write
<html>
<body>
<h2>Javascript basics</h2>

<script>
document.write(Hello javascript);
</script>

</body>
</html>

Using document.write
<html>
<body>
<h2>Javascript basics</h2>

<script>
document.write(Hello javascript);
</script>

</body>
</html>

Using innerHTML

<html>
<body>

<h2>Javascript basics</h2>

<p id="display"></p>

<script>
document.getElementById("display").innerHTML = hello javascript;

//here document.getElementById is a selector which select the html elements by using id and change the text inside this tag
</script>

</body>
</html>

Using console.log

<html>
<body>

<h2>Javascript basics</h2>

<script>
console.log(hello javascript);

//open your browser console by pressing F12 Key

</script>

<
/body>
<
/html>

Javascript Syntax

Javascript Statements Must be End With (;) Semicolon

Javascript Use var keyword to Store and Declare variable

Javascript Concatinate using +

Example : var a=”hello”+” ”+”Js”

Javascript Comments
//This is single line comments
/*This is Multi Line comments */

Thank You
1

Javascript Functions


Javascript Functions


Learn How To Create Functions in Javascript.
Javascript Function are of Four Types :-

a. No Argument With No Return Type
b.No Argument With Return Type
c.Argument With No Return type
d.Argument With return Type

Now Lets Start.

Example of function :-

function hello() // create function hello
{
//body and scope of function
}


1. No Argument With No Return Type

Code : -

<html>
<head>
<script>

function hello() // Create a function hello with no argument
{
console.log( “Calling Function hello”);
}

hello(); // Calling Function hello
// Output : Calling Function Hello in Your Console By Clicking On F12
</script>
</head>
<body>
<h2>Javascript Functions Tutorial</h2>
</body>
</html>

2. No Argument With Return Type

Code : -

<html>
<head>
<script>

function hello() // Create a function hello with no argument
{
var str=“Calling Function hello”;
return str; // Return Value
}

var srt1=hello(); // Calling Function hello Here We Use Echo To Print
console.log(str1); //Because it Only Return Value Not Print it
// Output : Calling Function Hello
</script>
</head>
<body>
<h2>Javascript Functions Tutorial</h2>
</body>
</html>

3. Argument With No Return Type

Code : -

<html>
<head>
<script>

function hello(a) // Create a function hello with argument
{
console.log(a); // Print Value
}

var ab=”hello test”;

hello(ab); // Calling Function hello With Parameter ab
// Output : hello test
</script>
</head>
<body>
<h2>Javascript Functions Tutorial</h2>
</body>
</html>

4. Argument With Return Type

Code : -

<html>
<head>
<script>

function hello(a) // Create a function hello with argument
{
var a=a.toLocaleUpperCase(a);
return a; // Return Value
}

var ab=”hello test”;

var out=hello(ab); // Calling Function hello With Parameter ab
console.log(out); // Output : Hello test Here first letter of word is capital
</script>
</head>
<body>
<h2>Javascript Functions Tutorial</h2>
</body>
</html>
Thank You
0