Friday, 17 February 2017

Calculate Distance Through Google Maps

Make this Function into your Model in CodeIgniter.

function getdist($addrFrom, $addrTo, $measurement){

    $formattedaddressFrom = str_replace(' ','+',$addrFrom);
    $formattedaddressTo = str_replace(' ','+',$addrTo);
   
    //Send request and receive data through json
      $mapcodeFrom = getfile_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedaddressFrom.'&sensor=false');
    $outcomeFrom = json_decode($mapcodeFrom);
    $mapcodeTo = getfile_contents('http://maps.google.com/maps/api/geocode/json?address='.$formattedaddressTo.'&sensor=false');
    $outcomeTo = json_decode($mapcodeTo);
   
    //Get the latitude and longitude from geo data
    $latFrom = $outcomeFrom->results[0]->geometry->location->lat;
    $longFrom = $outcomeFrom->results[0]->geometry->location->long;
    $latTo = $outcomeTo->results[0]->geometry->location->lat;
    $longTo = $outcomeTo->results[0]->geometry->location->long;
   
    //Calculate the distance from latitude and longitude
    $theta = $longitudeFrom - $longitudeTo;
    $dist = sin(deg2rad($latFrom)) * sin(deg2rad($latTo)) +  cos(deg2rad($latFrom)) * cos(deg2rad($latTo)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    $measurement = strtoupper($measurement);
    if ($measurement == "KM") {
        return ($miles * 1.609344).' km';
    } else if ($measurement == "NM") {
        return ($miles * 0.8684).' nm';
    } else {
        return $miles.' mi';
    }
}

  //If you want to use this Google API Key in your code it will helps you how?. If your daily request limit exceed then you would not get any result this Api Key will helps you .

$mapcode = getfile_contents('https://maps.google.com/maps/api/geocode/json?address='.$formattedaddr.'&sensor=false&key=GoogleAPIKey');


0 comments:

Post a Comment