Click Below to subscribe

How To Integrate Google Maps in Laravel 2022

Google Maps JavaScript API provides a bunch of methods for creating maps for web applications. In this tutorial, we will integrate google maps into the laravel project step by step.

1. Let's create a new laravel project.

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

2. Create a view and add the following code.

resources/views/map.blade.php

<!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>

        <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async></script>
        <script>
            let map, activeInfoWindow, markers = [];

            /* ----------------------------- Initialize 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) {
                    mapClicked(event);
                });

                initMarkers();
            }

            /* --------------------------- Initialize Markers --------------------------- */
            function initMarkers() {
                const initialMarkers = <?php echo json_encode($initialMarkers); ?>;

                for (let index = 0; index < initialMarkers.length; index++) {

                    const markerData = initialMarkers[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", (event) => {
                        if(activeInfoWindow) {
                            activeInfoWindow.close();
                        }
                        infowindow.open({
                            anchor: marker,
                            shouldFocus: false,
                            map
                        });
                        activeInfoWindow = infowindow;
                        markerClicked(marker, index);
                    });

                    marker.addListener("dragend", (event) => {
                        markerDragEnd(event, index);
                    });
                }
            }

            /* ------------------------- Handle Map Click Event ------------------------- */
            function mapClicked(event) {
                console.log(map);
                console.log(event.latLng.lat(), event.latLng.lng());
            }

            /* ------------------------ Handle Marker Click Event ----------------------- */
            function markerClicked(marker, index) {
                console.log(map);
                console.log(marker.position.lat());
                console.log(marker.position.lng());
            }

            /* ----------------------- Handle Marker DragEnd Event ---------------------- */
            function markerDragEnd(event, index) {
                console.log(map);
                console.log(event.latLng.lat());
                console.log(event.latLng.lng());
            }
        </script>
    </body>
</html>

Note:- Don't forget to update your Google API Key.

You can easily add/remove markers. also, you can pass additional properties in the marker object based on your requirement.

(a). Add a marker

const marker = new google.maps.Marker({
    position: {
        lat: 28.625043,
        lng: 79.810135
    },
    label: { color: "white", text: "P4" },
    draggable: true,
    map
});
markers.push(marker);

(b). Remove a marker

Example:- Remove P4 marker

const index = markers.findIndex(marker => marker.label.text == "P4");
if(index != -1) {
    markers[index].setMap(null);
    markers.splice(index, 1);
}

(c). Update marker properties

Example:- Update P4 marker

const index = markers.findIndex(marker => marker.label.text == "P4");
if(index != -1) {
    markers[index].setOptions({ ...markers[index], position: { lat: 28.625043, lng: 79.810135 } });
}

setOptions(options) - set marker properties

setPosition(latlng) - set marker position

setLabel(label) - set marker label

setVisible(boolean) - show/hide a marker 
   

3. Create a controller and add the following code.

php artisan make:controller MapController

app/Http/Controllers/MapController.php

<?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'));
    }
}

4. Create Route

routes/web.php

<?php

use App\Http\Controllers\MapController;
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('/', [MapController::class, 'index']);

5. Finally open http://localhost/laravel-google-maps/public in the browser.

Extras:- Reverse Geocoding

const geocoder = new google.maps.Geocoder();
const latlng = new google.maps.LatLng(28.625043, 79.810135);
const request = {
    latLng: latlng
}
geocoder.geocode(request, results => {
    if(results.length) {
        console.log(results[0].formatted_address)
    }
});

Checkout laravel-google-maps repo. https://github.com/ultimateakash/laravel-google-maps

If you facing any issues. don't hesitate to comment below. I will be happy to help you.

Thanks.

Leave Your Comment