Google Maps Integration with Property Pins: Complete Guide
This tutorial will walk you through integrating Google Maps with custom property pins for a real estate website. I'll provide the complete code and explain each step.
Step 1: Set Up Google Maps API
First, you need a Google Maps API key:
- Go to Google Cloud Console
- Create a new project
- Enable "Maps JavaScript API" and "Geocoding API"
- Create an API key
Step 2: HTML Structure
<!DOCTYPE html>
<html>
<head>
<title>Property Map</title>
<style>
#map {
height: 600px;
width: 100%;
}
.property-info {
padding: 10px;
max-width: 200px;
}
.property-info img {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<div id="map"></div>
<!-- Load Google Maps API -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
<!-- Our custom script -->
<script src="map.js"></script>
</body>
</html>
Step 3: JavaScript Implementation (map.js)
// Property data - would typically come from your database
const properties = [
{
id: 1,
title: "Luxury Apartment",
address: "123 Main St, Noida",
price: "₹75,00,000",
bedrooms: 3,
bathrooms: 2,
sqft: 1800,
image: "property1.jpg",
lat: 28.5355,
lng: 77.3910
},
{
id: 2,
title: "Commercial Space",
address: "456 Market Rd, Noida",
price: "₹1,20,00,000",
type: "Commercial",
sqft: 3500,
image: "property2.jpg",
lat: 28.5412,
lng: 77.4023
}
];
// Custom pin icon
const propertyIcon = {
url: "https://maps.google.com/mapfiles/kml/pal3/icon21.png",
scaledSize: new google.maps.Size(32, 32)
};
function initMap() {
// Center map on Noida
const noida = { lat: 28.5355, lng: 77.3910 };
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 13,
center: noida
});
// Create markers for each property
properties.forEach(property => {
const marker = new google.maps.Marker({
position: { lat: property.lat, lng: property.lng },
map: map,
title: property.title,
icon: propertyIcon
});
// Create info window content
const contentString = `
<div class="property-info">
<h3>${property.title}</h3>
${property.image ? `<img src="${property.image}" alt="${property.title}">` : ''}
<p><strong>Price:</strong> ${property.price}</p>
<p><strong>Address:</strong> ${property.address}</p>
${property.bedrooms ? `<p><strong>Bedrooms:</strong> ${property.bedrooms}</p>` : ''}
${property.bathrooms ? `<p><strong>Bathrooms:</strong> ${property.bathrooms}</p>` : ''}
<p><strong>Area:</strong> ${property.sqft} sq.ft.</p>
<button onclick="viewProperty(${property.id})">View Details</button>
</div>
`;
// Create info window
const infowindow = new google.maps.InfoWindow({
content: contentString
});
// Add click event to marker
marker.addListener("click", () => {
infowindow.open(map, marker);
});
});
}
// Function to handle property viewing
function viewProperty(id) {
// In a real app, this would redirect to property page
console.log(`Viewing property ${id}`);
// window.location.href = `/property/${id}`;
}
Step 4: Adding Geocoding (Optional)
If you don't have latitude/longitude for properties, add this function:
async function geocodeAddress(address) {
const geocoder = new google.maps.Geocoder();
return new Promise((resolve, reject) => {
geocoder.geocode({ address }, (results, status) => {
if (status === "OK" && results[0]) {
const location = results[0].geometry.location;
resolve({
lat: location.lat(),
lng: location.lng()
});
} else {
reject("Geocode failed: " + status);
}
});
});
}
// Usage example:
// const coords = await geocodeAddress("123 Main St, Noida");
Step 5: Advanced Features
Cluster Markers for Many Properties
Add this to your HTML head:
<script src="https://unpkg.com/@googlemaps/markerclusterer/dist/index.min.js"></script>
Then modify your initMap function:
function initMap() {
// ... previous map setup code ...
const markers = properties.map(property => {
return new google.maps.Marker({
position: { lat: property.lat, lng: property.lng },
map: map,
title: property.title,
icon: propertyIcon
});
});
// Add marker clusterer
new markerClusterer.MarkerClusterer({ map, markers });
}
Step 6: Making It Dynamic
In a real application, you would fetch properties from your backend:
async function fetchProperties() {
try {
const response = await fetch('/api/properties');
return await response.json();
} catch (error) {
console.error('Error fetching properties:', error);
return [];
}
}
// Modified initMap
async function initMap() {
const properties = await fetchProperties();
// Rest of your map initialization code
}
Complete Implementation Notes
-
API Key Security: Never expose your API key in frontend code in production. Instead:
- Use a proxy server
- Restrict the key to your domain
- Implement usage quotas
-
Performance Optimization:
- Load markers in batches for large datasets
- Implement viewport filtering to only load visible properties
- Use server-side clustering for thousands of properties
-
Customization Options:
- Different pin colors for property types (residential/commercial)
- Heatmaps for price distribution
- Drawing tools for area selection
-
Mobile Considerations:
- Add touch event handlers
- Implement geolocation for "Near Me" functionality
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
map.setCenter({
lat: position.coords.latitude,
lng: position.coords.longitude
});
});
}
This implementation provides a complete solution for displaying properties on Google Maps with custom pins and information windows. The code is ready to integrate with your real estate website and can be extended with additional features as needed.
Written by think4buysale.in Software and ompropertydealer.com
Top comments (0)