MySQL PHP无法按开发人员谷歌示例的顺序排序

I was following this tutorial : https://developers.google.com/maps/articles/phpsqlsearch_v3 and wanted to increment another query:

I'd like to get the 20 nearest points of some type ( example - the top 20 nearest points that are type 2).

So, at this point I Have both this 2 working codes:

This first one gives me the results of the nearest places that are type 2 but doesnt order by distance.

$con = $con = mysql_connect("localhost","username","password");

if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("database", $con);

$result = mysql_query("
  SELECT *
  FROM table

  WHERE (
    type= 'type 2'
  ) AND (
  (promotype*( 6371 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ))<30)
  LIMIT 0,20



  ")or die;

while($row = mysql_fetch_assoc($result))
  {
    $output[]=$row;
  }

print(json_encode($output));

mysql_close($con);

and this second code gives me the ordered by distance result but I cant add the type( very similar, just changes this part ):

SELECT *, 
( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * 
sin( radians( lat ) ) ) ) 
AS distance FROM marker HAVING distance < 30 ORDER BY distance ASC LIMIT 0, 5")

So,

The big question is: How can I ORDER BY distance the first code or add the type filter on the second?

Thanks in advance