MySQL Great Circle Distance (Haversine formula)

前端 未结 9 1657
栀梦
栀梦 2020-11-21 06:53

I\'ve got a working PHP script that gets Longitude and Latitude values and then inputs them into a MySQL query. I\'d like to make it solely MySQL. Here\'s my current PHP Cod

9条回答
  •  天命终不由人
    2020-11-21 07:09

    I have written a procedure that can calculate the same, but you have to enter the latitude and longitude in the respective table.

    drop procedure if exists select_lattitude_longitude;
    
    delimiter //
    
    create procedure select_lattitude_longitude(In CityName1 varchar(20) , In CityName2 varchar(20))
    
    begin
    
        declare origin_lat float(10,2);
        declare origin_long float(10,2);
    
        declare dest_lat float(10,2);
        declare dest_long float(10,2);
    
        if CityName1  Not In (select Name from City_lat_lon) OR CityName2  Not In (select Name from City_lat_lon) then 
    
            select 'The Name Not Exist or Not Valid Please Check the Names given by you' as Message;
    
        else
    
            select lattitude into  origin_lat from City_lat_lon where Name=CityName1;
    
            select longitude into  origin_long  from City_lat_lon where Name=CityName1;
    
            select lattitude into  dest_lat from City_lat_lon where Name=CityName2;
    
            select longitude into  dest_long  from City_lat_lon where Name=CityName2;
    
            select origin_lat as CityName1_lattitude,
                   origin_long as CityName1_longitude,
                   dest_lat as CityName2_lattitude,
                   dest_long as CityName2_longitude;
    
            SELECT 3956 * 2 * ASIN(SQRT( POWER(SIN((origin_lat - dest_lat) * pi()/180 / 2), 2) + COS(origin_lat * pi()/180) * COS(dest_lat * pi()/180) * POWER(SIN((origin_long-dest_long) * pi()/180 / 2), 2) )) * 1.609344 as Distance_In_Kms ;
    
        end if;
    
    end ;
    
    //
    
    delimiter ;
    

提交回复
热议问题