Thursday, September 22, 2022

Map dengan Javascript

 <html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

</head>

<body>

    Latitude:

    <input type="text" id="txtLatitude" value="18.92488028662047" />

    Latitude:

    <input type="text" id="txtLongitude" value="72.8232192993164" />

    <input type="button" value="Get Address" onclick="GetAddress()" />

    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

    <script type="text/javascript">

        function GetAddress() {

            var lat = parseFloat(document.getElementById("txtLatitude").value);

            var lng = parseFloat(document.getElementById("txtLongitude").value);

            var latlng = new google.maps.LatLng(lat, lng);

            var geocoder = geocoder = new google.maps.Geocoder();

            geocoder.geocode({ 'latLng': latlng }, function (results, status) {

                if (status == google.maps.GeocoderStatus.OK) {

                    if (results[1]) {

                        alert("Location: " + results[1].formatted_address);

                    }

                }

            });

        }

    </script>

</body>

</html>

Saturday, September 17, 2022

Orientasasi Layar Javascript

 <script>

function checkOr(){

    if (window.matchMedia("(orientation:portrait)").matches) {

      console.log('portrait ' + window.orientation);

    } else {

      console.log('landscape '+ window.orientation);

    }

}

window.addEventListener("orientationchange", checkOr);

</script>

Kirim Data to CSV dengan PHP

 <?php

$file = file_get_contents('urlnya', true);

$decode = json_decode($file);

$f = fopen("data.csv", "w");

for($i=0; $i < count($decode) ; $i ++){

$lineData = array($decode[$i]->last_name,$decode[$i]->first_name,$decode[$i]->email);

fputcsv($f, $lineData, ",");

}

?>


forEach , Map, For dalam javascript

 1. for javascript

<script>

  fetch('http://api.rifhandi.com/kuliner/product.php')

  .then(response => response.json())

  .then(data => {


                      let output = '<h2>Lists of Produk</h2>';

                        output += '<ul>';

                          for(let i=0 ; i < data.length; i++){

                            output += `<li> ${data[i].title}</li>`;

                          }

                        output += '</ul>';

              document.getElementById("response").innerHTML = output;


  });

</script>

<div id="response"></div>

2.  map javascript

<script>

  fetch('http://api.rifhandi.com/kuliner/product.php')

  .then(response => response.json())

  .then(data => {


                      let output = '<h2>Lists of Produk</h2>';

                        output += '<ul>';

                          data.map(function(item, index){

                            output += `<li> ${item.title}</li>`;

                          });

                        output += '</ul>';

              document.getElementById("response").innerHTML = output;


  });

</script>

<div id="response"></div> 

3. forEach Javascript

<script>

  fetch('http://api.rifhandi.com/kuliner/product.php')

  .then(response => response.json())

  .then(data => {


                      let output = '<h2>Lists of Produk</h2>';

                        output += '<ul>';

                          data.forEach(function(item, index){

                            output += `<li> ${item.title}</li>`;

                          });

                        output += '</ul>';

              document.getElementById("response").innerHTML = output;


  });

</script>

<div id="response"></div> 

Module Javacript

 1. HTML (index.html)

<!DOCTYPE html>

<html>

<head>

<title>Test</title>

</head>

<body>

<span id="hasil"></span>

<script type="module" src="./src/module.js"></script>

</body>

</html>

2.  Buat Folder src di dalam projek kita

3. module.js

    import { kali } from './kali.js'

    const tampil = kali(10,3);

    document.getElementById("hasil").innerHTML=tampil; 

4. kali.js

export function kali (a,b){

return a * b;

}


Membuat Meme dengan javascript

 1. Javscript

          let image;

function preview(){

    let im = document.getElementById("foto")

    let imgUrl = URL.createObjectURL(im.files[0]);

    image = new Image();

    image.src= imgUrl;

    image.addEventListener("load",()=>{

      updateImage(image);    

    }, {once:true})

  }


