com.couchbase.trombi.services.GeoService.java Source code

Java tutorial

Introduction

Here is the source code for com.couchbase.trombi.services.GeoService.java

Source

/*
 * Copyright (c) 2016 Couchbase, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.couchbase.trombi.services;

import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

import com.couchbase.trombi.domain.CityInfo;
import com.google.maps.GeoApiContext;
import com.google.maps.GeocodingApi;
import com.google.maps.TimeZoneApi;
import com.google.maps.model.AddressComponent;
import com.google.maps.model.AddressComponentType;
import com.google.maps.model.ComponentFilter;
import com.google.maps.model.GeocodingResult;
import com.google.maps.model.LatLng;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Service;

@Service
public class GeoService {

    @Value("${geo.api.key}")
    private String geoApiKey;

    @Cacheable("cities")
    public CityInfo findCity(String cityName, String countryName) {
        GeoApiContext context = new GeoApiContext().setApiKey(geoApiKey);
        GeocodingResult[] results = GeocodingApi.newRequest(context)
                .components(ComponentFilter.locality(cityName), ComponentFilter.country(countryName))
                .awaitIgnoreError();

        LatLng location = results[0].geometry.location;
        String stdCity = cityName;
        String stdCountry = countryName;
        for (AddressComponent ac : results[0].addressComponents) {
            for (AddressComponentType acType : ac.types) {
                if (acType == AddressComponentType.COUNTRY) {
                    stdCountry = ac.longName;
                } else if (acType == AddressComponentType.LOCALITY) {
                    stdCity = ac.longName;
                }
            }
        }

        TimeZone tz = TimeZoneApi.getTimeZone(context, location).awaitIgnoreError();

        return new CityInfo(stdCity, stdCountry, new Point(location.lat, location.lng),
                (int) TimeUnit.MILLISECONDS.toHours(tz.getRawOffset()));
    }

}