Wednesday, 22 February 2023

Get distance between address in kilometer

 <?php 

        $addressFrom = 'Bus Stand, 3MQQ+R3Q, Enasan, Gujarat 382330';
        $addressTo   = 'RAJKOT BUS PORT, bus port shop, 48, Kanak Rd, Karanpara, Rajkot, Gujarat 360001';
 ?>
<span>{{ getDistance($addressFrom, $addressTo, "K") }}</span>

*************************************************************

<?php
function getDistance($addressFrom, $addressTo, $unit = 'K')
{
    // Google API key
    $apiKey = 'xxxxxxxx';
    
    // Change address format
    $formattedAddrFrom    = str_replace(' ', '+', $addressFrom);
    $formattedAddrTo     = str_replace(' ', '+', $addressTo);
    
    // Geocoding API request with start address
    $geocodeFrom = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddrFrom.'&sensor=false&key='.$apiKey);
    $outputFrom = json_decode($geocodeFrom);
    if(!empty($outputFrom->error_message)){
        return $outputFrom->error_message;
    }
    
    // Geocoding API request with end address
    $geocodeTo = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address='.$formattedAddrTo.'&sensor=false&key='.$apiKey);
    $outputTo = json_decode($geocodeTo);
    if(!empty($outputTo->error_message)){
        return $outputTo->error_message;
    }
    
    // Get latitude and longitude from the geodata
    $latitudeFrom    = $outputFrom->results[0]->geometry->location->lat;
    $longitudeFrom    = $outputFrom->results[0]->geometry->location->lng;
    $latitudeTo        = $outputTo->results[0]->geometry->location->lat;
    $longitudeTo    = $outputTo->results[0]->geometry->location->lng;
    
    // Calculate distance between latitude and longitude
    $theta    = $longitudeFrom - $longitudeTo;
    $dist    = sin(deg2rad($latitudeFrom)) * sin(deg2rad($latitudeTo)) +  cos(deg2rad($latitudeFrom)) * cos(deg2rad($latitudeTo)) * cos(deg2rad($theta));
    $dist    = acos($dist);
    $dist    = rad2deg($dist);
    $miles    = $dist * 60 * 1.1515;
    
    // Convert unit and return distance
    $unit = strtoupper($unit);
    if($unit == "K"){
        return round($miles * 1.609344, 2).' km';
    }elseif($unit == "M"){
        return round($miles * 1609.344, 2).' meters';
    }else{
        return round($miles, 2).' miles';
    }
}
?> 

 

Tuesday, 21 February 2023

Google autosuggest address

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
    <!-- Fonts -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
        integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.6.3.min.js"
        integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.min.js"></script>
    <style> .pac-container.pac-logo { z-index: 9999; }  </style>
</head>
<body>
    <div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
        <div class="grid grid-cols-1 md:grid-cols-2">
            <div class="container mt-2">
                <div class="row">
                    <div class="col-md-6  m-auto">
                        <div class="card shadow">
                            <div class="card-body">
                                <!-- Trigger the modal with a button -->
                                <input type="text" name="currentlocation" id="currentlocation"
                                    class="form-control col-md-6" placeholder="Select Location" readonly
                                    data-toggle="modal" data-target="#myModal">
                                <!-- Modal -->
                                <div id="myModal" class="modal fade" role="dialog">
                                    <div class="modal-dialog col-md-5 modal-sm">

                                        <!-- Modal content-->
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <button type="button" class="close"
                                                    data-dismiss="modal">&times;</button>
                                                <h4 class="modal-title">Search Location</h4>
                                            </div>
                                            <div class="modal-body">
                                                <div class="card-body">
                                                    <div class="form-group">
                                                        <input type="text" name="autocomplete" id="autocomplete"
                                                            class="form-control" placeholder="Enter a city">
                                                    </div>
                                                    <div class="form-group" id="lat_area">
                                                        <label for="latitude"> Latitude </label>
                                                        <input type="text" name="latitude" id="latitude"
                                                            class="form-control">
                                                    </div>
                                                    <div class="form-group" id="long_area">
                                                        <label for="latitude"> Longitude </label>
                                                        <input type="text" name="longitude" id="longitude"
                                                            class="form-control">
                                                    </div>
                                                    <br>
                                                    <div id="ucurrentlocation">Use Current Location</div>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-default"
                                                    data-dismiss="modal">Close</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"
                integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"
                crossorigin="anonymous"></script>
            <script
                src="https://maps.google.com/maps/api/js?key=xxxxx&libraries=places&callback=initAutocomplete"
                type="text/javascript"></script>
            <script src="address.js"></script>
        </div>
    </div>
    <script> $("#ucurrentlocation").click(function(event) { getLocation(); });

    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
            div.innerHTML = "The Browser Does not Support Geolocation";
        }
    }

    function showPosition(position) {
        var location = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + position.coords.latitude + "," +
            position.coords.longitude + "&key=xxxxx"
        $.get(location, function(data) {
            $("#currentlocation").val(data.results[0].formatted_address);
        });
    }

    function showError(error) {
        if (error.PERMISSION_DENIED) {
            div.innerHTML = "The User have denied the request for Geolocation.";
        }
    }
    getLocation();
    </script>
