Friday, April 9, 2021

Autocomplete Address Search Module Using Google API and PHP

Steps to implement an autocomplete address search module

The first step is to grab a google’s API Key, you can find it here.

index.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

        <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

        <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

    </head>
    <body>

        <select id="address" style="width:500px;"></select>

        <script type="text/javascript">
            $(document).ready(function(){

                $("#submit").click(function(){
                    var val = $("#address").val();
                    alert(val);
                });

                $('select').select2({
                    placeholder: "Search for your city",
                    ajax: {
                        url: function(params){
                            return 'api.php?data='+params.term; 
                        },
                        dataType: 'json', 
                        processResults: function (data) {
                            return {
                                results: $.map(data, function (item) {
                                    return {
                                        text: item.text,
                                        id: item.text
                                    }
                                })
                            };
                        }
                    }

                });
            });
        </script>

    </body>
</html>

 

api.php


<?php

 $terms = $_GET['data'];

 $data = file_get_contents("https://maps.googleapis.com/maps/api/place/autocomplete/json?input=".$terms."&types=geocode&key={YOUR_API_KEY}");


 $arr = array();
 $i=0;
 foreach(json_decode($data)->predictions as $item){
 $arr[$i] = array(
 'id' => $i,
 'text' => $item->description
 );
 $i++;
 }

 echo json_encode($arr);

?>

you just have to put above index.html and api.php in the same directory, and you replace {YOUR_API_KEY} with your’s one.

Important Note

By using google place API google simply needs some policy to follow (read this policy here), Google wants their “powered by Google” logo to be shown in the drop-down.

Note:- you need a live or local server to run this module.


Source: https://www.myprogrammingtutorials.com/autocomplete-address-search-module-google-api-php.html


No comments:

Post a Comment

Please Comment Here!

How to backup and download Database using PHP

< ?php $mysqlUserName = 'databaseusername' ; $mysqlPassword = 'databasepassword' ; $mysqlHostNa...