Calculate the center point of multiple latitude/longitude coordinate pairs

后端 未结 21 1582
暖寄归人
暖寄归人 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:50

    As an appreciation for this thread, here is my little contribution with the implementation in Ruby, hoping that I will save someone a few minutes from their precious time:

    def self.find_center(locations)
    
     number_of_locations = locations.length
    
     return locations.first if number_of_locations == 1
    
     x = y = z = 0.0
     locations.each do |station|
       latitude = station.latitude * Math::PI / 180
       longitude = station.longitude * Math::PI / 180
    
       x += Math.cos(latitude) * Math.cos(longitude)
       y += Math.cos(latitude) * Math.sin(longitude)
       z += Math.sin(latitude)
     end
    
     x = x/number_of_locations
     y = y/number_of_locations
     z = z/number_of_locations
    
     central_longitude =  Math.atan2(y, x)
     central_square_root = Math.sqrt(x * x + y * y)
     central_latitude = Math.atan2(z, central_square_root)
    
     [latitude: central_latitude * 180 / Math::PI, 
     longitude: central_longitude * 180 / Math::PI]
    end
    

提交回复
热议问题