安卓:如何根据当前位置(地理位置/地理编码)获取时间或时区



我有一个地理代码(纬度,经度(。我的要求是根据此地理代码获取时间或获取时区,无论 android 设备的时间当时是否更改。

对此要求有任何想法...

你可以通过纬度和经度使用谷歌API获取时区

https://maps.googleapis.com/maps/api/timezone/json?location=38.908133,-77.047119&timestamp=1458000000&key=YOUR_API_KEY

或者第二种方式是

Calendar calender = Calendar.getInstance();
TimeZone timeZone = calender.getTimeZone();
Log.d("Time zone","="+timeZone.getDisplayName());

谷歌为他们的地图服务提供了一个非常好的库,其中包括地理代码查找。

我为您编写了一个简单的代码片段,但请参考地图库以查看您需要哪些 API 密钥。

https://github.com/googlemaps/google-maps-services-java

import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.PlacesApi;
import com.google.maps.model.GeocodingResult;
import com.google.maps.model.PlaceDetails;
public class Maps {
private static String apiKey;
public Maps(String apikey) {
    this.apiKey = apikey;
}
public String getTimezone(String address) throws Exception {
// The API will save the most matching result of your defined address in an array
GeocodingResult[] results = GeocodingApi.geocode(context, address).await();
 // .geometry.location returns an LatLng object coressponding to your address; 
//getTimeZone returns the timezone and it will be saved as a TimeZone object 
    TimeZone timeZone = TimeZoneApi.getTimeZone(context,results[0].geometry.location).await();
// returns the displayname of the timezone
    return timeZone.getDisplayName();
    }
}
public class Run {
public static void main(String[] args) throws Exception {
    String apiKey = "YOURGOOGLEAPIKEY"
    Maps m = new Maps(apiKey);
    m.getTimezone("Amsterdam");
    }
}

最新更新