如何用Java開發地理位置應用程序?
開發帶有地理位置的應用(Geocoding)是這樣的過程,利用其它地理位置信息找到相應的坐標。
Java API for Google geocoder v3可以很好地支持地理位置應用開發。使用這個API可以做一些很酷的事情。例如,下面是來自http://gliesians.com一張圖片,是路透社世界新聞RSS的地理位置應用,它會自動在谷歌地圖(GMAP)上做出新聞標識。
通過三個簡單的步驟使用Google Geocoder-Java API開發Geocoding應用:
- 步驟一:添加GeoCoder API到Maven的dependency標簽中。
- 步驟二:通過使用API寫一個方法來開發GeoCoding應用。
- 步驟三:將一個位置傳遞給這個方法,然后查看位置信息。
在Maven中添加GeoCoder API依賴
將以下代碼添加到你Maven項目的pom.xml文件:
<dependency> <groupId>com.google.code.geocoder-java</groupId> <artifactId>geocoder-java</artifactId> <version>0.16</version> </dependency>
使用Google Geocoder v3 API開發地理位置應用程序
下面的示例代碼是我遵循MIT許可對Joe Pasqua代碼進行的修改。這段代碼將會接收的一個地理位置(比如意大利),然后以數組形式返回經緯度。
public static Float[] performGeoCoding(String location) {
if (location == null)
return null;
Geocoder geocoder = new Geocoder();
GeocoderRequest geocoderRequest
= new GeocoderRequestBuilder()
.setAddress(location) // location
.setLanguage("en") // language
.getGeocoderRequest();
GeocodeResponse geocoderResponse;
try {
geocoderResponse = geocoder.geocode(geocoderRequest);
if (geocoderResponse.getStatus() == GeocoderStatus.OK
& !geocoderResponse.getResults().isEmpty()) {
GeocoderResult geocoderResult =
geocoderResponse.getResults().iterator().next();
LatLng latitudeLongitude =
geocoderResult.getGeometry().getLocation();
Float[] coords = new Float[2];
coords[0] = latitudeLongitude.getLat().floatValue();
coords[1] = latitudeLongitude.getLng().floatValue();
return coords;
}
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
給方法傳入地點,然后獲得你的地理位置信息
下面的代碼運行這個方法,啟用地理位置應用然后打印結果:
public static void main(String[] args) {
String location = "Troia, Foggia, Italy";
Float[] coords = performGeoCoding(location);
System.out.println(location + ": "
+ coords[0] + ", " + coords[1]);
} $ Troia, Foggia, Italy: 41.35978, 15.308114
注意:導入
這里是對于不用IDE的程序員來說需要的相關導入:
import com.google.code.geocoder.Geocoder; import com.google.code.geocoder.GeocoderRequestBuilder; import com.google.code.geocoder.model.GeocodeResponse; import com.google.code.geocoder.model.GeocoderRequest; import com.google.code.geocoder.model.GeocoderResult; import com.google.code.geocoder.model.GeocoderStatus; import com.google.code.geocoder.model.LatLng; import java.io.IOException;
例如,在NetBeans中使用“Ctrl+Alt+I”完成自動導入。
一如既往,我希望很多人已經發現這篇博文有趣并且有用
——Robert
原文鏈接: robertjliguori 翻譯: ImportNew.com - Calarence
譯文鏈接: http://www.importnew.com/14132.html
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!

