How to Add Geolocation-Based Property Search & Map Integration in Laravel for an Airbnb Clone with External APIs?

How to Add Geolocation-Based Property Search & Map Integration in Laravel for an Airbnb Clone with External APIs? - Cron24 Technologies

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:

  1. Install Leaflet and Leaflet.markercluster via npm:
npm install leaflet leaflet.markercluster
  1. Create a Vue component or use JavaScript to integrate the map into your frontend. Here’s a simplified example:
<template>
  <div>
    <div id="map"></div>
    <div>
      Latitude: <input v-model="latitude" />
      Longitude: <input v-model="longitude" />
      Radius (km): <input v-model="radius" />
      <button @click="searchProperties">Search</button>
    </div>
    <ul>
      <li v-for="property in properties" :key="property.id">
        {{ property.title }} - {{ property.distance }} km away
      </li>
    </ul>
  </div>
</template>

<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>

<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 Tips:
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 PHP Laravel code. It includes lots of readymade functionalities like inbuilt Google Maps, geolocation-based search google auto-complete search etc.,

This script gives aspiring entrepreneurs a head start, saving time and effort. Using this 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.