How to Integrate Google Maps in Laravel: Complete Step-by-Step Guide

Share this post on:
Laravel Google Maps integration tutorial - Step-by-step guide with code examples

Google Maps is one of the most widely used mapping services, and integrating it into your Laravel application can enhance user experience significantly. Whether you want to display store locations, track assets, or build location-based services, Google Maps API makes it possible.

In this guide, we’ll walk through step-by-step instructions to integrate Google Maps into a Laravel project.

Step 1: Create a New Laravel Project

If you don’t already have a Laravel project, create one using Composer:

composer create-project laravel/laravel laravel-google-maps

Step 2: Create a View for Google Maps

Inside resources/views/, create a new Blade template called map.blade.php and add the following code:

<!DOCTYPE html>

<html>

<head>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <style>

        .text-center { text-align: center; }

        #map { width: 100%; height: 400px; }

    </style>

</head>

<body>

<h1 class="text-center">Laravel Google Maps</h1>

               <div id="map"></div>

               <!-- Google Maps API -->

<script src="https://maps.googleapis.com/maps/api/js?              key=YOUR_API_KEY&callback=initMap" async> </script>

<script>

        let map, activeInfoWindow, markers = [];

        // Initialize Google Map

        function initMap() {

            map = new google.maps.Map(document.getElementById("map"), {

                center: { lat: 28.626137, lng: 79.821603 },

                zoom: 15

            });

            map.addListener("click", function(event) {

                console.log("Map clicked at:", event.latLng.lat(), event.latLng.lng());

            });

            initMarkers();

        }

  // Add Markers

        function initMarkers() {

            const initialMarkers = <?php echo json_encode($initialMarkers); ?>;

initialMarkers.forEach((markerData, index) => {

                const marker = new google.maps.Marker({

                    position: markerData.position,

                    label: markerData.label,

                    draggable: markerData.draggable,

                    map

                });

                markers.push(marker);

                const infowindow = new google.maps.InfoWindow({

                    content: `<b>${markerData.position.lat}, ${markerData.position.lng}</b>`,

                });

                marker.addListener("click", () => {

                    if(activeInfoWindow) activeInfoWindow.close();

                    infowindow.open({ anchor: marker, map });

                    activeInfoWindow = infowindow;

                    console.log("Marker clicked:", marker.position.toString());

                });

                marker.addListener("dragend", (event) => {

                    console.log("Marker dragged to:", event.latLng.lat(), event.latLng.lng());

                });

            });

        }

    </script>

</body>

</html>

Note: Replace YOUR_API_KEY with your Google Maps API Key. (You can generate one from Google Cloud Console).

Step 3: Create a Controller

Generate a controller for handling the map logic:

php artisan make:controller MapController

Now, open app/Http/Controllers/MapController.php and add the following code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class MapController extends Controller

{

    public function index()

    {

        $initialMarkers = [

            [

                'position' => ['lat' => 28.625485, 'lng' => 79.821091],

                'label' => ['color' => 'white', 'text' => 'P1'],

                'draggable' => true

            ],

            [

                'position' => ['lat' => 28.625293, 'lng' => 79.817926],

                'label' => ['color' => 'white', 'text' => 'P2'],

                'draggable' => false

            ],

            [

                'position' => ['lat' => 28.625182, 'lng' => 79.81464],

                'label' => ['color' => 'white', 'text' => 'P3'],

                'draggable' => true

            ]

        ];

        return view('map', compact('initialMarkers'));

    } }

Here, we are sending initial marker data (position, label, draggable property) to the view.

Step 4: Define Routes

Open routes/web.php and add:

use App\Http\Controllers\MapController;
use Illuminate\Support\Facades\Route;
Route::get('/', [MapController::class, 'index']);

Step 5: Run Your Application

Start the Laravel development server:

php artisan serve

Now open your browser at:

http://127.0.0.1:8000

You should see a Google Map with markers displayed.

In this blog, we integrated Google Maps into a Laravel application using the Google Maps JavaScript API.