function updateImage(img){

  let canvas = document.getElementById('card_canvas');

  let ctx = canvas.getContext('2d');

  let w = img.width;

  let h = img.height;

  canvas.width = 300;

  canvas.height = 300;

  ctx.drawImage(img, 0, 0 , 300, 300);

  // var imgData = ctx.canvas.toDataURL();  

            // silahkan di custom sendiri 

}


2. HTML

<input type="file" id="foto" onchange="preview()" />

<hr>

<canvas id="card_canvas"></canvas>

3 Helper javascript

function calc_image_size(video) {
    let y = 1;
    if (video.endsWith('==')) {
        y = 2
    }
    let x_size = (video.length * (3 / 4)) - y
    return Math.round(x_size / 1024)
}



function getBase64(file) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}



Base64 to Blob Javascript + Check Size base64 Javascript

1.    const b64toBlob = (b64Data, contentType='', sliceSize=512) => {

  const byteCharacters = atob(b64Data);

  const byteArrays = [];

  for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {

    const slice = byteCharacters.slice(offset, offset + sliceSize);

    const byteNumbers = new Array(slice.length);

    for (let i = 0; i < slice.length; i++) {

      byteNumbers[i] = slice.charCodeAt(i);

    }

    const byteArray = new Uint8Array(byteNumbers);

    byteArrays.push(byteArray);

  }

  const blob = new Blob(byteArrays, {type: contentType});

  return blob;

}


            " call functional => b64toBlob(b64Data,contentType) "


2. Check size base64 with javascript (Kilo Byte)

            function calc_image_size(image) {

    let y = 1;

    if (image.endsWith('==')) {

        y = 2

    }

    const x_size = (image.length * (3 / 4)) - y

    return Math.round(x_size / 1024)

}

    " call functional => calc_image_size(b64Data) "

Canvas Menggunakan Javascript

 1. Html

<canvas width="250" height="250" style="border:1px solid #d3d3d3;" id="myCanvas"></canvas>

<hr />

<button onclick="draw()">Draw</button> | 

<button onclick="save()">Save</button>


2. Javscript

        <script type="text/javascript">

var img = new Image();

img.src="sample.jpeg";

function draw () {

  var c = document.getElementById("myCanvas");

  var ctx = c.getContext("2d");

  console.log(img.width);

  console.log(img.height);

  ctx.drawImage(img, 0, 0, 250, 250);

};

function save () {

  var c = document.getElementById("myCanvas");

  var ctx = c.getContext("2d");

  var imgData = ctx.canvas.toDataURL();

  

  var formdata = new FormData();

formdata.append( "foto", imgData );

var ajax = new XMLHttpRequest();

ajax.open( "POST", "parse.php" );

ajax.onreadystatechange = function() {

if(ajax.readyState == 4 && ajax.status == 200) {

if(ajax.responseText == "success"){

console.log(ajax.responseText)

} else {

console.log(ajax.responseText)

}

}

}

ajax.send( formdata );



};

</script>


3. PHP

<?php

$photo = $_POST['foto'];

if(!empty($photo)){

$image_no="5";

$image = explode(",", $photo);

$path = "uploads/".$image_no.".png";

$status = file_put_contents($path,base64_decode($image[1]));

if($status){

echo "Successfully Uploaded";

}else{

echo "Upload failed";

}

}else{

echo "Aduuh Gagal";

}


?>




Menggunakan FILEREADER Javascript


 

1. HTML

<input type="file" id="foto" onchange="preview(event)" />

2. Javascript

<script type="text/javascript">

function preview(event){

  const reader = new FileReader();

  reader.addEventListener("load",()=>{

      console.log(reader.result);

      // function upload(reader.result) => jika ingin menggunakan data base64 di fungsional lainnya.

  })

  reader.readAsDataURL(event.target.files[0]);

}

</script> 

Set Cookie dan Remove Cookie dengan php vanilla.js

< html lang = "en" > < head >     < meta charset = "UTF-8" >     < meta name = "viewport...