Laravel 10 - Google Maps integration

Touseef Afridi
05 Sep 24

Laravel 10 - Google Maps integration

In this tutorial, we'll discuss how to integrate Google Maps into Laravel 10, which is useful for displaying interactive maps and location-based data.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

In this guide, we walk you through integrating Google Maps into a Laravel application. You’ll begin by setting up a fresh Laravel project and configuring the frontend assets. Then, you'll customize the default welcome.blade.php page to display a Google Map centered on a location of your choice, such as Jeddah Corniche. We’ll also cover how to obtain a Google Maps API key from the Google Cloud Console and securely store it in the .env file for authentication. Finally, you’ll test the setup by running your Laravel app, ensuring that Google Maps loads correctly, while understanding how to handle billing information for API usage. By the end of this guide, you’ll have successfully integrated Google Maps into your Laravel application.

Step # 1 : Set Up a Fresh Laravel Project.

Let’s kick things off by setting up a brand-new Laravel project. If you already have Laravel installed globally, simply run the following command in your terminal.
laravel new google-maps
If you prefer using Composer directly, you can use.
composer create-project laravel/laravel --prefer-dist google-maps
This will scaffold a fresh Laravel application named google-maps, including all the necessary files and dependencies. Once the installation is complete, your new Laravel project will be ready to go, providing a clean foundation to start building your Google Maps-based features with ease.

Step # 2 : Access Your Project and Set Up Frontend Assets.

Open your terminal (like Git Bash or Command Prompt) and move into your Laravel project directory. For example.
cd c:xampp/htdocs/google-maps
Once inside the project folder, install the frontend dependencies and start the Vite development server by running.
npm install && npm run dev
Leave this terminal running to keep Vite active. Then, open a new terminal tab or window and navigate back to the same project directory. This will allow you to continue running Laravel-specific commands while Vite handles your frontend assets in the background.

Step # 3 : Customize the Welcome Page to Display Google Maps.

Now that your Laravel app is set up and ready, let’s replace the default welcome page with a custom layout that integrates a Google Map. To do this, open the resources/views/welcome.blade.php file in your project directory and replace its existing content with the code provided below.
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel - Google Maps</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <style>
        #map {
            height: 400px;
            width: 100%;
        }
    </style>
</head>
<body>
    <div class="container" style="margin-top: 50px;">
        <h2>Laravel 10 - Code Shotcut - Google Maps</h2>
        <div id="map"></div>
    </div>
    <script>
        function initMap() {
            const latLng = { lat: 21.60476953235633, lng: 39.10753805227597 };
            const mapOptions = {
                zoom: 12,
                center: latLng,
            };
            const map = new google.maps.Map(document.getElementById("map"), mapOptions);
            new google.maps.Marker({
                position: latLng,
                map: map,
                title: "Welcome to Jeddah Corniche",
            });
        }
        window.initMap = initMap;
    </script>
    <script
        src="https://maps.googleapis.com/maps/api/js?key={{ env('GOOGLE_MAP_KEY') }}&callback=initMap"
        async defer>
    </script>
</body>
</html>
This template includes a simple layout with a Google Map centered on Jeddah Corniche, providing a clear and interactive view of the location. The initMap function sets up the map view and places a marker on the selected location. It uses the GOOGLE_MAP_KEY from your .env file to load the Google Maps API script dynamically, ensuring secure and easy integration. Once this is saved, your app’s homepage will now render a live, interactive map instead of the default Laravel welcome screen, providing a more engaging and functional user experience.

Step # 4 : Add Your Google Maps API Key to the .env File.

Next, you’ll need to integrate your Google Maps API key into your Laravel application to authenticate the requests made to Google Maps. Open the .env file in your project’s root directory and add the following line.
GOOGLE_MAP_KEY="Your Google Map API Key here"
Make sure to replace Your Google Map API Key here with the actual API key you generated from the Google Cloud Platform. This step ensures your Laravel app can access Google Maps services securely by using the API key stored in the environment file. After this, Google Maps will be ready to work within your app.

Step # 5 :Get Your Google Maps API Key.

To start using Google Maps in your Laravel project, you’ll need to generate an API key from the Google Cloud Console. Here’s how you can get it.
  1. Go to the Google Cloud Console (Link: https://console.cloud.google.com/).
  2. If you don't have a project, create a new one.
  3. Once your project is set up, head to the Credentials section.
  4. Click Create Credentials and choose API Key.
  5. Optionally, apply any restrictions (e.g., limiting usage to certain domains or IP addresses) for added security.
  6. Review the usage limits to understand the limits on API requests.
  7. Copy the generated API key.

Now that you have your API key, add it to your .env file like this.
GOOGLE_MAP_KEY="Your Google Map API Key here"
This API key will authenticate your app with Google Maps, enabling it to access mapping services. Restricting the key helps secure it, ensuring that only authorized requests are processed. By storing it in the .env file, you keep your sensitive credentials secure and easily configurable.

Step # 6 : Testing the Setup.

Now it’s time to test whether everything is working as expected. Start the Laravel development server by running the following command.
php artisan serve
Open your browser and navigate to the following URL: 127.0.0.1:8000. If you see the message This page can't load Google Maps correctly, it means that Google requires billing information for the API, even for testing purposes. Don’t worry, Google provides $200 worth of free usage each month, and you won’t incur any charges unless you exceed this limit.

Conclusion

By following this guide, you've successfully integrated Google Maps into your Laravel application. You've set up a fresh Laravel project, customized the welcome page to display an interactive map, and securely added your Google Maps API key. This setup allows you to easily add location-based features to your app, such as showing custom markers and dynamically loading maps. With the $200 free usage from Google, you can confidently test and deploy your application without worrying about costs, as long as you stay within the usage limits.
For further exploration, check out the official Google Maps API documentation to enhance your integration with additional features and customizations.
Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering