2013年8月14日水曜日

ジオコーダー&逆ジオコーダー Google API for Java

緯度・経度と住所の相互変換コード。
GoogleのAPIが便利。後は、LatLngに関係する情報をユーザに返すコードが出来れば、GPSとの連携ができる。


public class GeocoderApp {
public static String invGeocode(double lat, double lng){
final Geocoder geocoder = new Geocoder();
BigDecimal latB = new BigDecimal(lat);
BigDecimal lngB = new BigDecimal(lng);
LatLng location = new LatLng(latB, lngB);
GeocoderRequest geocoderRequest = new GeocoderRequestBuilder().setLocation(location).setLanguage("ja").getGeocoderRequest();
GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest);
GeocoderStatus status = geocoderResponse.getStatus();
switch (status) {
case ZERO_RESULTS:
return null;
case OVER_QUERY_LIMIT:
case REQUEST_DENIED:
case INVALID_REQUEST:
case UNKNOWN_ERROR:
case ERROR:
throw new RuntimeException(status.value());
default:
}
List<GeocoderResult> results = geocoderResponse.getResults();
for (GeocoderResult result : results) {
return result.getFormattedAddress();
}
return null;
}
public static LatLng geocode(String address) {
final Geocoder geocoder = new Geocoder();
GeocoderRequest geocoderRequest = new GeocoderRequestBuilder()
.setAddress(address).setLanguage("ja")
.getGeocoderRequest();
GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest);
GeocoderStatus status = geocoderResponse.getStatus();
switch (status) {
case ZERO_RESULTS:
return null;
case OVER_QUERY_LIMIT:
case REQUEST_DENIED:
case INVALID_REQUEST:
case UNKNOWN_ERROR:
case ERROR:
throw new RuntimeException(status.value());
default:
}
List<GeocoderResult> results = geocoderResponse.getResults();
for (GeocoderResult result : results) {
GeocoderGeometry geometry = result.getGeometry();
return geometry.getLocation();
}
return null;
}
}

0 件のコメント:

コメントを投稿