Calculate the center point of multiple latitude/longitude coordinate pairs

后端 未结 21 1589
暖寄归人
暖寄归人 2020-11-27 09:27

Given a set of latitude and longitude points, how can I calculate the latitude and longitude of the center point of that set (aka a point that would center a view on all poi

21条回答
  •  孤街浪徒
    2020-11-27 09:37

    I used a formula that I got from www.geomidpoint.com and wrote the following C++ implementation. The array and geocoords are my own classes whose functionality should be self-explanatory.

    /*
     * midpoints calculated using formula from www.geomidpoint.com
     */
       geocoords geocoords::calcmidpoint( array& points )
       {
          if( points.empty() ) return geocoords();
    
          float cart_x = 0,
                cart_y = 0,
                cart_z = 0;
    
          for( auto& point : points )
          {
             cart_x += cos( point.lat.rad() ) * cos( point.lon.rad() );
             cart_y += cos( point.lat.rad() ) * sin( point.lon.rad() );
             cart_z += sin( point.lat.rad() );
          }
    
          cart_x /= points.numelems();
          cart_y /= points.numelems();
          cart_z /= points.numelems();
    
          geocoords mean;
    
          mean.lat.rad( atan2( cart_z, sqrt( pow( cart_x, 2 ) + pow( cart_y, 2 ))));
          mean.lon.rad( atan2( cart_y, cart_x ));
    
          return mean;
       }
    

提交回复
热议问题