user7435594
user7435594

Reputation:

How to get nearby courts from given lat long in laravel?

I want to get basketball courts on basis of given lat long in eloquent ORM. I tried to get that but here I got this error.

Call to undefined function App\Http\Controllers\Api\RADIANS()

is there any way to get nearby location using Eloquent if yes then how? please help me out I'm sharing me doings so far.

HomeCourt Controller

public function fetchHomeCourts(Request $request) {

    $validator = Validator::make(
        array(
            'lat' => $request->lat,
            'long' => $request->long,
        ),
        array(
            'lat' => 'required',
            'long' => 'required',
        )
    );
    if ($validator->fails()) {
        $this->setMeta("422", Constant::MSG_422);
        return response()->json($this->setResponse());
    }
    $homeCourt= HomeCourt::where(ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))*6380 < 10)->first();
    if(!$homeCourt) {
        $this->setMeta("200", "No courts found");
        $this->setData("homeCourts",$homeCourt);
        return response()->json($this->setResponse());
    }
    $this->setMeta("200", "Home court list");
    $this->setData("homeCourts",$homeCourt);
    return response()->json($this->setResponse());

}

Upvotes: 3

Views: 4587

Answers (4)

Abdullah Esnawi
Abdullah Esnawi

Reputation: 49

Implementation Using Google Places API

  1. Get a Google API Key from Google Cloud Console.
  2. Enable Places API in your Google Cloud project.
  3. Make an API request to fetch nearby courts.
  4. Filter courts and return the relevant data.

The code should be like controller below:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class CourtController extends Controller
{
    public function getNearbyCourts(Request $request)
    {
        $latitude = $request->input('latitude');
        $longitude = $request->input('longitude');
        $radius = $request->input('radius', 20000); // Default 20km, converted to meters
        $apiKey = config('services.google_places.api_key'); // Store API Key in env

        // Google Places API request
        $googleResponse = Http::get("https://maps.googleapis.com/maps/api/place/nearbysearch/json", [
            'location' => "$latitude,$longitude",
            'radius' => $radius,
            'keyword' => 'court', // Filter by courts
            'key' => $apiKey
        ]);

        // Decode Google API response
        $places = $googleResponse->json();
        
        if (!isset($places['results'])) {
            return response()->json(['error' => 'Failed to fetch nearby courts'], 500);
        }

        // Extract court details
        $courts = collect($places['results'])->map(function ($place) {
            return [
                'name' => $place['name'] ?? 'Unknown Court',
                'address' => $place['vicinity'] ?? 'No Address Available',
                'latitude' => $place['geometry']['location']['lat'],
                'longitude' => $place['geometry']['location']['lng'],
                'rating' => $place['rating'] ?? 'N/A',
                'place_id' => $place['place_id'],
            ];
        });

        return response()->json([
            'success' => true,
            'data' => $courts,
        ]);
    }
}

Upvotes: 0

Andres Felipe
Andres Felipe

Reputation: 4330

I have tried the above answer with no success, but thanks to @apokryfos answer i did this, so, this is my code, i put it in a raw DB query.

\DB::table("users")
     ->select("users.id", \DB::raw("6371 * acos(cos(radians(" . $this->lat . "))
     * cos(radians(users.latitude)) 
     * cos(radians(users.longitude) - radians(" . $this->lng . ")) 
     + sin(radians(" .$this->lat. ")) 
     * sin(radians(users.latitude))) AS distance"))
     ->having('distance', '<', $this->rad)
     ->first();

Upvotes: 1

apokryfos
apokryfos

Reputation: 40683

So this is what basically happens:

The user will give you the coordinates they are interested in (via a magic procedure, most pages supply a map that the users click on but it's really what is best for your users).

This is what your code needs to read:

public function fetchHomeCourts(Request $request) {

    $validator = Validator::make(
        array(
            'lat' => $request->lat,
            'long' => $request->long,
        ),
        array(
            'lat' => 'required',
            'long' => 'required',
        )
    );
    if ($validator->fails()) {
        $this->setMeta("422", Constant::MSG_422);
        return response()->json($this->setResponse());
    }
    $homeCourt= HomeCourt::whereRaw("ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))*6380 < 10")->first();
    if(!$homeCourt) {
        $this->setMeta("200", "No courts found");
        $this->setData("homeCourts",$homeCourt);
        return response()->json($this->setResponse());
    }
    $this->setMeta("200", "Home court list");
    $this->setData("homeCourts",$homeCourt);
    return response()->json($this->setResponse());

}

The whereRaw bit will pass that whole formula to MySQL directly instead of having Laravel trying to figure out how to build it into a query (since it's not a standard format that Laravel can handle.

From what I understand that formula is basically the for the distance on a the curved surface of the earth ( 6380 is the radius of earth in km and the rest looks like he arc-distance of two points).

Assuming that all courts you are interested in are stored in your database (you can either have a manual list or update them using some sort of overnight process to get it from somewhere) you don't need to run an API query on every request.

Upvotes: 1

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

This can only be done using Google Map Places Web Service API, this should help you get the functionality you're looking for.

A Nearby Search lets you search for places within a specified area. You can refine your search request by supplying keywords or specifying the type of place you are searching for.

A Nearby Search request is an HTTP URL of the following form:

https://maps.googleapis.com/maps/api/place/nearbysearch/output?parameters

where output may be either of the following values:

json (recommended) indicates output in JavaScript Object Notation (JSON)

xml indicates output as XML

Nearby search example

The following example is a search request for places of type 'restaurant' within a 500m radius of a point in Sydney, Australia, containing the word 'cruise':

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=500&type=restaurant&keyword=cruise&key=YOUR_API_KEY

Reference

Upvotes: 1

Related Questions