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

后端 未结 17 1607
走了就别回头了
走了就别回头了 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:08

    If you want to use geonames.org then use this code. (But geonames.org is very slow sometimes)

    String get_time_zone_time_geonames(GeoPoint gp){
    
    
            String erg = "";
    
            double Longitude = gp.getLongitudeE6()/1E6;
            double Latitude = gp.getLatitudeE6()/1E6;
    
    
    
            String request = "http://ws.geonames.org/timezone?lat="+Latitude+"&lng="+ Longitude+ "&style=full";
    
            URL time_zone_time = null;
    
            InputStream input;
           // final StringBuilder sBuf = new StringBuilder();
    
    
            try {
                time_zone_time = new URL(request);
    
    
            try {
                input = time_zone_time.openConnection().getInputStream();
    
    
            final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                final StringBuilder sBuf = new StringBuilder();
    
                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        sBuf.append(line);
                    }
                } catch (IOException e) {
                        Log.e(e.getMessage(), "XML parser, stream2string 1");
                } finally {
                    try {
                        input.close();
                    } catch (IOException e) {
                        Log.e(e.getMessage(), "XML parser, stream2string 2");
                    }
                }
    
    
    
    
                 String xmltext = sBuf.toString();
    
    
                 int startpos = xmltext.indexOf("<geonames");
                 xmltext = xmltext.substring(startpos);
    
    
    
                XmlPullParser parser;
                try {
                    parser = XmlPullParserFactory.newInstance().newPullParser();
    
    
                parser.setInput(new StringReader (xmltext));
    
                int eventType = parser.getEventType();  
    
                String tagName = "";
    
                while(eventType != XmlPullParser.END_DOCUMENT) {
                    switch(eventType) {
    
                        case XmlPullParser.START_TAG:
    
                              tagName = parser.getName();
    
                            break;
    
    
                        case XmlPullParser.TEXT :
    
    
                            if  (tagName.equalsIgnoreCase("time"))
                              erg = parser.getText();  
    
    
                        break;   
    
                    }
    
                    try {
                        eventType = parser.next();
                    } catch (IOException e) {
    
                        e.printStackTrace();
                    }
    
                }
    
                } catch (XmlPullParserException e) {
    
                    e.printStackTrace();
                    erg += e.toString();
                }
    
    
    
                } catch (IOException e1) {
    
                    e1.printStackTrace();
                }
    
    
                } catch (MalformedURLException e1) {
    
                    e1.printStackTrace();
                }
    
    
    
    
    
            return erg;
    
     }
    

    And use it with:

    GeoPoint gp = new GeoPoint(39.6034810,-119.6822510);
    String Current_TimeZone_Time = get_time_zone_time_geonames(gp);
    
    0 讨论(0)
  • 2020-11-21 05:11

    We at Teleport just started opening up our API's and one of the usecases is also exposing TZ information for coordinates.

    For example one could request all our available TZ information for coordinates in following manner:

    curl -s https://api.teleport.org/api/locations/59.4372,24.7453/?embed=location:nearest-cities/location:nearest-city/city:timezone/tz:offsets-now | jq '._embedded."location:nearest-cities"[0]._embedded."location:nearest-city"._embedded."city:timezone"'
    

    This would return the following

    {
      "_embedded": {
        "tz:offsets-now": {
          "_links": {
            "self": {
              "href": "https://api.teleport.org/api/timezones/iana:Europe%2FTallinn/offsets/?date=2015-09-07T11%3A20%3A09Z"
            }
          },
          "base_offset_min": 120,
          "dst_offset_min": 60,
          "end_time": "2015-10-25T01:00:00Z",
          "short_name": "EEST",
          "total_offset_min": 180,
          "transition_time": "2015-03-29T01:00:00Z"
        }
      },
      "_links": {
        "self": {
          "href": "https://api.teleport.org/api/timezones/iana:Europe%2FTallinn/"
        },
        "tz:offsets": {
          "href": "https://api.teleport.org/api/timezones/iana:Europe%2FTallinn/offsets/{?date}",
          "templated": true
        },
        "tz:offsets-now": {
          "href": "https://api.teleport.org/api/timezones/iana:Europe%2FTallinn/offsets/?date=2015-09-07T11%3A20%3A09Z"
        }
      },
      "iana_name": "Europe/Tallinn"
    }
    

    For the example I used ./jq for JSON parsing.

    0 讨论(0)
  • 2020-11-21 05:11

    by using latitude and longitude get time zone of current location below code worked for me

    String data = null;         
    LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Location ll = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    double lat = 0,lng = 0;
    if(ll!=null){
        lat=ll.getLatitude();
        lng=ll.getLongitude();
    }
    System.out.println(" Last known location of device  == "+lat+"    "+lng);
    
    InputStream iStream = null; 
    HttpURLConnection urlConnection = null;
    try{
        timezoneurl = timezoneurl+"location=22.7260783,75.8781553&timestamp=1331161200";                    
        // timezoneurl = timezoneurl+"location="+lat+","+lng+"&timestamp=1331161200";
    
        URL url = new URL(timezoneurl);                
        // Creating an http connection to communicate with url 
        urlConnection = (HttpURLConnection) url.openConnection(); 
    
        // Connecting to url 
        urlConnection.connect();                
    
        // Reading data from url 
        iStream = urlConnection.getInputStream();
    
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
    
        StringBuffer sb  = new StringBuffer();
        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }
        data = sb.toString();
        br.close();
    
    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        try {
            iStream.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        urlConnection.disconnect();
    }
    
    try {
        if(data!=null){
            JSONObject jobj=new JSONObject(data);
            timezoneId = jobj.getString("timeZoneId");
    
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            format.setTimeZone(TimeZone.getTimeZone(timezoneId));
    
            Calendar cl = Calendar.getInstance(TimeZone.getTimeZone(timezoneId));
            System.out.println("time zone id in android ==  "+timezoneId);
    
            System.out.println("time zone of  device in android == "+TimeZone.getTimeZone(timezoneId));
            System.out.println("time fo device in android "+cl.getTime());
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    0 讨论(0)
  • 2020-11-21 05:16

    Here's how you can use Google's script editor to get the timezoneName and timeZoneId inside a gsheet.

    Step 1. Get an API key for Google's timezone API

    Step 2. Create a new gsheet. Underneath the 'tools' menu click 'script editor'. Add the following code:

    function getTimezone(lat, long) {  
      var apiKey = 'INSERTAPIKEYHERE'
      var url = 'https://maps.googleapis.com/maps/api/timezone/json?location=' + lat + ',' + long + '&timestamp=1331161200&key=' + apiKey 
      var response = UrlFetchApp.fetch(url);
      var data = JSON.parse(response.getContentText());
      return data["timeZoneName"];
    }
    

    Step 3. Save and publish your getTimezone() function and use it as shown in the image above.

    0 讨论(0)
  • 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());
        }
    }
    
    0 讨论(0)
提交回复
热议问题