Calculate Google distance of Input address and all the address from MySQL Server using jQuery ajax.get

元气小坏坏 提交于 2019-12-08 09:10:56

问题


Problem Description

I want to create a webpage where user can input an address, then the server will calculate the distance from the input address to every address I have in the MySQL database. I am trying to use ajax GET method to do it. And I have the following codes:

<?php
$query = "SELECT * FROM markers_v2 WHERE 1 LIMIT 3";
$result = mysql_query($query);
$lat = $_GET['lat'];
$lng = $_GET['lng'];

function caldist($lat1, $lng1, $lat2, $lng2) {
    $R = 6371;
    $dLat = deg2rad($lat2 - $lat1);
    $dLng = deg2rad($lng2 - $lng1);
    $dLat1 = deg2rad($lat1);
    $dLat2 = deg2rad($lat2);

$a = sin($dLat/2)*sin($dLat/2)+cos($dLat1)*cos($dLat1)*sin($dLng/2)*sin($dLng/2);
$c = 2 * atan2(sqrt($a),sqrt(1-$a));
return $R * $c;
}


if(!$result) {
    die('invalid query: '.mysql_error());
}   
$jsondata = '[';
while($row = @mysql_fetch_assoc($result)){
    $jsondata .= '{"lat":"' . $row['lat'] . '",';
    $jsondata .= '"lng":"' . $row['lng'] . '",';
    $jsondata .= '"distance":"' . caldist($lat,$lng,$row['lat'],$row['lng']) .'"';
    $jsondata .= '},';
}
$jsondata .= ']';
?>

The block of codes above works fine when I am manually inputting the GET Variables through the URL bar. e.g.:

http://www.example.com/find_distance.php?lat=123456&lng=234567

However, I want a way so that the input address will be automatically turned into lat and lng through Geocode. I am using the codes below for geocode:

  function searchAddress(addr) {
        geocoder = new google.maps.Geocoder();

        geocoder.geocode({address:addr}, function(result){
            loc = result[0].geometry.location;
        });
        return loc;

    }

I am trying to use the ajax get method below: but it doesn't seem to work as I wanted:

        var data = 'lat='+loc.lat()+'&lng='+loc.lng();

        $.ajax({
            url:'find_distance.php',
            type:'GET',
            data: data,
            cache:false,
            complete:function(){alert('Complete');},
            success:function(){alert('success, '+data);}
        });
    }

It doesn't seem to work. Do I have to somehow tell the PHP code to run again in the PHP code section?


回答1:


Try object notation Like this

 var data = {'lat':loc.lat(),'lng':loc.lng()};

    $.ajax({
        url:'find_distance.php',
        type:'GET',
        data: data,
        cache:false,
        complete:function(){alert('Complete');},
        success:function(){alert('success, '+data);}
    });
}


来源:https://stackoverflow.com/questions/8914506/calculate-google-distance-of-input-address-and-all-the-address-from-mysql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!