</body>
</html>

*************************************************************

address.js            

$(document).ready(function () {
    $("#lat_area").addClass("d-none");
    $("#long_area").addClass("d-none");
});
google.maps.event.addDomListener(window, "load", initialize);
function initialize() {
    var input = document.getElementById("autocomplete");
    var autocomplete = new google.maps.places.Autocomplete(input);
    autocomplete.addListener("place_changed", function () {
        var place = autocomplete.getPlace();      
        $("#latitude").val(place.geometry["location"].lat());
        $("#longitude").val(place.geometry["location"].lng());
        // --------- show lat and long ---------------
        $("#lat_area").removeClass("d-none");
        $("#long_area").removeClass("d-none");
        var newadd =$("#autocomplete").val();
        $("#currentlocation").val(newadd);
        $(".close").click();
    });
}

Sunday, 19 February 2023

Create new scratch card.

 Html

<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Scratch Card</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
    <div class="container">
      <div class="base">
        <h4>You Won</h4>
        <h3>$20</h3>
      </div>
      <canvas id="scratch" width="200" height="200"></canvas>
    </div>
    <!-- Script -->
    <script src="script.js"></script>
  </body>
</html>


Scriptjs

let canvas = document.getElementById("scratch");
let context = canvas.getContext("2d");

const init = () => {
  let gradientColor = context.createLinearGradient(0, 0, 135, 135);
  gradientColor.addColorStop(0, "#c3a3f1");
  gradientColor.addColorStop(1, "#6414e9");
  context.fillStyle = gradientColor;
  context.fillRect(0, 0, 200, 200);
};

//initially mouse X and mouse Y positions are 0
let mouseX = 0;
let mouseY = 0;
let isDragged = false;

//Events for touch and mouse
let events = {
  mouse: {
    down: "mousedown",
    move: "mousemove",
    up: "mouseup",
  },
  touch: {
    down: "touchstart",
    move: "touchmove",
    up: "touchend",
  },
};

let deviceType = "";

//Detech touch device
const isTouchDevice = () => {
  try {
    //We try to create TouchEvent. It would fail for desktops 
and throw error.
    document.createEvent("TouchEvent");
    deviceType = "touch";
    return true;
  } catch (e) {
    deviceType = "mouse";
    return false;
  }
};

//Get left and top of canvas
let rectLeft = canvas.getBoundingClientRect().left;
let rectTop = canvas.getBoundingClientRect().top;

//Exact x and y position of mouse/touch
const getXY = (e) => {
  mouseX = (!isTouchDevice() ? e.pageX : e.touches[0].pageX) - rectLeft;
  mouseY = (!isTouchDevice() ? e.pageY : e.touches[0].pageY) - rectTop;
};

isTouchDevice();
//Start Scratch
canvas.addEventListener(events[deviceType].down, (event) => {
  isDragged = true;
  //Get x and y position
  getXY(event);
  scratch(mouseX, mouseY);
});

//mousemove/touchmove
canvas.addEventListener(events[deviceType].move, (event) => {
  if (!isTouchDevice()) {
    event.preventDefault();
  }
  if (isDragged) {
    getXY(event);
    scratch(mouseX, mouseY);
  }
});

//stop drawing
canvas.addEventListener(events[deviceType].up, () => {
  isDragged = false;
});

//If mouse leaves the square
canvas.addEventListener("mouseleave", () => {
  isDragged = false;
});

const scratch = (x, y) => {
  //destination-out draws new shapes behind the existing canvas content
  context.globalCompositeOperation = "destination-out";
  context.beginPath();
  //arc makes circle - x,y,radius,start angle,end angle
  context.arc(x, y, 12, 0, 2 * Math.PI);
  context.fill();
};

window.onload = init();


style.css

* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
  }
  body {
    height: 50vh;    
  }
  .container {
    width: 20em;
    height: 20em;
    background-color: #f5f5f5;
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    border-radius: 0.6em;
  }
  .base,
  #scratch {
    height: 200px;
    width: 200px;
    position: absolute;
    transform: translate(-50%, -50%);
    top: 50%;
    left: 50%;
    text-align: center;
    cursor: pointer;
    border-radius: 1.3em;
  }
  .base {
    background-color: #ffffff;
    font-family: "Poppins", sans-serif;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    box-shadow: 0 1.2em 2.5em rgba(17, 12, 99, 0.15);
  }
  .base h3 {
    font-weight: 600;
    font-size: 3.5em;
    color: #17013b;
  }
  .base h4 {
    font-weight: 400;
    color: #746e7e;
  }
  #scratch {
    -webkit-tap-highlight-color: transparent;
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    user-select: none;
  }


Thursday, 16 February 2023

How to get the current longitude and latitude. using javascript?

<div id="location"></div>

<script>
    var div = document.getElementById("location");
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition, showError);
        } else {
            div.innerHTML = "The Browser Does not Support Geolocation";
        }
    }
    
    function showPosition(position) {
        div.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;
    }
    
    function showError(error) {
        if (error.PERMISSION_DENIED) {
            div.innerHTML = "The User have denied the request for Geolocation.";
        }
    }
    getLocation();
</script>

Wednesday, 15 February 2023

URL encode

 URL  encode

 

 <?php

namespace App\Http\Controllers\API;
 
use Log; use DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class EncodeController extends Controller
{       
    // UrlEncode
    public function urlencode(Request $request)
    {
        try            
        {  
            $myvar = DB::table('cl_master_category')
            ->select('cl_master_category.category_id', 'cl_master_category.category_name', 'cl_master_category.status', 'cl_master_category.color_code')
            ->get();
            
            $ciphering = "AES-256-CBC";    
            $encryption_key = env('ENCRYPTION_KEY');            
            $encryption_iv = env('ENCRYPTION_IV');
            
            $myencoding = openssl_encrypt($myvar, $ciphering,$encryption_key, 0, $encryption_iv);  
            
            return response()->json(['success' => true ,'encoded'=>$myencoding], 200);
           
        }
        catch (\Exception\Database\QueryException $e)
        {
            Log::info('Query: '.$e->getSql());
            Log::info('Query: Bindings: '.$e->getBindings());
            Log::info('Error: Code: '.$e->getCode());
            Log::info('Error: Message: '.$e->getMessage());

            return response()->json(['success' => false , 'message' => 'Database Server Error. Please try again later.'], 500);
        }
        catch (\Exception $e)
        {
            Log::info('Error: Code: '.$e->getCode());
            Log::info('Error: Message: '.$e->getMessage());

            return response()->json(['success' => true , 'message' => 'Internal Server Error. Please try again later.'], 500);
        }
    }
   
}


********************************************************************
Nextjs code

import React from "react";

import CryptoJS from "crypto-js";

const test = () => { 

  let keytext =  "25c6c7ff35b9979b151f2136cd13b0ff"

  let encrypted = "Nb7g0tuktmBmEwUbGrMabzMHlUTN/uyDPg5coE0AHTgmkvkxmwYxapvMu4IaZoCEXphDN+A+PfcMRGGdPso1vbKWJU9X1Yr+oh/eBRobD6hkG4BWJIxnVW79LSkK8WBfieMy05j2FxQH8GzXlPJ9KtcaMcxU2Zj8YERpko2Q8bpcWAlbQVDHXHRaYLMjoR7QvUz2OYqY3CNyLQgXnoc70q5JyAT+eC036Mx/zBnjA16HeVI5xI1MFQ4aFEddd58XwICngKZcuahG0tdUcZ8Z4XgZnmMzMrt+QeunhPg+IQGZhPhL4ZqH2CMYMy2TDtIqClRiAytjekMIcyJErYjVSYPnvGuBQqXiwW23QM69XWMvY0WFmZXXnKQPiwcRUSh3UgEPmbk6Dx023KnL6uw6Maq7/8BzaPzKCJO31gxyXk17NEh+by/59/UDaaLSKnB4fFRu1G/qa+Rg5n5l01XK2uNWITqKne3xWleACeMN652ZVhU1dWPwiWKkwI6hjbCg8m9UtRKw57rq3d6Jt/pN+SUdLJXbIjcTd9oxWlltSUDv4LlstWIlRIx9i6B+SEOMWtEvJvVfDn2DrBtxdo+02SH7ZjNhNi8CEFEHQybPxNBd2KNaiAWyIHgiqCZwmoCDjgPoQh2bWj33jPOVGvqPsCfuFfW10RieWK8yMtZHV2/W16DX3+j3Urt7Cb5o0KvG2+va3+YvTZ123c3a/+UkR+S2odrhEku041VUahIx15Zlhi80ffPn0ngX6E4wDa5QkKAL34kZbQJnZPnzD0P4QOHl34cpn5ZZVP8HsoWAXrAiTM033qG976w43Ld1ewxGG5VhSGRgNHj9CQ42l5+7GQ=="

  // let decrypted = "";

  let ivtext ="1234567891011121"

  

  const key = CryptoJS.enc.Utf8.parse(keytext);

  const iv = CryptoJS.enc.Utf8.parse(ivtext);  

  var decrypted = CryptoJS.AES.decrypt(encrypted, key, {

    iv: iv,

    mode: CryptoJS.mode.CBC,

  });

  text = CryptoJS.enc.Utf8.stringify(decrypted)

  console.log("decrypt", CryptoJS.enc.Utf8.stringify(decrypted));

  return (

    <>

      <div> {text}</div>

      {/ <div>encrypted Text : {encrypted}</div> /}

      {/ <div>Decrypted Text : {decrypted}</div> /}

    </>

  );

};

