Having an interactive map on your website can significantly enhance the user experience, especially if you're running a business that requires location-based searches. In this blog post, we’ll go through the steps to embed a Google Maps iFrame with a custom search feature, allowing users to enter an address and find locations directly from your Wix website.
To learn more about setting up multiple markers on Google Maps using Wix Velo, check out this detailed guide: Google Maps Customization with Wix Velo - Dynamic Markers.
Struggling with the technical details? Let CodeMasters handle the setup for you!
Step 1: Get Google Maps API Key
To create a custom map with search functionality, you’ll need to use the Google Maps API. Start by obtaining an API key.
Go to the Google Cloud Platform Console.
Click the project drop-down and create a new project.
Once you're in your project, go to the navigation menu and select APIs & Services > Dashboard.
Click “ENABLE APIS AND SERVICES”.
Search for "Google Maps JavaScript API" and click on it.
Click "Enable".
In the credentials tab, click “Create credentials” and choose API key.
Note: Make sure to secure your API key by restricting it to your website's domain.
Step 2: Embed Google Maps iframe on Wix
Now that you have your API key, it’s time to embed the map into your Wix website.
Log in to your Wix account and select the website you want to edit.
Click on ‘Edit Site’ to enter the Wix website editor.
Navigate to the page where you want to add the Google Maps.
Click on the ‘Add’ (+) button on the left-hand side menu.
Select ‘Embed’ from the dropdown menu and then choose ‘HTML iFrame’.
An HTML widget will appear on your page. Click on it to access the settings.
Choose the ‘Enter Code’ option and paste the following code, replacing YOUR_API_KEY with the API key you obtained earlier:
<!DOCTYPE html>
<html>
<head>
<title>Google Maps</title>
<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]"></script>
<script>
let map;
let marker;
function initMap() {
// Initial Toronto coordinates
const lat = 43.65107;
const lng = -79.347015;
// Map options
const mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
zoomControl: true,
fullscreenControl: true,
scrollwheel: true,
};
// Create the map
map = new google.maps.Map(document.getElementById("map"), mapOptions);
// Add an initial marker
marker = new google.maps.Marker({
position: { lat, lng },
map,
title: "Toronto"
});
// Listen for postMessage updates
window.addEventListener('message', function(event) {
if (event.data && event.data.type === 'updateMapCenter') {
updateMapCenter(event.data.lat, event.data.lng, event.data.zoom);
}
});
}
function updateMapCenter(lat, lng, zoom) {
const newCenter = new google.maps.LatLng(lat, lng);
map.setCenter(newCenter);
map.setZoom(zoom);
// Update the marker's position
marker.setPosition(newCenter);
}
</script>
<style>
/* Ensure proper rendering and no scrollbars */
html, body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
}
#map {
width: 100%;
height: 100%;
}
</style>
</head>
<body onload="initMap()">
<div id="map"></div>
</body>
</html>
Explanation
1. Google Maps API Setup: The code starts by loading the Google Maps API through a <script> tag, using a URL that includes your API key (replace [YOUR_API_KEY] with your actual key). This API is essential for rendering the map and enabling Google Maps features on your webpage.
2. initMap() Function: This function initializes the map with specific settings:
Center: The map is centered at predefined latitude and longitude.
Zoom Level: Set to 6 for a medium-range view.
Map Type: Displays terrain details (google.maps.MapTypeId.TERRAIN).
Controls: Street view, zoom, fullscreen, and scrollwheel are disabled for a customized experience.
3. updateMapCenter(lat, lng, zoom) Function: This function dynamically updates the map's center and zoom level based on provided latitude, longitude, and zoom values. It ensures the map can adapt in real-time.
4. Dynamic Updates with Event Listener: The code listens for messages using window.postMessage(). When a message contains new coordinates, the map updates instantly. This feature is perfect for applications requiring real-time map adjustments.
Struggling to make your Google Maps integration dynamic? Our experts at CodeMasters can help you create a fully functional, customized solution. Contact us now to get started!
Step 3: Add Velo Code to Capture the User's Address Input and Send Coordinates to the iFrame
First, let's add the address input field
Add Element: In the Wix Editor, click the '+' button on the left-hand side toolbar to add an element to your page.
Choose Input Element: Under the “Input” category, you’ll find "Address Input". Click on it.
Customize the Input Element: Once the input field is on your page, you can click on it to customize its properties, such as placeholder text, font, color, and more.
Configure the Input Element: Click on the input field and then click on the 'Settings' button (looks like a gear) to set up properties such as whether the input is required, what type of text validation is used, etc.
$w('#addressInput1').onChange((event) => {
let Address = $w("#addressInput1").value;
// Ensure Address contains valid location data
if (Address.location && Address.location.latitude && Address.location.longitude) {
let latitude = Address.location.latitude;
let longitude = Address.location.longitude;
// Send a message to the iframe (Google Map) to update the center and marker
$w('#GoogleMap').postMessage({
type: 'updateMapCenter',
lat: latitude,
lng: longitude,
zoom: 10 // Adjust the zoom level if needed
});
} else {
console.error("Invalid location data in Address input");
}
});
Explanation
Event Listener for Address Input
The code listens for changes in the Address Input field using $w('#addressInput1').onChange(). When a user types or selects an address, this function is triggered.
Extract Location Data
The entered address is accessed via $w("#addressInput1").value. To ensure the address is valid, the code checks for the presence of location.latitude and location.longitude.
Send Map Update Request
If the address contains valid latitude and longitude values, a message is sent to the Google Map iframe using $w('#GoogleMap').postMessage().
The message includes:
type: Specifies the message type (updateMapCenter).
lat and lng: The new latitude and longitude values to center the map.
zoom: An optional zoom level for the map.
Error Handling
If the address lacks valid location data, an error message is logged using console.error() to inform developers of the issue.
Watch the Integration in Action!
Join us as we bring the steps from this blog post to life in our YouTube tutorial. In the video, we walk you through every detail—copying and pasting the code, integrating Google Maps, and enabling dynamic updates with an address input field and API key on your Wix Studio site. Whether you're new to web development or a seasoned pro, this guide simplifies the process and ensures your site is interactive and functional. Watch now to transform your website with Google Maps integration!
Wrapping Up
In conclusion, integrating Google Maps into your Wix website with a custom address search functionality is a powerful feature. Not only does it enhance user experience, but it also adds an interactive element that can be invaluable for businesses looking to provide location-based information. Keep in mind the importance of writing clean and efficient code, as this forms the backbone of such features.
Now, what if you need advanced customization or encounter challenges you cannot surmount on your own? This is where CodeMasters Agency comes in.
Connect with CodeMasters Agency.
CodeMasters Agency specializes in web development, and their team of experts is adept at integrating various functionalities into websites. Whether it's Google Maps integration or any other advanced feature, CodeMasters Agency has the expertise to make your website stand out.
Don't leave your website in the hands of chance; let professionals handle it. Contact CodeMasters Agency today.
Sign up for free and unlock over $300 in exclusive deals on top SaaS tools like LinkedIn credits, QuickBooks, SEMrush, and more! Explore Deals