How to Add Geolocation-Based Property Search & Map Integration in Laravel for an Airbnb Clone with External APIs?
Richardson
Posted on October 10, 2023
Implementing geolocation-based search and map integration in a Laravel application, such as an Airbnb clone, involves several steps. In this example, I'll guide you through the process of setting up a geolocation-based property search using the Google Maps API and Laravel.
Step 1: Set Up a Laravel Project
If you haven't already, create a new Laravel project:
composer create-project --prefer-dist laravel/laravel airbnb-clone
cd airbnb-clone
Step 2: Configure Your Database
Set up your database connection in the .env file and run migrations to create a properties table:
php artisan make:model Property -m
php artisan migrate
Define the schema for your properties table in the generated migration file (database/migrations/YYYY_MM_DD_create_properties_table.php):
public function up()
{
Schema::create('properties', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('description');
$table->decimal('latitude', 10, 7);
$table->decimal('longitude', 10, 7);
$table->timestamps();
});
}
Step 3: Create a Property Model and Seeder
Define the Property model (app/Models/Property.php) and create a seeder to populate the database with sample properties:
php artisan make:seeder PropertySeeder
In Property.php, add the fillable fields and define a scope for geolocation-based search:
protected $fillable = ['title', 'description', 'latitude', 'longitude'];
public function scopeWithinDistance($query, $latitude, $longitude, $radius = 10)
{
return $query
->select('id', 'title', 'description', 'latitude', 'longitude')
->selectRaw(
"(6371 * acos(cos(radians(?)) * cos(radians(latitude)) * cos(radians(longitude) - radians(?)) + sin(radians(?)) * sin(radians(latitude)))) AS distance",
[$latitude, $longitude, $latitude]
)
->having('distance', '<=', $radius);
}
In PropertySeeder.php, seed some sample data with coordinates:
use Illuminate\Database\Seeder;
use App\Models\Property;
class PropertySeeder extends Seeder
{
public function run()
{
Property::create([
'title' => 'Cozy Apartment',
'description' => 'A comfortable apartment in the city center.',
'latitude' => 40.7128,
'longitude' => -74.0060,
]);
// Add more properties here...
}
}
Run the seeder to populate the database:
php artisan db:seed --class=PropertySeeder
Step 4: Create the Search Controller
Generate a controller for property search:
php artisan make:controller PropertyController
In PropertyController.php, create a method for geolocation-based search:
use Illuminate\Http\Request;
use App\Models\Property;
public function search(Request $request)
{
$latitude = $request->input('latitude');
$longitude = $request->input('longitude');
$radius = $request->input('radius', 10); // Default radius is 10 kilometers
$properties = Property::withinDistance($latitude, $longitude, $radius)->get();
return response()->json(['properties' => $properties]);
}
Step 5: Set Up Routes
Define the API route for property search in routes/api.php:
Route::get('/properties/search', 'PropertyController@search');
Step 6: Create the Frontend
For the frontend, you can use JavaScript and a mapping library like Leaflet or Google Maps. Here's an example using Leaflet:
- Install Leaflet and Leaflet.markercluster via npm:
npm install leaflet leaflet.markercluster
- Create a Vue component or use JavaScript to integrate the map into your frontend. Here's a simplified example:
<!-- Vue Component Template -->
<template>
<!-- Map Container -->
<div>
<div id="map"></div>
<!-- Search Inputs -->
<div>
Latitude: <input v-model="latitude" />
Longitude: <input v-model="longitude" />
Radius (km): <input v-model="radius" />
<button @click="searchProperties">Search</button>
</div>
<!-- Property List -->
<ul>
<li v-for="property in properties" :key="property.id">
{{ property.title }} - {{ property.distance }} km away
</li>
</ul>
</div>
</template>
<!-- Vue Component Script -->
<script>
import L from 'leaflet';
export default {
data() {
return {
latitude: 0,
longitude: 0,
radius: 10,
properties: [],
map: null,
};
},
mounted() {
this.map = L.map('map').setView([this.latitude, this.longitude], 10);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(this.map);
},
methods: {
searchProperties() {
axios
.get(`/api/properties/search?latitude=${this.latitude}&longitude=${this.longitude}&radius=${this.radius}`)
.then((response) => {
this.properties = response.data.properties;
this.updateMarkers();
})
.catch((error) => {
console.error(error);
});
},
updateMarkers() {
// Clear existing markers
this.map.eachLayer((layer) => {
if (layer instanceof L.Marker) {
this.map.removeLayer(layer);
}
});
// Add new markers
this.properties.forEach((property) => {
L.marker([property.latitude, property.longitude])
.addTo(this.map)
.bindPopup(property.title);
});
},
},
};
</script>
<!-- Vue Component Styles -->
<style>
#map {
height: 400px;
}
</style>
Step 7: Start Your Development Server
Run your Laravel development server and compile your frontend assets:
php artisan serve
npm run dev
Now, when you access your application, you should have a simple geolocation-based property search and map integration using Laravel, Vue.js, and the Google Maps API.
Remember to customize and enhance this example to fit the specific requirements of your Airbnb clone. Additionally, consider implementing user authentication and security measures when handling user-generated data and location information.
Pro Tip:
Speed up your short-term vacation property rental business dreams with "Hyra" by Cron24 Technologies. It's a ready-made Airbnb clone script crafted with powerful Laravel code. It includes lots of ready-made functionalities like inbuilt Google Maps, geolocation-based search, Google auto-complete search, and more. This script gives aspiring entrepreneurs a head start, saving time and effort.
Using the Hyra software, you can launch your rental platform faster and focus on making it your own. Start your journey to success with this pre-built solution with splendid 24/7 technical and customer care support!
Thank you for your time.
Posted on October 10, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 10, 2023