export default test;

 

 

Tuesday, 14 February 2023

Steps to consider for login process using google

 web.php

<?php

use App\Http\Controllers\ConnectController;
 
Route::get('/googleconnect', [ConnectController::class, 'googleconnect'])->name('googleconnect');
Route::get('oauth2callback', [ConnectController::class, 'oauth2callback'])->name('oauth2callback'); 


require __DIR__.'/auth.php';

ConnectController.php

<?php namespace App\Http\Controllers; use Illuminate\Http\RedirectResponse; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Redirect; use Illuminate\View\View; class ConnectController extends Controller { public function googleconnect(Request $request) { // Initialise the client. $client = new \Google\Client(); $client->setApplicationName('Calendar'); $client->setDeveloperKey("xxxxxxxxx"); $client->setAuthConfig('./client_secret.json'); $client->setAccessType("offline"); $client->setIncludeGrantedScopes(true); $client->setApprovalPrompt('force'); $client->addScope(['profile',\Google_Service_Calendar::CALENDAR]); // Set the redirect URL back to the site to handle the OAuth2 response. 
This handles both the success and failure journeys. $auth_url = $client->createAuthUrl(); $client->setRedirectUri(('http://localhost:8000/') . '/oauth2callback'); return redirect()->to($auth_url); } public function oauth2callback (Request $request) { // Get all the request parameters $input = $request->all();// Attempt to load the venue from the state
we set in $client->setState($venue->id); // the venue with a message. if (isset($input['error']) && $input['error'] == 'access_denied') { toastr()->warning('Authentication was cancelled. Your calendar has not been integrated.'); return redirect()->route('login'); } elseif (isset($input['code'])) { $client = new \Google\Client(); $client->setApplicationName('Calendar'); $client->setDeveloperKey("xxxxxxx"); $client->setAuthConfig('./client_secret.json'); $client->setAccessType("offline"); $client->setIncludeGrantedScopes(true); $client->setApprovalPrompt('force'); $client->addScope(['profile',\Google_Service_Calendar::CALENDAR]); $accessToken = $client->fetchAccessTokenWithAuthCode($request->code); $service = new \Google\Service\Calendar($client); $google_account_email = $service->calendars->get('primary')->id; toastr()->success($google_account_email); return redirect()->route('login'); } } }


Note: Store the access token in database.
Settings

$client->setAccessToken($google->token); // If there is no previous token or it's expired. if ($client->isAccessTokenExpired()) { // Refresh the token if possible, else fetch a new one. if ($client->getRefreshToken()) { $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken()); } else { // Request authorization from the user. return response()->json(['success' => false, 'message' => 'Something wrong! Please try again.' ], 200); } $tokenObj=json_encode($client->getAccessToken()); $google->token=$tokenObj; $save_token=$google->save(); }


Points to be consider while writing HTML

 1.    Add proper alt text and title text to images.

2.    Use headings properly.

3.    Use ARIA landmarks. (e.g., role="navigation", role="main")

4.    Add labels to form fields.

5.    Group related form fields together

6.    Provide sufficient color contrast.

7.    Avoid using tiny fonts.

8.    Respect white space.

9.    Provide a visible indication of focus. (e.g., :hover, :focus)

10.    Use text, not pictures of text (as possible).

11.    Caption video

12.    Describe the video

13.    Test web pages using a keyboard

14.    Giving proper title on <a> tags

15.    Responsive testing

Machine Learning - Potato Leaf Disease Prediction

Step 1: import numpy as np import pandas as pd import splitfolders import matplotlib.pyplot as plt import tensorflow as tf from tensorflow i...