Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Aslam97/7bbb7b9cab03bffb882cfa712cdec7e5 to your computer and use it in GitHub Desktop.
Save Aslam97/7bbb7b9cab03bffb882cfa712cdec7e5 to your computer and use it in GitHub Desktop.
Display data with the maximum distance using latitude and longitude

Example showing Product with max distance radius from latitude and longitude

  • Model Query Scope
    public function scopeIsWithinMaxDistance($query, $latitude, $longitude, $radius = 25)
    {
        // for miles you'd use 3961 instead of 6371 (Kilometer)
        $sql = "(6371 * acos(cos(radians($latitude))
                        * cos(radians(address.latitude))
                        * cos(radians(address.longitude)
                        - radians($longitude))
                        + sin(radians($latitude))
                        * sin(radians(address.latitude))))";

        return $query
            ->select('*')
            ->selectRaw("{$sql} AS distance")
            ->whereRaw("{$sql} < ?", [$radius]);
    }
  • Controller
        $latitude = '-6.121435';
        $longitude = '106.774124';
        $radius = 7;
        
        $x = Product::whereHas('address', function ($query) use ($latitude, $longitude, $radius) {
            $query->isWithinMaxDistance($latitude, $longitude, $radius);
        })->with('address')->get();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment