Skip to content
Somnio Technology Solutions Call Us
Banner 1

November 16th, 2023

Geospatial Solutions with Laravel + Redis

Let's say you want to find out the closest route to your new delivery client or develop an Uber-like service giving you know the closest drivers to the pickup point.

Redis has some amaing geospatial functions. In my case there are 2 GEO functions that will do the trick. GEOADD and GEORADIUS.

We will need to add the points we currently know to the index and then run the search. Once we find a point, we then get the route. Once you have the route, you can add new points if needed. You can used the same key for Redis if your sets are small. In my case, my $key is 'locations'.

public static function addSinglePointRedis($user_id,$route_name,$lat,$lng,$key)
{
    $temp = [];
    $temp[] = $key;
    $temp[] = (float) $lat;
    $temp[] = (float) $lng;
    $temp[] = $route_name.':'.$user_id;
    return Redis::command('GEOADD', $temp);
}

public static function getClosestPoint($lat,$lng,$key,$distance)
{
    $temp = [];
    $temp[] = $key;
    $temp[] = (float) $lng;
    $temp[] = (float) $lat;
    $temp[] = $distance;
    $temp[] = 'mi';//Miles
    $temp[] = 'WITHDIST';
    $temp[] = 'ASC';
    return Redis::command('GEORADIUS', $temp);
}

Now, lets put it all together.

$key='locations';
$distance=10; //If you are a Uber like service you can make this 20,30 or the distance you need 

//This step can be skip if you dont flush your Redis instance.
$getKnownPoints=Address::whereNotNull('route')
	->get()
    ->each(function($point){
    	self::addSinglePointRedis($point->user_id,$point->route,$point->lat,$point->lng,$key);
    });
    
$getUnknownPoints=Address::whereNull('route')
	->get();
    ->each(function($point)use($key,$distance){
    	$closest=self::getClosestPoint($point->lat,$point->lng,$key,$distance);
        if(empty($closest)){
         //No route in a 10 miles radious.
        }else{
        $route = $closest[0][0];
            $route = explode(':', $route);
            $point->route = $route[0];
            $route->save();
            self::addSinglePointRedis($point->user_id,$point->route,$point->lat,$point->lng,$key);
        }
    });

One of my clients spent 2 hours a day doing this manually. Now the process runs twice a day for 10 seconds savings hours of time.


Posted on: November 16th, 2023

Redis   Laravel   Geospatial  

Meet the author

Blog Author

Camilo Martinez

Software Developer

Camilo, has 15+ years as a full-stack software developer. His extensive expertise spans cloud solutions across industries like communication, transportation, education, healthcare, and e-commerce.

Subscribe to new posts

Want to work with us?

OUR PREVIOUS CLIENTS

Customer
Customer
Customer
Customer