Google consists of all the addresses which have been listed on Google map. These addresses are basically listed on the basis of latitude and the longitude. It defines co-ordinate points on the earth. So, every location has a fixed set of the latitude and the longitude. We can make a custom list of addresses and store it to the database. Then according to the requirement, we can use it for the purpose of autocomplete. This concept is much simple if we have a low set of data. But what, if you have to search in a geographical area such as a country or outside our country. So for achieving this functionality, I will be using google autocomplete address. In this post, I will be helping you to implement google places autocomplete example with step by step.
Drag and Drop File Upload in Laravel 6 Using Dropzone js
Prerequisites
Before creating a new project in Laravel 6 you must install these all in your system.
- PHP version >=7.3.9
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
So, let’s begin the implementation of Google autocomplete address in Laravel 6.
Google Autocomplete Address in Laravel 6
Create a new project by hitting the below command in the command prompt or terminal.
composer create-project --prefer-dist laravel/laravel location-autocomplete
Just wait for the project dependencies setup. Once, it is done let’s continue the steps.
For this project, we do not need any database configuration. Actually, we are not going to work with the database. We’ll just create a Controller and a view in which I will implement the Google autocomplete places.
How to Upload Multiple Images in Laravel 6 with Validation
Get Google Place API Key
For implementing the autocomplete address, we’ll have to get the key. So, just go to the link https://cloud.google.com and follow the below steps for getting the API key.
- You will need to login with your Google account. Then just select the type of product. In this case, we are going to implement the places.
- If you haven’t any fresh Laravel 6 setup then just create a new project.
How to Resize Image in Laravel 6 Before Upload
- If you have no project then let’s create a new one.
- I have created a new project there with named Place Autocomplete.
- In the next step, it will prompt you for creating a billing account. Actually the Google Autocomplete Address is a paid API. So for the demo purposes, I am not going to create a billing account here.
How to Implement Pagination in Laravel 6 with Example
Get Google Place API For Developer
Just cancel, and skip the billing step. Google provides a free API key for the developer for the demo. So, I am just going the use it. In the below image you will have an option in the top right corner named Console.
Just click on that option. It will redirect you to the below result. In this result, you will be showing the product list provided by the Google Cloud Platform.
Now, we have to select the Places API from the list. So, just click on the Places API. Now, you will be redirected to the description of this API.
Here, we will have to enable this API service. So, that we can use it for development purposes. Once, it will enable, you can use all the services related under the Place API.
Create API Key For Place Autocomplete
In the next step, you will have to create an API key for the place autocomplete. So, under the menu section, just click on the APIs tab as shown you in the below result.
Under the Credentials tab, you will be showing an option to create credentials. So, just click on that and create an API key.
Once, the API key has been created, it will look like the below result.
Now, we’ll be using this API Key for creating our Autocomplete place.
Create a Controller
For this application, we no need any database related operation. So, we are not going to synchronize this application with the database. Simply, we will create a controller and a view. In the view, we’ll create a layout for implementing the google autocomplete address. After that, on the selection of the address/location/city, we will get the latitude and the longitude.
So, for creating a new controller we will be using the artisan command. Below, I have created a controller with the name HomeController.
php artisan make:controller HomeController
Once, the controller has been created, let’s add some code there.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
// ---------------- [ Load View ] ----------------
public function locationAutoComplete(Request $request) {
return view("auto-complete");
}
}
Create a Route
For the above controller function, we will require a route to call the view. So, in the routes/web.php just add a single line of code.
Route::get("auto-complete", "HomeController@locationAutoComplete");
Create a View For Google Autocomplete Address
In the resource folder just create a view. I have created a view with the name auto-complete.blade.php. Now, just add the below HTML snippet there.
<!doctype html>
<html lang="en">
<head>
<title>Google Autocomplete Address Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="crossorigin="anonymous"></script>
</head>
<body>
<div class="container mt-5">
<div class="row">
<div class="col-xl-6 col-lg-6 col-md-8 col-sm-12 col-12 m-auto">
<div class="card shadow">
<div class="card-header bg-primary">
<h5 class="card-title text-white"> Google Autocomplete Address</h5>
</div>
<div class="card-body">
<div class="form-group">
<label for="autocomplete"> Location/City/Address </label>
<input type="text" name="autocomplete" id="autocomplete" class="form-control" placeholder="Select Location">
</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>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-success"> Submit </button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
Run the Laravel Application
Save the above snippet and just run the application with artisan command.
php artisan serve
Once, Laravel development server has started, simply navigate to the browser window.
http://localhost:8000/auto-complete
You will have a result with the below screen.
So, the layout is ready, now just need to add some javascript code for autocomplete address.
Add Autocomplete Script
So, in the footer section before closing the body tag, just add the below script there.
{{-- javascript code --}}
<script src="https://maps.google.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initAutocomplete" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#lat_area").addClass("d-none");
$("#long_area").addClass("d-none");
});
</script>
<script>
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");
});
}
</script>
Save and refresh the page. Now, just try entering some city names. Suppose, I am trying to enter the USA. In the autocomplete address result, you can see the results are similar from the USA country.
How to Implement Yajra Datatables in Laravel 6
Restrict Country in Google Autocomplete Address
Suppose, if you don’t want to pick addresses from the whole world then you can set the specific country. This will give you a more clear and specific search result based on the country.
In the below script, I have specified the country to India. So, now, in the search results, the location will be showing of India only. Not outside the country.
<script>
google.maps.event.addDomListener(window, 'load', initialize);
function initialize() {
var options = {
componentRestrictions: {country: "IN"}
};
var input = document.getElementById('autocomplete');
var autocomplete = new google.maps.places.Autocomplete(input, options);
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");
});
}
</script>
To check the result, simply refresh the page and try out the same search. Now, as a result, you can see I have entered the USA. But this time in the autocomplete only address is showing of India.
Laravel 6 Custom Login and Registration with Session
Conclusion
The Google autocomplete address is really an awesome feature by the Google Cloud Platform. There are lots of other map services that can be used to build a real-time application for the web and mobile. In this application demo, I have shown you how you can use the Google autocomplete address. Also, you can restrict the specific country and city for the autocomplete address. I hope you can use this demo to build your projects. In the upcoming posts, I will come up with a more advanced and real demo with Laravel 6. I hope you will enjoy the coding.
Paul says
Thanks for the great post. It works well, but I get a Java error alongside the working script which I can see when I “inspect” the page.
Uncaught (in promise)
md {message: “initAutocomplete is not a function”, name: “InvalidValueError”, stack: “Error↵ at new md (https://maps.google.com/maps/…ibraries=places&callback=initAutocomplete:149:124“}
How can I get rid of that error?