我想创建一个网页,在这里用户可以输入一个地址,那么服务器将计算从输入地址的距离,每个地址我已经在MySQL数据库。我想用ajax GET方法来做到这一点。我有以下的codeS:
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 .= ']';
?>
的codeS块以上工作正常,当我通过手动地址栏输入GET变量。例如:
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
不过,我想办法使输入地址会自动通过地理code变成纬度和经度。我使用C $ CS的$下面的地缘code:
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;
}
我试图使用AJAX get方法如下:但它似乎并没有工作,因为我想:
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);}
});
}
这似乎并没有工作。我必须以某种方式告诉PHP code在PHP code节再次运行?
It doesn't seem to work. Do I have to somehow tell the PHP code to run again in the PHP code section?
尝试对象符号像这样
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);}
});
}