Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
function distance($lat1, $lng1, $lat2, $lng2)
{
// convert latitude/longitude degrees for both coordinates
// to radians: radian = degree * π / 180
$lat1 = deg2rad($lat1);
$lng1 = deg2rad($lng1);
$lat2 = deg2rad($lat2);
$lng2 = deg2rad($lng2);
// calculate great-circle distance
$distance = acos(sin($lat1) * sin($lat2) + cos($lat1) * cos($lat2) * cos($lng1 - $lng2));
// distance in human-readable format:
// earth's radius in km = ~6371
return 6371 * $distance;
}
function search()
{
// we'll want everything within, say, 10km distance
$distance = 10;
// earth's radius in km = ~6371
$radius = 6371;
$lat = 60.494717;
$lng = -151.06813;
// latitude boundaries
$maxlat = $lat + rad2deg($distance / $radius);
$minlat = $lat - rad2deg($distance / $radius);
// longitude boundaries (longitude gets smaller when latitude increases)
$maxlng = $lng + rad2deg($distance / $radius / cos(deg2rad($lat)));
$minlng = $lng - rad2deg($distance / $radius / cos(deg2rad($lat)));
$jewel = \DB::connection('jewel');
$stores = $jewel->table('wp_blue_stores')->whereBetween('lat', [
$minlat,
$maxlat
])->whereBetween('long', [$minlng, $maxlng])->get();
$result = $stores->pluck('account_id')->toArray();
foreach ($stores as $index => $store) {
$resultDistance = distance($lat, $lng, $store->lat, $store->long);
if ($resultDistance > $distance) {
unset($stores[$index]);
}
}
dd($stores->pluck('account_id')->toArray(), $result);
}
// Reference: https://www.mullie.eu/geographic-searches/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment