使用纬度和经度值在Android中创建Location对象

fon*_*man 125 android location distance

我有一个程序,其中一个位置的纬度和经度值存储在我下载的数据库中.

我想得到这些坐标和我当前位置之间的距离.

Location类有一个简单的方法来查找两个Location对象之间的距离,所以我想我会用坐标创建一个Location对象,然后调用该方法.

是否有捷径可寻?而且,如果还有另一个可靠,相当简单的方程式,它不会使事情变得太混乱,那也会起作用.谢谢.

(android.location.Location)

And*_*son 287

假设您已经拥有一个包含当前位置的位置对象.

Location targetLocation = new Location("");//provider name is unnecessary
targetLocation.setLatitude(0.0d);//your coords of course
targetLocation.setLongitude(0.0d);

float distanceInMeters =  targetLocation.distanceTo(myLocation);
Run Code Online (Sandbox Code Playgroud)

  • Android的文档真的很糟糕的例子,浪费了相当多的时间.我的另一个问题是假设我提供了一个像gps这样的有效提供商,它会给我当前的位置吗?换句话说,提供者的意义是什么 (2认同)

dst*_*dst 30

您可以使用其构造函数创建位置,然后设置latutude和longitude值.

final Location location = new Location("yourprovidername");
location.setLatitude(1.2345d);
location.setLongitude(1.2345d);
Run Code Online (Sandbox Code Playgroud)


Vij*_*y E 11

我正在回答这个问题,因为像我这样的很多人都不知道究竟"providername"是什么.下面的代码回答了问题:

Location location = new Location(LocationManager.GPS_PROVIDER);
location.setLatitude(23.5678);
location.setLongitude(34.456);
Run Code Online (Sandbox Code Playgroud)

我在这里使用LocationManager.GPS_PROVIDER提供商.

  • 但是,如果手动创建“location”对象,那么使用空字符串不是比“LocationManager.GPS_PROVIDER”、“LocationManager.PASSIVE”或“LocationManager.NETWORK_PROVIDER”更合适吗? (2认同)