Skip to content

Instantly share code, notes, and snippets.

@gormus
Forked from tscheepers/GeoSpatialThingController.php
Created April 23, 2016 04:40
Show Gist options
  • Select an option

  • Save gormus/5af72dd994784e4b9712d93885fc3c56 to your computer and use it in GitHub Desktop.

Select an option

Save gormus/5af72dd994784e4b9712d93885fc3c56 to your computer and use it in GitHub Desktop.
Geospatial sort by distance using Laravel 4 and MySQL. I'm using a point column named geolocation in a table called meetings.
<?php
class MeetingsController extends \BaseController {
/**
* Display a listing of the resource.
* GET /meetings
*
* @return Response
*/
public function index()
{
// Using fairly new ST_Distance and ST_Within function in MySQL
$lat = 6.0;
$lon = 52.0;
$maximumDistance = 1000;
$lonBound1 = $lon - $maximumDistance / abs(cos(deg2rad($lat)) * 69);
$lonBound2 = $lon + $maximumDistance / abs(cos(deg2rad($lat)) * 69);
$latBound1 = $lat - ($maximumDistance / 69);
$latBound2 = $lat + ($maximumDistance / 69);
$meetings = Meeting::whereRaw("
ST_Within(
geolocation,
envelope(
linestring(
point($lonBound1, $latBound1),
point($lonBound2, $latBound2)
)
)
)")->orderByRaw("
ST_Distance(
geolocation,
GeomFromText('POINT($lat $lon)')
)")->get();
return $meetings;
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateMeetingsTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('meetings', function(Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->timestamps();
});
DB::statement("ALTER TABLE meetings ADD COLUMN geolocation POINT");
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('meetings');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment