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

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

    Ok here is the short Version without correct NTP Time:

    String get_xml_server_reponse(String server_url){
    
    URL xml_server = null;
    
    String xmltext = "";
    
    InputStream input;
    
    
    try {
        xml_server = new URL(server_url);
    
    
        try {
            input = xml_server.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");
                }
            }
    
            xmltext =  sBuf.toString();
    
        } catch (IOException e1) {
    
                e1.printStackTrace();
            }
    
    
        } catch (MalformedURLException e1) {
    
          e1.printStackTrace();
        }
    
     return  xmltext;
    
    } 
    
    
    long get_time_zone_time_l(GeoPoint gp){
    
    
            String raw_offset = "";
            String dst_offset = "";
    
            double Longitude = gp.getLongitudeE6()/1E6;
            double Latitude = gp.getLatitudeE6()/1E6;
    
            long tsLong = System.currentTimeMillis()/1000;
    
    
            if (tsLong != 0)
            {
    
            // https://maps.googleapis.com/maps/api/timezone/xml?location=39.6034810,-119.6822510&timestamp=1331161200&sensor=false
    
            String request = "https://maps.googleapis.com/maps/api/timezone/xml?location="+Latitude+","+ Longitude+ "&timestamp="+tsLong +"&sensor=false";
    
            String xmltext = get_xml_server_reponse(request);
    
            if(xmltext.compareTo("")!= 0)
            {
    
             int startpos = xmltext.indexOf("<TimeZoneResponse");
             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("raw_offset"))
                              if(raw_offset.compareTo("")== 0)                               
                                raw_offset = parser.getText();  
    
                            if  (tagName.equalsIgnoreCase("dst_offset"))
                              if(dst_offset.compareTo("")== 0)
                                dst_offset = parser.getText();  
    
    
                            break;   
    
                     }
    
                     try {
                            eventType = parser.next();
                        } catch (IOException e) {
    
                            e.printStackTrace();
                        }
    
                    }
    
                    } catch (XmlPullParserException e) {
    
                        e.printStackTrace();
                        erg += e.toString();
                    }
    
            }      
    
            int ro = 0;
            if(raw_offset.compareTo("")!= 0)
            { 
                float rof = str_to_float(raw_offset);
                ro = (int)rof;
            }
    
            int dof = 0;
            if(dst_offset.compareTo("")!= 0)
            { 
                float doff = str_to_float(dst_offset);
                dof = (int)doff;
            }
    
            tsLong = (tsLong + ro + dof) * 1000;
    
    
            }
    
    
      return tsLong;
    
    }
    

    And use it with:

    GeoPoint gp = new GeoPoint(39.6034810,-119.6822510);
    long Current_TimeZone_Time_l = get_time_zone_time_l(gp);
    
    0 讨论(0)
  • 2020-11-21 05:00

      function jsonpRequest(url, data)
    {
        let params = "";
        for (let key in data)
        {
            if (data.hasOwnProperty(key))
            {
                if (params.length == 0)
                {
                    params += "?";
                }
                else
                {
                    params += "&";
                }
                let encodedKey = encodeURIComponent(key);
                let encodedValue = encodeURIComponent(data[key]);
                params += encodedKey + "=" + encodedValue;
             }
        }
        let script = document.createElement('script');
        script.src = url + params;
        document.body.appendChild(script);
    }
    
    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    }
    let lat_ini=[]; let lon_ini=[];
    function showPosition(position) {
      lat_ini= position.coords.latitude;
      lon_ini= position.coords.longitude;
    }
    ////delay time between lines
    function sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
    ///////
    function getGMT()
    {
      getfinalGMT()
      getLocation()
      async function sample() {
        await sleep(2000);
    let lat_str=lat_ini.toString();
    let lng_str=" "+lon_ini.toString();
    
      let url = "https://api.opencagedata.com/geocode/v1/json";
      let data = {
        callback: "displayGMT",
        q: lat_str + lng_str,
        key: "fac4471073a347019196c1291e6a97d7"
      }
      jsonpRequest(url, data)
    }
     sample();
     }
    let your_GMT=[];
    function displayGMT(data)
    {
    your_GMT=(Number(data.results[0].annotations.timezone.offset_string))
    console.log(your_GMT)
    }
    /////
    function getfinalGMT()
    {
    let lat=document.getElementById("lat_id").value; let lng=document.getElementById("lng_id").value;
    let lat_str=lat.toString();
    let lng_str=" "+lng.toString();
    
      let url = "https://api.opencagedata.com/geocode/v1/json";
      let data = {
        callback: "displayfinalGMT",
        q: lat + lng_str,
        key: "fac4471073a347019196c1291e6a97d7"
      }
      jsonpRequest(url, data)
     }
    let final_GMT=[];
    function displayfinalGMT(data)
    {
    final_GMT=(Number(data.results[0].annotations.timezone.offset_string))
    console.log(final_GMT)
    }
    /////clock
    
    
    const hourHand = document.querySelector('[data-hour-hand]')
    const minuteHand = document.querySelector('[data-minute-hand]')
    const secondHand = document.querySelector('[data-second-hand]')
      let dif_overall=[];
    function setClock() {
       let gmt_diff=Number(your_GMT-final_GMT)/100
       if (gmt_diff>12){
          dif_overall=gmt_diff-12
       }
       else{
         dif_overall=gmt_diff
       }
        console.log(dif_overall)
      const currentDate = new Date()
      const secondsRatio = currentDate.getSeconds() / 60
      const minutesRatio = (secondsRatio + currentDate.getMinutes()) / 60
      const hoursRatio = (minutesRatio + currentDate.getHours() - dif_overall ) / 12
      setRotation(secondHand, secondsRatio)
      setRotation(minuteHand, minutesRatio)
      setRotation(hourHand, hoursRatio)
    }
    
    function setRotation(element, rotationRatio) {
      element.style.setProperty('--rotation', rotationRatio * 360)
    }
    function activate_clock(){
    setClock()
    setInterval(setClock, 1000)
    }
    *, *::after, *::before {
      box-sizing: border-box;
    }
    
    body {
      background: linear-gradient(to right, hsl(200, 100%, 50%), hsl(175, 100%, 50%));
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      overflow: hidden;
    }
    
    .clock {
      width: 200px;
      height: 200px;
      background-color: rgba(255, 255, 255, .8);
      border-radius: 50%;
      border: 2px solid black;
      position: relative;
    }
    
    .clock .number {
      --rotation: 0;
      position: absolute;
      width: 100%;
      height: 100%;
      text-align: center;
      transform: rotate(var(--rotation));
      font-size: 1.5rem;
    }
    
    .clock .number1 { --rotation: 30deg; }
    .clock .number2 { --rotation: 60deg; }
    .clock .number3 { --rotation: 90deg; }
    .clock .number4 { --rotation: 120deg; }
    .clock .number5 { --rotation: 150deg; }
    .clock .number6 { --rotation: 180deg; }
    .clock .number7 { --rotation: 210deg; }
    .clock .number8 { --rotation: 240deg; }
    .clock .number9 { --rotation: 270deg; }
    .clock .number10 { --rotation: 300deg; }
    .clock .number11 { --rotation: 330deg; }
    
    .clock .hand {
      --rotation: 0;
      position: absolute;
      bottom: 50%;
      left: 50%;
      border: 1px solid white;
      border-top-left-radius: 10px;
      border-top-right-radius: 10px;
      transform-origin: bottom;
      z-index: 10;
      transform: translateX(-50%) rotate(calc(var(--rotation) * 1deg));
    }
    
    .clock::after {
      content: '';
      position: absolute;
      background-color: black;
      z-index: 11;
      width: 15px;
      height: 15px;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      border-radius: 50%;
    }
    
    .clock .hand.second {
      width: 3px;
      height: 45%;
      background-color: red;
    }
    
    .clock .hand.minute {
      width: 7px;
      height: 40%;
      background-color: black;
    }
    
    .clock .hand.hour {
      width: 10px;
      height: 35%;
      background-color: black;
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    /* Background Styles Only */
    
    @import url('https://fonts.googleapis.com/css?family=Raleway');
    
    * {
        font-family: Raleway;
    }
    
    .side-links {
      position: absolute;
      top: 15px;
      right: 15px;
    }
    
    .side-link {
      display: flex;
      align-items: center;
      justify-content: center;
      text-decoration: none;
      margin-bottom: 10px;
      color: white;
      width: 180px;
      padding: 10px 0;
      border-radius: 10px;
    }
    
    .side-link-youtube {
      background-color: red;
    }
    
    .side-link-twitter {
      background-color: #1DA1F2;
    }
    
    .side-link-github {
      background-color: #6e5494;
    }
    
    .side-link-text {
      margin-left: 10px;
      font-size: 18px;
    }
    
    .side-link-icon {
      color: white;
      font-size: 30px;
    }
       <input type="text" id="lat_id" placeholder="lat"><br><br>
      <input type="text" id="lng_id" placeholder="lng"><br><br>
    <button class="text" onClick="getLocation()">Location</button>
    <button class="text" onClick="getGMT()"> GMT</button>
    <button class="text" onClick="activate_clock()"> Activate</button>
    <div class="clock">
      <div class="hand hour" data-hour-hand></div>
      <div class="hand minute" data-minute-hand></div>
      <div class="hand second" data-second-hand></div>
      <div class="number number1">1</div>
      <div class="number number2">2</div>
      <div class="number number3">3</div>
      <div class="number number4">4</div>
      <div class="number number5">5</div>
      <div class="number number6">6</div>
      <div class="number number7">7</div>
      <div class="number number8">8</div>
      <div class="number number9">9</div>
      <div class="number number10">10</div>
      <div class="number number11">11</div>
      <div class="number number12">12</div>
    </div>

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

    How about this solution for node.js https://github.com/mattbornski/tzwhere

    And its Python counterpart: https://github.com/pegler/pytzwhere

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

    You can use geolocator.js for easily getting timezone and more...

    It uses Google APIs that require a key. So, first you configure geolocator:

    geolocator.config({
        language: "en",
        google: {
            version: "3",
            key: "YOUR-GOOGLE-API-KEY"
        }
    });
    

    Get TimeZone if you have the coordinates:

    geolocator.getTimeZone(options, function (err, timezone) {
        console.log(err || timezone);
    });
    

    Example output:

    {
        id: "Europe/Paris",
        name: "Central European Standard Time",
        abbr: "CEST",
        dstOffset: 0,
        rawOffset: 3600,
        timestamp: 1455733120
    }
    

    Locate then get TimeZone and more

    If you don't have the coordinates, you can locate the user position first.

    Example below will first try HTML5 Geolocation API to get the coordinates. If it fails or rejected, it will get the coordinates via Geo-IP look-up. Finally, it will get the timezone and more...

    var options = {
        enableHighAccuracy: true,
        timeout: 6000,
        maximumAge: 0,
        desiredAccuracy: 30,
        fallbackToIP: true, // if HTML5 fails or rejected
        addressLookup: true, // this will get full address information
        timezone: true,
        map: "my-map" // this will even create a map for you
    };
    geolocator.locate(options, function (err, location) {
        console.log(err || location);
    });
    

    Example output:

    {
        coords: {
            latitude: 37.4224764,
            longitude: -122.0842499,
            accuracy: 30,
            altitude: null,
            altitudeAccuracy: null,
            heading: null,
            speed: null
        },
        address: {
            commonName: "",
            street: "Amphitheatre Pkwy",
            route: "Amphitheatre Pkwy",
            streetNumber: "1600",
            neighborhood: "",
            town: "",
            city: "Mountain View",
            region: "Santa Clara County",
            state: "California",
            stateCode: "CA",
            postalCode: "94043",
            country: "United States",
            countryCode: "US"
        },
        formattedAddress: "1600 Amphitheatre Parkway, Mountain View, CA 94043, USA",
        type: "ROOFTOP",
        placeId: "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
        timezone: {
            id: "America/Los_Angeles",
            name: "Pacific Standard Time",
            abbr: "PST",
            dstOffset: 0,
            rawOffset: -28800
        },
        flag: "//cdnjs.cloudflare.com/ajax/libs/flag-icon-css/2.3.1/flags/4x3/us.svg",
        map: {
            element: HTMLElement,
            instance: Object, // google.maps.Map
            marker: Object, // google.maps.Marker
            infoWindow: Object, // google.maps.InfoWindow
            options: Object // map options
        },
        timestamp: 1456795956380
    }
    
    0 讨论(0)
  • 2020-11-21 05:06

    disclosure: I am the author of the docker-image described below

    I have wrapped https://github.com/evansiroky/node-geo-tz in a very simple docker-container

    https://hub.docker.com/repository/docker/tobias74/timezone-lookup

    You can start the docker-container with

    docker run -p 80:3000 tobias74/timezone-lookup:latest
    

    This exposes the lookup-service on your localhost on port 3000. You can then do a timezone-lookup by

    curl "localhost:3000/timezone?latitude=12&longitude=34"
    
    0 讨论(0)
  • 2020-11-21 05:06
    1. There are several sources online that have geojson data for timezones (here's one, here's another)

    2. Use a geometry library to create polygon objects from the geojson coordinates (shapely [python], GEOS [c++], JTS [java], NTS [.net]).

    3. Convert your lat/lng to a point object (however your library represents that) and check if it intersects the timezone polygon.

      from shapely.geometry import Polygon, Point
      
      def get_tz_from_lat_lng(lat, lng):
          for tz, geojson in timezones.iteritems():
              coordinates = geojson['features'][0]['geometry']['coordinates']
              polygon = Polygon(coordinates)
              point = Point(lng, lat)
              if polygon.contains(point):
                  return tz
      
    0 讨论(0)
提交回复
热议问题