How to get a time zone from a location using latitude and longitude coordinates?

后端 未结 17 1974
走了就别回头了
走了就别回头了 2020-11-21 04:38

Given the latitude and longitude of a location, how does one know what time zone is in effect in that location?

In most cases, we are looking for an IANA/Olson time z

17条回答
  •  没有蜡笔的小新
    2020-11-21 05:16

    https://en.wikipedia.org/wiki/Great-circle_distance

    And here is a good implementation using JSON data: https://github.com/agap/llttz

    public TimeZone nearestTimeZone(Location node) {
        double bestDistance = Double.MAX_VALUE;
        Location bestGuess = timeZones.get(0);
    
        for (Location current : timeZones.subList(1, timeZones.size())) {
            double newDistance = distanceInKilometers(node, current);
    
            if (newDistance < bestDistance) {
                bestDistance = newDistance;
                bestGuess = current;
            }
        }
    
        return java.util.TimeZone.getTimeZone(bestGuess.getZone());
    }
    
      protected double distanceInKilometers(final double latFrom, final double lonFrom, final double latTo, final double lonTo) {
            final double meridianLength = 111.1;
            return meridianLength * centralAngle(latFrom, lonFrom, latTo, lonTo);
        }
    
        protected double centralAngle(final Location from, final Location to) {
            return centralAngle(from.getLatitude(), from.getLongitude(), to.getLatitude(), to.getLongitude());
        }
    
        protected double centralAngle(final double latFrom, final double lonFrom, final double latTo, final double lonTo) {
            final double latFromRad = toRadians(latFrom),
                    lonFromRad = toRadians(lonFrom),
                    latToRad   = toRadians(latTo),
                    lonToRad   = toRadians(lonTo);
    
            final double centralAngle = toDegrees(acos(sin(latFromRad) * sin(latToRad) + cos(latFromRad) * cos(latToRad) * cos(lonToRad - lonFromRad)));
    
            return centralAngle <= 180.0 ? centralAngle : (360.0 - centralAngle);
        }
    
        protected double distanceInKilometers(final Location from, final Location to) {
            return distanceInKilometers(from.getLatitude(), from.getLongitude(), to.getLatitude(), to.getLongitude());
        }
    }
    

提交回复
热议问题