This tutorial will teach you how to use Laravel to integrate a Google Map with numerous markers and an info box. Google Maps are used to direct users to their destinations or to show the locations of businesses and other users.

Google Maps is the best approach to use a map and markers when we want to display many locations with some information on a map, such as neighboring restaurants, hotels, and other locations. While the map has several markers, we will also learn how to automatically center the map.

There are numerous applications that make advantage of Google Maps' different markers and info boxes, each with its own unique requirements for use in the application. Examples include showing hotel prices with info boxes, contact information, and nearby places.

In this lesson, we'll utilize a straightforward illustration where we display a google map with a position marker that uses latitude and longitude. All Laravel versions, including 5, 6, 7, 8, and 9, as well as Laravel 9, are compatible with this example.

Create a Laravel project

The first step is to start a new Laravel project by using the composer command, alternatively you can read the How to install Laravel 8? Use the Laravel artisan command to create migrations, models, and controllers

Configure google map

Create a Google Developer account now, and then follow the steps below to obtain keys for the Google Map.

  • Visit the Credentials page on the Google Maps Platform.
  • Access the Credentials page.
  • Click Create credentials > API key on the Credentials page.
  • Your freshly created API key is displayed in the window for creating API keys.

On the Credentials page, under API keys, the new API key is listed.
then include it in the environment file.

GOOGLE_MAPS_API_KEY=KEY_HERE

Create Controller

Create a controller next, and then add the required imports and classes. You can create manually or using Laravel artisan.

php artisan make:controller MapController 
    <?php

    namespace App\Http\Controllers;

    use App\Models\Article;
    use App\Models\User;
    use Illuminate\Http\Request;

    class MapController extends Controller
    {
         

        public function showMap(Request $request)
        {

          $locations = [
            ["lat" => 12.9716, "lng" => 77.5946],
            ["lat" => 26.9124, "lng" => 75.7873],
            ["lat" => 22.2587, "lng" => 71.1924],
          ];
          return view("show-map",['locations'=>$locations]);
        }
}

Create View Files

Create show-map.blade.php, the view file we used in the controller, and add the following code.

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

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Google Map with Multiple Marker and Info Box in Laravel - CodeSolutionStuff </title>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
    <link href="//netdna.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" />

</head>

<body class="antialiased">
    <div class="container">
        <!-- main app container -->
        <div class="readersack">
            <div class="container">
                <div class="row">
                    <div class="col-md-12 ">
                        <h3>Google Map with Multiple Marker and Info Box in Laravel - CodeSolutionStuff </h3>
                        <div id="map" style='height:400px'></div>

                    </div>
                </div>
            </div>
        </div>
        <!-- credits -->
        <div class="text-center">
            <p>
                <a href="#" target="_top">Google Map with Multiple Marker and Info Box in Laravel
                </a>
            </p>
            <p>
                <a href="https://www.codesolutionstuff.com" target="_top">CodeSolutionStuff.com</a>
            </p>
        </div>
    </div>

</body>
<script type="text/javascript">
    function initializeMap() {
        const locations = <?php echo json_encode($locations) ?>;

        const map = new google.maps.Map(document.getElementById("map"));
        var infowindow = new google.maps.InfoWindow();
        var bounds = new google.maps.LatLngBounds();
        for (var location of locations) {
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(location.lat, location.lng),
                map: map
            });
            bounds.extend(marker.position);
            google.maps.event.addListener(marker, 'click', (function(marker, location) {
                return function() {
                    infowindow.setContent(location.lat + " & " + location.lng);
                    infowindow.open(map, marker);
                }
            })(marker, location));

        }
        map.fitBounds(bounds);
    }
</script>

<script type="text/javascript" src="https://maps.google.com/maps/api/js?key={{ env('GOOGLE_MAPS_API_KEY') }}&callback=initializeMap"></script>


</html>

JavaScript, which is used to add maps, is the primary reasoning.

 function initializeMap() {
        const locations = <?php echo json_encode($locations) ?>;

        const map = new google.maps.Map(document.getElementById("map"));
        var infowindow = new google.maps.InfoWindow();
        var bounds = new google.maps.LatLngBounds();
        for (var location of locations) {
            var marker = new google.maps.Marker({
                position: new google.maps.LatLng(location.lat, location.lng),
                map: map
            });
            bounds.extend(marker.position);
            google.maps.event.addListener(marker, 'click', (function(marker, location) {
                return function() {
                    infowindow.setContent(location.lat + " & " + location.lng);
                    infowindow.open(map, marker);
                }
            })(marker, location));

        }
        map.fitBounds(bounds);
    }

In order for the map to automatically centre, we also included the auto centre code here.

Create the route

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/show-map', "\App\Http\Controllers\ArticleController@showMap" );

Recommended Posts

View All

Laravel 8 Stripe Subscription Tutorial Using Cashier Example


laravel cashier, stripe laravel, laravel subscription tutorial, laravel 8 cashier tutorial, laravel 8 stripe subscription tutorial

Laravel 9 Database Backup with Spatie Tutorial Example


Learn how to easily backup your Laravel 9 database using the Spatie backup package with this step-by-step tutorial example. Safeguard your important d...

Laravel One to Many Eloquent Relationship


laravel one to many relationship example, laravel one to many sync, one to many relationship laravel 5.6, one to many relationship laravel model

How to Implement Gravatar Image using thomaswelton/laravel-gravatar in Laravel 9


Learn how to easily implement Gravatar image using thomaswelton/laravel-gravatar in Laravel 9. Enhance user profiles with personalized images.

Laravel 9 Elasticsearch Integration From Scratch With Example


In this post, we'll talk about how to incorporate Elasticsearch from scratch using a Laravel 9 example.