Laravel 12 - How to Integrate Google Maps
Laravel 12 - How to Integrate Google Maps
In this tutorial, we will discuss how to integrate Google Maps into a Laravel 12 application using the Maps JavaScript API. You'll learn how to display maps, add markers, and enhance your app with interactive location features.
If you're a video person, feel free to skip the post and check out the video instead!
Quick Overview
This guide walks you through integrating Google Maps into a Laravel 12 application. It begins by setting up a fresh Laravel project (or using an existing one) with a minimal installation, MySQL as the database. After accessing the project folder, you update the welcome.blade.php view to embed a styled Google Map centered on the Burj Khalifa, complete with a marker for easy identification. The Google Maps API key is securely stored in the .env file to authenticate requests. You’ll also learn how to obtain this API key from the Google Cloud Console, apply security restrictions, and review usage limits. Finally, the Laravel development server is launched to test the integration locally. If you encounter the "This page can’t load Google Maps correctly" error, the guide explains how enabling billing in Google Cloud, backed by a $200 monthly free credit, resolves this requirement.
Step # 1 : Set Up a Fresh Laravel Project or Use an Existing One.
To get started, either create a new Laravel project or use an existing one. If you have Laravel globally installed you can generate a fresh project using the following command.
laravel new google-maps
Or you can use Composer to create a fresh project.
composer create-project laravel/laravel --prefer-dist google-maps
During the setup process, make the following choices when prompted.
- Starter Kit: Select None to install Laravel without any authentication scaffolding.
- Database: Choose MySQL to configure Laravel for MySQL-based storage.
- Run Migrations: Type yes. This will automatically create the default database tables such as users and password_resets.
- Install Frontend Dependencies: Choose Yes when asked to run npm install and npm run build. This will install required frontend packages like Vite and Tailwind CSS and compile your assets.
At this point, we have a fresh Laravel project named google-maps. If Laravel is installed globally, the laravel new command sets it up quickly. Otherwise, composer create-project handles the installation. The setup provides a minimal installation with no starter kit, uses MySQL as the database, and runs the default migrations.
Step # 2 : Access the Project.
Open your terminal (such as Git Bash, Command Prompt, or any terminal of your choice) and navigate to the root directory of your Laravel project.
cd c:xampp/htdocs/google-maps
This puts you inside the project folder, where you can run Artisan commands, manage dependencies, and start the development server as you continue building your application.
Step # 3 : Update the Welcome Page to Display Google Maps.
Next, we’ll modify the default welcome.blade.php view to embed an interactive Google Map on the homepage. Replace the content of resources/views/welcome.blade.php with the following code.
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 12 - Google Maps - Code Shotcut</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body class="bg-gray-100 text-gray-800 min-h-screen flex flex-col items-center justify-center px-4 py-8 space-y-6">
<h2 class="text-3xl font-bold text-indigo-700 text-center">
Laravel 12 - Code Shotcut - Google Maps
</h2>
<div class="w-full max-w-5xl bg-white p-8 rounded-lg shadow-lg">
<div id="map" class="rounded-md overflow-hidden shadow"></div>
</div>
<script>
function initMap() {
const latLng = { lat: 25.1972, lng: 55.2744 }; // Burj Khalifa coordinates
const mapOptions = {
zoom: 15,
center: latLng,
};
const map = new google.maps.Map(document.getElementById("map"), mapOptions);
new google.maps.Marker({
position: latLng,
map: map,
title: "Burj Khalifa - World's Tallest Building",
});
}
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>
By updating the welcome view, we embed a styled Google Map section directly into the homepage. The #map div is given a fixed height and full width to ensure proper visibility. The map is centered at the Burj Khalifa in Dubai using its latitude and longitude coordinates, with a marker placed at the location for reference. The initMap() function initializes the map, and the Google Maps JavaScript API is loaded dynamically using the API key stored in the .env file as GOOGLE_MAP_KEY. When the page loads, the map is automatically rendered, providing users with an interactive view centered on the Burj Khalifa.
Step # 4 : Set Up the Google Maps API Key.
Open your Laravel project’s .env file and add the following line to define your Google Maps API key.
GOOGLE_MAP_KEY="Your Google Map API Key here"
This setup allows Laravel to securely access your API key without hardcoding it into your codebase. The key is essential for authenticating requests to the Google Maps JavaScript API and rendering the map correctly. By storing it in the .env file, we keep sensitive credentials separate from the application's logic, making the project more secure and easier to manage across different environments.
Step #5: Get Your Google Maps API Key.
To use Google Maps in your Laravel 12 app, visit the Google Cloud Console (Link: https://console.cloud.google.com/) and follow these steps.
- Create a new project if you don’t have one already.
- Click on APIs & Services and Navigate to the Credentials section.
- Click Create Credentials and choose API Key. Your API key will then be generated and displayed.
- Set usage restrictions (by domain, IP, or API type) to protect your key (Optional).
- Review the usage limits (Link: https://developers.google.com/webmaster-tools/limits) to avoid service interruptions.
Copy the generated API key and paste it into your .env file like this.
GOOGLE_MAP_KEY="Your Google Map API Key here"
This API key enables Google Maps features in your app by authenticating your requests. Using the .env file keeps your key secure and out of your source code, making it easier to manage across different environments. With your key in place, your updated HTML view can now dynamically load and render the map using the Google Maps JavaScript API.
Step # 6 : Test Your Google Maps Integration.
Now that everything is set up, let’s test the integration by starting Laravel’s development server. Run this command in your terminal.
php artisan serve
Once the server is running, open your browser and navigate to: http://127.0.0.1:8000. You should see the homepage with the embedded Google Map centered on the Burj Khalifa.
If you encounter the message This page can’t load Google Maps correctly, it means that Google requires billing information to enable the Maps API, even for testing purposes. This requirement is a standard policy designed to prevent misuse and ensure fair use of their services across all users. Fortunately, Google provides a $200 monthly free credit that covers the needs of most small to medium projects, so in most cases, you won’t be charged unless your usage exceeds this limit. To resolve this error, simply visit the Google Cloud Console (Link: https://console.cloud.google.com/) enable billing for your project, and add a valid payment method. Once billing is set up, reload your application, and the Google Map should display correctly without any issues.
Conclusion
By following this guide, you’ve successfully integrated Google Maps into your Laravel application, showcasing an interactive map centered on the iconic Burj Khalifa. The API key is securely stored in the .env file, allowing Laravel to load it dynamically while keeping sensitive data safe. This setup provides users with a seamless way to visualize important locations right within your app. Although Google requires billing information to enable the Maps API, the $200 monthly free credit covers most projects, so you can get started without worry. From here, you can enhance your map further by adding custom markers, directions, or interactive elements.
For more options and advanced features, be sure to explore the official Google Maps API documentation.
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments