I have a project that will detect nearby markers/establishments based on the radius I set. I have 5km/3km/1km
selection. I temporarily set the center to a static lat
and lng
. In fetching the coordinates of the markers, I have a database for it and when calculating the coordinates. I use some formula that I found.
Here is my code in backend in fetching nearby markers based on the center marker
Static lat lng from frontend // lat: 1.3182001528756,lng: 103.84650707245
$km = $request->radius/1000; //1km
$centerLat = $request->centerLat;
$centerLng = $request->centerLng;
$ky = 40000 / 360;
$originParm = $centerLat.','.$centerLng;
$test = \DB::select(\DB::raw("SELECT school_name as name, lng, lat,
( 6371 * acos( cos( radians(" . $centerLat . ") )
* cos( radians( lat ) ) * cos( radians( lng ) - radians(" . $centerLng . ") )
+ sin( radians(" . $centerLat . ") ) * sin( radians( lat ) ) ) )
AS distance FROM xp_pn_schools HAVING distance < ".$km.""));
$test = json_decode(collect($test),true);
foreach($test as $data) {
$arr['data'][] = array(
'coord' => ['lat' => $data['lat'], 'lng' => $data['lng']],
'name' => ucwords(strtolower($data['name'])),
'distance' => $data['distance'],
);
$coordArr[] = $data['lat'].','.$data['lng']; //concat for google api link
}
Backend for using the goole distance matrix api (For getting the ETA and distance based on the location)
$destination = implode('|',$coordArr);
$ch = curl_init();
$url = 'https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins='.$originParm.'&destinations='.rawurlencode($destination).'&key=***********&mode=driving';
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$output = json_decode($output,true);
curl_close($ch);
return response()->json(array(
'markers' => $arr,
'time' => $output
));
But in my frontend when i check the response, I got something like
I set the radius for 1km or 1000 from my front end in order to render little results to compare
As what you can see the first result which is Farrer School
has a distance of 0.8 km
from the formula. But in the google maps api it is 2.1 km
. How can I verify which of the two is correct?