graph icon indicating copy to clipboard operation
graph copied to clipboard

Add example of using math() to calculate Haversine Great Circle distance

Open krlawrence opened this issue 5 years ago • 0 comments

Add to the discussion of Geo Spatial queries that are possible in Gremlin using the examples below that demonstrate calculating the Haversine Great Circle Distance between two airports.

g.withSideEffect("PI", 3.1415926535).
  withSideEffect("rdeg", 0.017453293).
  withSideEffect("gcmiles",3956).        
  V().has('code','AUS').as('src').
  V().has('code','LHR').as('dst').
  select('src','dst').
    by(project('lat','lon').
         by('lat').
         by('lon')).as('grp').
    project('ladiff','lgdiff','lat1','lon1','lat2','lon2').
       by(project('la1','la2').
            by(select('grp').select('src').select('lat')).
            by(select('grp').select('dst').select('lat')).
          math('(la2 - la1) * rdeg')).
       by(project('lg1','lg2').
            by(select('grp').select('src').select('lon')).
            by(select('grp').select('dst').select('lon')).
          math('(lg2 - lg1) * rdeg')).
       by(select('grp').select('src').select('lat')).
       by(select('grp').select('src').select('lon')).
       by(select('grp').select('dst').select('lat')).
       by(select('grp').select('dst').select('lon')).
    math('(sin(ladiff/2))^2 + cos(lat1*rdeg) * cos(lat2*rdeg) * (sin(lgdiff/2))^2').
    math('gcmiles * (2 * asin(sqrt(_)))')              

g.withSideEffect("PI", 3.1415926535).
  withSideEffect("rdeg", 0.017453293).
  withSideEffect("gcmiles",3956).
  V().
  has('code',within('AUS','DFW')).
  group().
    by('code').
    by(project('lat','lon').
      by('lat').
      by('lon')).
  as('grp').
  project('ladiff','lgdiff','lat1','lon1','lat2','lon2').
    by(project('la1','la2').
         by(select('AUS').select('lat')).
         by(select('DFW').select('lat')).
       math('(la2 - la1) * rdeg')).
    by(project('lg1','lg2').
         by(select('AUS').select('lon')).
         by(select('DFW').select('lon')).
       math('(lg2 - lg1) * rdeg')).
    by(select('grp').select('AUS').select('lat')).
    by(select('grp').select('AUS').select('lon')).
    by(select('grp').select('DFW').select('lat')).
    by(select('grp').select('DFW').select('lon')).
    math('(sin(ladiff/2))^2 + cos(lat1*rdeg) * cos(lat2*rdeg) * (sin(lgdiff/2))^2').
    math('gcmiles * (2 * asin(sqrt(_)))')       

krlawrence avatar Mar 09 '20 21:03 krlawrence