Laravel 11 - Google Maps integration
Laravel 11 - Google Maps integration
In this tutorial, we'll discuss how to integrate Google Maps into Laravel 11, 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
This guide walks through integrating Google Maps into a Laravel application. It starts with setting up a fresh Laravel project or using an existing one, ensuring a minimal installation with MySQL as the database and Pest for testing. After navigating to the project directory, the welcome.blade.php file is updated to include Google Maps, styling the map container and initializing the map at Jeddah Corniche with a marker. The Google Maps API key is securely configured in the .env file to authenticate API requests. The guide also explains obtaining the API key from the Google Cloud Console, applying restrictions for security, and reviewing usage limits. Finally, the Laravel development server is started, and the integration is tested by accessing the local URL. If an error appears stating "This page can't load Google Maps correctly," the guide highlights the need for enabling billing in Google Cloud, which provides a $200 free credit each month for API usage.
Step # 1 : Create a Fresh Laravel Project or Use an Existing One.
If Laravel is installed globally, create a new Laravel project by running.
laravel new google-maps
Or
Alternatively, you can use Composer to generate the project.
composer create-project laravel/laravel --prefer-dist google-maps
During the setup process, choose the following options when prompted.
- Select None for the Starter Kit to install Laravel without any authentication scaffolding.
- Choose Pest as the testing framework to enable a modern and minimalistic testing setup.
- Set the database to MySQL to configure Laravel for MySQL-based storage.
- Type Yes to run migrations and automatically create the default database tables.
Now we have a new Laravel project named google-maps. If Laravel is installed globally, laravel new sets it up quickly; otherwise, composer create-project downloads and installs Laravel. The setup ensures a minimal installation (no starter kit), configures Pest for testing, sets MySQL as the database, and applies default database migrations.
Step # 2 : Access the project.
Open a terminal (e.g., Git Bash) and navigate to your Laravel project's root folder.
cd c:xampp/htdocs/google-maps
Now we have accessed the Laravel project directory, allowing us to run further commands, manage dependencies, and start the development server.
Step # 3 : Update the View.
Modify the welcome.blade.php file to include the following HTML, which integrates Google Maps into your Laravel application.
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 11 - Google Maps - Code Shotcut</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 11 - 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>
By updating the welcome.blade.php file, we integrate Google Maps into the Laravel application. The #map div is styled with a fixed height and full width to properly display the map. The initMap function initializes Google Maps, centering it at Jeddah Corniche with predefined latitude (21.6047695) and longitude (39.1075380). A marker is placed at this location with a title for interactivity. The Google Maps API script is loaded dynamically, using the API key stored in the .env file (GOOGLE_MAP_KEY). When the page loads, initMap runs automatically, rendering the map. Now, users visiting the Laravel application's homepage will see an interactive Google Map displaying the specified location.
Step # 4 : Configure the Google Maps API Key.
Open the .env file in your Laravel project and define a variable for your Google Maps API key by adding the following line
GOOGLE_MAP_KEY="Your Google Map API Key here"
By adding this variable, we store the Google Maps API key securely within Laravel's environment configuration. This key is required to authenticate requests to the Google Maps API and enable map rendering. Using the .env file ensures that sensitive credentials are not hardcoded into the application, improving security and maintainability. Now, Laravel can access this key dynamically whenever the map needs to be loaded.
Step #5: Obtain the Google Maps API Key.
To get your Google Maps API key, 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.
- Navigate to the Credentials section.
- Click on Create Credentials and select API Key.
- Apply restrictions if needed to enhance security.
- Review usage limits (Link: https://developers.google.com/webmaster-tools/limits).
- Copy the generated API key and add it to your .env file.
GOOGLE_MAP_KEY="Your Google Map API Key here"
This step provides authentication for Google Maps API requests. By generating an API key, Google Cloud identifies your project and allows you to use mapping services. Restricting the key (e.g., by domain or IP) improves security, preventing unauthorized use. Adding the key to .env ensures secure and flexible configuration without exposing sensitive information in the codebase.
Step # 6 : Testing the Integration.
Now, it's time to test the implementation by starting the Laravel development server. Run the following command in your terminal.
php artisan serve
Once the server is running, open your browser and access the below URL.
127.0.0.1:8000
If you encounter the error This page can't load Google Maps correctly, it means Google requires billing information to use the Maps API, even for testing. This is a standard requirement to prevent abuse and ensure fair usage. However, Google provides a $200 free credit per month, which is sufficient for most small to medium-scale applications, and you won’t be charged unless your usage exceeds this limit. To resolve the issue, visit the Google Cloud Console (Link: https://console.cloud.google.com/), enable billing for your project, and link a payment method.
Conclusion
By following this guide, you've successfully integrated Google Maps into your Laravel application. Your project now displays an interactive map centered on Jeddah Corniche, using a dynamically loaded API key stored securely in the .env file. The integration allows users to visualize locations within your application seamlessly. To ensure continued access, Google requires billing information, but the $200 monthly free credit covers most use cases. You can further enhance the map by adding custom markers, directions, and interactive features.
For more details, refer to the 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