Search code examples
phpmysqligoogle-geolocation

Getting values of lattitude longitude as null. PHP


I have a table of venues, which has column of latitude ,longitude, which states it's location. I want to get the locations from venues table and get the locations which are near to the current location of the user.

Current location would be given as a parameters to the function.

For this 1st I tried to get all the latitude and longitude from the venues table created an array of it.

Then I tried to calculate the distance for each venue in venues array. But distance array is seems to be 0,0. The values of $lat1,$lon1,$lat2,$lon2 are being null.

I am new to php so no idea how to do this.

I want to return the locations which are near 10 km from the current location of the user.

search function :

  public function searchVendors($lat1,$lon1)
    {
      //  $lat2 = -10.4212157;
      //  $lon2 = 28.6031842;

      // $lat1 = 19.9950050;
      // $lon1 = 73.8413080;

    try{

   //  $lat1 = $fields -> lat1;
   //  $lon1 = $fields -> lon1;

     $con = DB::getConnection();

     $query = "SELECT `lattitude`,`longitude` FROM venues";

     $rs = mysqli_query($con,$query) or die (json_encode(array("result"=>-1, "message"=>mysqli_error())));
     $n = mysqli_num_rows($rs);

     $venues = array();

     if ( $n > 0 ) {

     while ( $row = mysqli_fetch_assoc($rs)) {
        $venues[] = $row;
     }

     $distances = array();

     foreach($venues as $venue)
     {
        $lat2 = $venue -> lattitude;
        $lon2 = $venue -> longitude;

        $dist = $this -> distance($lat1, $lon1, $lat2, $lon2);

        $distances[] = $dist;

     }
        echo $lat1;
        echo $lon1;
        echo $lat2;
        echo $lon2;

        $result = array("lat1" => $lat1,"lon1" =>$lon1,"lat2" => $lat2 ,"lon2" => $lon2, "result"=>1, "message"=>"success", "distances" => $distances);
        return json_encode($result);

     } else {
        $result = array("result"=>-1, "message"=>"Distances list is empty");
        return json_encode($result);
     }
     } catch(DBConnectionException $e) {
        $result = array("result"=>-1, "message"=> $e -> getMessage());
        return json_encode($result);
     }
        return null;
    }

getVendors php

   <?php

header("Content-type: application/json");

    if ( $_SERVER['REQUEST_METHOD']=='POST') {
        include_once ("../include/Vendor.php");
    try {

    $con = DB::getConnection();

    $raw = file_get_contents("php://input");
    $data = json_decode($raw, true);

    $lat1 = $data -> lattitude;
    $lon1 = $data -> longitude;

    echo $lat1;
    echo $lon1;

    $v = new Vendor();
    $response = $v -> searchVendors($lat1,$lon1);

    json_encode($response);


    if ( $response == null ) {
            $response = json_encode(array("result" => -2, "message" => "Empty result"));
            echo $response;
        } else {
            echo $response;
        }
    } catch(Exception $e) {
        $result = array("result" => -1, "message" => $e -> getMessage());
        echo json_encode($result);
        }
}

?>

Input I am passing from postman is :

{

    "lat1" : "19.9764360",
    "lon1" : "73.8573440"

}

Output I get is :

{
  "lat1": null,
  "lon1": null,
  "lat2": null,
  "lon2": null,
  "result": 1,
  "message": "success",
  "distances": [
    0,
    0,
    0,
    0,
    0,
    0,
    0,
    0
  ]
}

EDIT : As answered by RigsFolly

getVendors php:

    <?php

header("Content-type: application/json");

    if ( $_SERVER['REQUEST_METHOD']=='POST') {
        include_once ("../include/Vendor.php");
    try {

    $con = DB::getConnection();

    $raw = file_get_contents("php://input");
    $data = json_decode($raw);          // now its an object if it was stored as an object

    $lat1 = $data -> lattitude;
    $lon1 = $data -> longitude;

    echo $lat1;
    echo $lon1;

    $v = new Vendor();
    $response = $v -> searchVendors($data);

    json_encode($response);

    if ( $response == null ) {
            $response = json_encode(array("result" => -2, "message" => "Empty result"));
            echo $response;
        } else {
            echo $response;
        }
    } catch(Exception $e) {
        $result = array("result" => -1, "message" => $e -> getMessage());
        echo json_encode($result);
        }
}

?>

search function:

  public function searchVendors($fields)
    {

    try{

     $con = DB::getConnection();

     $query = "SELECT `lattitude`,`longitude` FROM venues";

     $rs = mysqli_query($con,$query) or die (json_encode(array("result"=>-1, "message"=>mysqli_error())));
     $n = mysqli_num_rows($rs);

     $venues = array();

     $lat1 = $fields -> lattitude;
     $lon1 = $fields -> longitude;

     if ( $n > 0 ) {

     while ( $row = mysqli_fetch_object($rs)) {
    $venues[] = $row;
 }

 $distances = array();

 foreach($venues as $venue)
 {
    $lat2 = $venue -> lattitude;
    $lon2 = $venue -> longitude;

    $dist = $this -> distance($lat1, $lon1, $lat2, $lon2);

    $distances[] = $dist;

 }
        echo $lat1;
        echo $lon1;
        echo $lat2;
        echo $lon2;

        $result = array("lat1" => $lat1,"lon1" =>$lon1,"lat2" => $lat2 ,"lon2" => $lon2, "result"=>1, "message"=>"success", "distances" => $distances);
        return json_encode($result);

     } else {
        $result = array("result"=>-1, "message"=>"Distances list is empty");
        return json_encode($result);
     }
     } catch(DBConnectionException $e) {
        $result = array("result"=>-1, "message"=> $e -> getMessage());
        return json_encode($result);
     }
        return null;
    }

I am getting output as:

    {
  "lat1": null,
  "lon1": null,
  "lat2": "-2.6357434",
  "lon2": "18.4276047",
  "result": 1,
  "message": "success",
  "distances": [
    8321.16,
    8322.48,
    8321.37,
    2617.96,
    0,
    2535.52,
    3368.05,
    2069.09
  ]
}

lat1,lon1 still seems empty, and is distance is right? How can I get it in kilometers?

distance function:

  public function distance($lat1, $lon1, $lat2, $lon2) {

        $theta = $lon1 - $lon2;
        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = strtoupper($unit);

        $km = $miles * 1.609344;

        $result = round($km ,2);

        return $result;
    }

What's wrong here? Can anyone help please? Thank you..


Solution

  • You used mysqli_fetch_assoc so $row will be a associative array and not an object. So either use mysqli_fetch_object or reference this as $lat2 = $venue['lattitude'];

    I suggest amending the mysqli_fetch_assoc to mysqli_fetch_object, less code to amend!

     //while ( $row = mysqli_fetch_assoc($rs)) {
     while ( $row = mysqli_fetch_object($rs)) {
        $venues[] = $row;
     }
    
     $distances = array();
    
     foreach($venues as $venue)
     {
        $lat2 = $venue -> lat1;     // name corrected
        $lon2 = $venue -> lon1;     // name corrected
    
        $dist = $this -> distance($lat1, $lon1, $lat2, $lon2);
    
        $distances[] = $dist;
    
     }
    

    Also in getVendors you convert the json string to an array.

    You are passing it from javascript as an object so use it as one, like this

    //$data = json_decode($raw, true);  // true = convert to array
    $data = json_decode($raw);          // now its an object if it was stored as an object
    
    $lat1 = $data -> lattitude;
    $lon1 = $data -> longitude;