Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7925169
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 3, 20262026-06-03T18:10:05+00:00 2026-06-03T18:10:05+00:00

I have a question that I have spent too many hours trying to resolve.

  • 0

I have a question that I have spent too many hours trying to resolve.
I am using de Haversine formula to calculate the distance between two points, but the code that I’m using is giving me values that are too high for a distance like KM.

This is the code:

$pesquisa_raio = "%" . $_GET['raio'] . "%";
$latitude = floatval("%" . $_GET['lat'] . "%");
$longitude = floatval("%" . $_GET['log'] . "%");
$cidade="%" . $_GET['cidade'] . "%";

$sql= "SELECT * FROM oferta";//"add depois" //Inner Join concelhos On oferta.concelhos_id = concelhos.idconcelhos ";
$query = mysql_query($sql);
$array = mysql_fetch_array($query);
$row = mysql_num_rows($query);
//$sql_cidades = "SELECT * FROM oferta WHERE localizacao like '$pesquisa_loc'";


if (isset($latitude) && isset($longitude)) {
    if ($row > 0) {
        do {
        $endereco=$array['concelho_id'];
        $request="http://maps.google.com/maps/api/geocode/json?address='.$endereco.'sensor=false";
        $json_data=file_get_contents($request);
        
        $earth_radius = 6372.795477598;
        $lat_1 = floatval($latitude);
        $lon_1 = floatval($longitude);
        $lat_2 = 41.145570;//floatval($latitude2);
        $lon_2 = -8.627014;//floatval($longitude2);
        $delta_lat = $lat_2 - $lat_1 ;
        $delta_lon = $lon_2 - $lon_1 ;
        $alpha    = $delta_lat/2;
        $beta     = $delta_lon/2;
        $a        = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($lat_1)) * cos(deg2rad($lat_2)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
        $c        = asin(min(1, sqrt($a)));
        $distance = 2*$earth_radius * $c;
        $distance = round($distance, 4);
        echo $distance."\n";
          if($distance<=$pesquisa_raio){
            $response = $array['titulo'] . "|";
        }
    } while ($array = mysql_fetch_assoc($query));
        json_encode($response);

Is something wrong with the code, or is it that I can’t understand the result?


Solved

So I have this code that doesn’t work, but I fix the problem, this is the solution:

    $tipo_output = "json"; // pode ser utilizado o json também
               // a sua API KEY do Google Maps gerado com o link acima
                $google_api = "0R4r34bcHA6I0Ppts5oHcxhgoPmdOvt4Hz2cA2w";
               // o endereço que desejamos que o google procure
               // lembrando que o endereço tem que ser no padrão de uma requisição URL e caso possua acentuação, vamos executar um utf8_encode
               $cidade=$array['concelho'];
               echo $cidade;
               $endereco_desejado = urlencode(utf8_encode("$cidade, PT"));
               // Desired address
               $endereco_final = "http://maps.google.com/maps/api/geocode/json?address=". $endereco_desejado ."&sensor=true";
               // conteudo da página
                $string = file_get_contents($endereco_final); // get json content
$json_a = json_decode($string); //json decoder
            //busca da lat e log
            $longitude2 = $json_a->results[0]->geometry->location->lng;
            $latitude2 =$json_a->results[0]->geometry->location->lat;
            //calculo da distancia
            
            $earth_radius = 6371.0;
            $latitude1 = $latitude * pi() / 180.0;
            $longitude1 = $longitude * pi() / 180.0;
            $latitude2 = $latitude2 * pi() / 180.0;
            $longitude2 = $longitude2 * pi() / 180.0;
            
             $dLat = $latitude2 - $latitude1;
             $dLong = $longitude2 - $longitude1;
            
             $a = sin($dLat / 2) * sin($dLat / 2) + cos( $latitude1) * cos($latitude2) * sin($dLong / 2) * sin($dLong / 2);
             
             $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
            
             $resultado=intval($earth_radius * $c); // resultado em km.
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-03T18:10:08+00:00Added an answer on June 3, 2026 at 6:10 pm

    Your inputs are broken.

    $latitude = floatval("%" . $_GET['lat'] . "%");
    $longitude = floatval("%" . $_GET['log'] . "%");
    

    Think about what you’re doing. floatval('%123.4%') will always be a zero, no matter what you take from $_GET.

    Those look like leftovers from an SQL query, but there you need a different escaping method (e.g. PDO) to avoid SQL injection.


    Also, you’re loading remote data using a malformed query and apparently ignoring the result?

    $endereco=$array['concelho_id'];
    $request="http://maps.google.com/maps/api/geocode/json?address='.$endereco.'sensor=false";
    $json_data=file_get_contents($request);
    

    This will produce an URL similar to http://maps.google.com/maps/api/geocode/json?address='.some kind of address.'sensor=false , which is never going to give you useful answers because it’s

    1. including single quotes and periods (you seem to have mixed up double and single quotes),
    2. not properly escaping the dynamic part at all,
    3. missing an & before sensor=false.

    (Not to mention $array won’t even be initialized the first time you run the do {} while loop.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a question concerning using the toggle function. I have a template that
First of all I'm sorry for the question's title, but I've spent hours trying
I have a question that should be quick and easy for you guys to
I have a question that may be quite naive, but I feel the need
I have a question that I just don't feel like I've found a satisfactory
I have a question that I'm ashamed to ask, but I'm going to have
I have a question that may sound odd, but being somewhat of a newbie,
I have a question that can I use AS400ConnectionPool in Spring if then pls
I have a question that's somewhat of an extension of this thread . I
I have a quick question that I can't seem to find online. I am

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.