如何用Java开发地理位置应用程序?
作者:网络转载 发布时间:[ 2014/12/25 13:45:02 ] 推荐标签:Java 地理位置应用程序
下面的示例代码是我遵循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

sales@spasvo.com