Last Updated On - May 3rd, 2024 Published On - Apr 28, 2024
Introduction
Have you ever struggled to find the perfect address in your web application/project? The struggle ends here! In this tutorial, I’ll guide you through building a user-friendly location search feature like Uber’s, blinkit, Domino’s, that will seamlessly integrate with your application using the Google Maps API.
Expected Output
Prerequisites
- Basic knowledge of HTML & Javascript
Also Read: How to Integrate Google Calendar API Using Laravel 10 to Send Bulk Invites In 2024?
Obtaining Your Google Maps API Key
Visit the Google Cloud Platform Console (https://console.cloud.google.com/).
Create a new project (or use an existing one).
Enable the Google Places API Web Service
(https://developers.google.com/maps/documentation/javascript/overview).
Create and Secure API Key
Create an API key and restrict it to your application’s domain for security (https://developers.google.com/maps/api-security-best-practices).
Note: When you deploy your application to production, remove localhost from allowed domains list.
Project Setup
This is pure HTML and Javascript code, so you can implement it in any framework, language and frontend technology. I am using a free Bootstrap 5 template which you can download from https://themewagon.com/themes/jubilee/
Also Read: How to send notification to Microsoft Teams from Laravel 10?
Code Setup
Open index.html
and I am using the hero section form to display the search input and handle user interaction.
HTML
<div>
<form id="form" class="d-flex align-items-center position-relative ">
<input type="text" name="location" placeholder="Search your location"
class="form-control bg-white border-0 rounded-4 shadow-none px-4 py-3 w-100" id="txtLocation">
<button class="btn btn-primary rounded-4 px-3 py-2 position-absolute align-items-center m-1 end-0"><svg
xmlns="http://www.w3.org/2000/svg" width="22px" height="22px">
<use href="#search" />
</svg></button>
</form>
<div class="row">
<div class="col-md-12 mt-2">
<input type="text" name="formatted_address" placeholder="Address"
class="form-control bg-white border-0 rounded-4 shadow-none px-4 py-3 w-100" id="formatted_address">
</div>
<div class="col-md-12 mt-2">
<input type="text" name="latitude" placeholder="Latitude"
class="form-control bg-white border-0 rounded-4 shadow-none px-4 py-3 w-100" id="latitude">
</div>
<div class="col-md-12 mt-2">
<input type="text" name="longitude" placeholder="Longitude"
class="form-control bg-white border-0 rounded-4 shadow-none px-4 py-3 w-100" id="longitude">
</div>
</div>
</div>
Add Google Map Javascript API library just before closing the body tag.
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API_KEY&loading=async&libraries=places&callback=initialize"></script>
Javascript
Here is the javascript code to handle input and get the output from API
// Function to initialize Google Maps API and related services
function initialize() {
const input = document.getElementById("txtLocation"); // Get the search input field
// Options for the Autocomplete service
const options = {
fields: ["place_id", "formatted_address", "name"],
strictBounds: false,
types: ["establishment"], // Optionally filter suggestions to establishments
};
const geocoder = new google.maps.Geocoder; // Create a Geocoder object for address lookups
const autocomplete = new google.maps.places.Autocomplete(input, options); // Create Autocomplete service for location suggestions
// Disable type filtering by default (optional customization)
autocomplete.setTypes([]);
const infowindow = new google.maps.InfoWindow(); // Create an InfoWindow object (not used in this code)
// Add event listener for place selection
autocomplete.addListener("place_changed", () => {
infowindow.close(); // Close any existing InfoWindow
const place = autocomplete.getPlace(); // Get the selected place object
console.log('Place:', place); // Log the place object for debugging
// Reverse geocode using place ID to get full address
geocoder.geocode({'placeId': place.place_id}, function (results, status) {
if (results.length > 0) {
document.getElementById("formatted_address").value = results[0].formatted_address;
}
if (status === google.maps.GeocoderStatus.OK) {
const lat = results[0].geometry.location.lat();
const lng = results[0].geometry.location.lng();
setLocationCoordinates(lat, lng); // Update latitude and longitude fields
}
});
});
}
// Function to update latitude and longitude input fields
function setLocationCoordinates(lat, lng) {
const latitudeField = document.getElementById("latitude");
const longitudeField = document.getElementById("longitude");
latitudeField.value = lat;
longitudeField.value = lng;
}
Explanation
- The code loads the Google Maps API with your API key and the
places
library, enabling location suggestions. - The
initialize()
function sets up the Google Places Autocomplete service, linking it to the input field with IDtxtLocation
. - The
place_changed
event listener captures the selected location data, which you can log to the console for testing or use for further functionality.
Overall functionality
- When the user enters a location in the search box (
txtLocation
), the Autocomplete service suggests matching locations. - When the user selects a suggestion, the geocoding process retrieves the full address and coordinates.
- The retrieved address populates the
formatted_address
field, while the latitude and longitude values are displayed in the dedicated fieldslatitude
andlongitude
respectively.
Beyond the Basics (Optional)
- Implement error handling for potential API errors.
- Enhance security by validating and sanitizing user input.
- Integrate the retrieved location data with your application’s features:
- Display the location on a map.
- Store the address details for user preferences.
- Use the coordinates for distance calculations or fare estimations.
FAQs
What is location search?
Location search is a functionality that enables users to find places or businesses around them. It leverages location data and mapping services to provide accurate and relevant results.
How does location search with Google Maps API work?
Google Maps API offers a suite of tools and services to implement location search functionality. Users can enter a search query or allow the app to access their current location. The API then fetches relevant places based on the search query or user’s location data and displays them on a map.
What are the benefits of using Google Maps API for location search?
Google Maps API offers several advantages for location search integration:
Accuracy and Reliability: Utilize Google’s extensive database of locations and business listings to ensure accuracy and reliability.
Customization: You can customize the search experience according to your specific requirements and brand identity.
Rich User Experience: Improve user engagement by incorporating interactive maps and location data for a richer user experience.
How to implement location search with Google Maps API?
Implementing location search involves integrating the Google Maps API into your web application. The API provides various tools and services to achieve this functionality. This blog post itself is a complete tutorial for the same. Refer to the Google Maps API documentation for detailed instructions and code examples.
Are there any limitations on using Google Maps API for location search?
While Google Maps API offers a powerful solution for location search, it’s important to consider some limitations:
Quotas and Billing: Free plans come with usage limits. Be mindful of your quota usage and billing costs for exceeding them.
Data Accuracy: While Google strives for accuracy, location data may not always be perfect. Consider implementing mechanisms to handle potential inaccuracies.
Conclusion
By following these steps, you’ve successfully implemented a user-friendly location search feature in your application using the Google Maps API. This empowers your users to find their destinations effortlessly, enhancing the overall experience.
Note: The above code snippet focuses on the search functionality. If you want to display the selected location on a map, you’ll need additional code to integrate the Google Maps API and create a map element.