欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

如何用Java开发地理位置应用程序?,java地理位置

来源: javaer 分享于  点击 31482 次 点评:29

如何用Java开发地理位置应用程序?,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 翻译: Wld5.com - Calarence
译文链接: http://www.wld5.com/14132.html
[ 转载请保留原文出处、译者和译文链接。]

相关文章

    暂无相关文章
相关栏目:

相关文章

    用户点评