0

I am capturing users current location lat long and comparing it with specific location lat long(location lat long stored in db) and comparing both, if user lat long is more than 200 meters show message you are outside 200 meters, but in output I am getting wrong value it is showing 122 km which is not correct.

Code:

function check_distance($lat1, $lat2, $long1, $long2) {
        $url = "https://maps.googleapis.com/maps/api/distancematrix/json?key=my_api_key" . $lat1 . "," . $long1 . "&destinations=" . $lat2 . "," . $long2 . "&mode=driving&language=en";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $response = curl_exec($ch);
        curl_close($ch);
        $response_a = json_decode($response, true);
        $dist_value = $response_a['rows'][0]['elements'][0]['distance']['value'];
        if($distance_value>200 meters){
        // show more than 200 meters from specific location 
        }
    }

echo check_distance($lat1, $lat2, $long1, $long2);
user_1234
  • 741
  • 1
  • 9
  • 22
  • 1
    Shouldn't you have `&origins=` or something before you add `$lat1` and `$long1`? Now you're appending those to the `key` value, like `json?key=my_api_key123,123` – M. Eriksson Oct 03 '20 at 08:22
  • @MagnusEriksson yes I am passing lat long to url – user_1234 Oct 03 '20 at 08:26
  • I said that you're missing the key for the lat1 and long1 values. – M. Eriksson Oct 03 '20 at 08:58
  • You say 122 km is not correct, does that mean you are checking some known lat long with the database lat long? If so, have you verified that those are indeed being passed correctly to the function and that the $url is correct? Have you tested any other known coordinates by hard coding them into a test rather than relying on extracting from the database? – Mark Oct 03 '20 at 12:41
  • 1
    Have you tried making use of [HTML 5 Geolocation](https://developers.google.com/maps/documentation/javascript/examples/map-geolocation) instead of getting the coordinates from your database? Because your database may not always be accurate enough to give you your desired results – Ricky Cuarez Oct 06 '20 at 04:04

0 Answers0