Android:如何初始化“位置”类型的变量(除了使其等于 null)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2985302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: How to initialize a variable of type "Location" (other than making it equal to null)
提问by Skizit
I'm looking to test some code I've written and to do so I need to construct a variable of type Location and to give it a long / lat value but I'm unsure how I would do so. Any ideas?
我希望测试我编写的一些代码,为此我需要构造一个 Location 类型的变量并为其赋予一个 long / lat 值,但我不确定我将如何这样做。有任何想法吗?
回答by Matti Virkkunen
The API documentationis quite clear on this. First create a new Location instance:
API 文档对此非常清楚。首先创建一个新的 Location 实例:
Location loc = new Location("dummyprovider");
And then use the setter methods to set the location parameters you need, e.g.:
然后使用setter方法设置你需要的位置参数,例如:
loc.setLatitude(20.3);
loc.setLongitude(52.6);
回答by Atta Ullah
Location object = new Location("service Provider");
it will create an object of Type Location that contains the initial Latitude and Longitude at location '0' to get the initial values use
它将创建一个 Location 类型的对象,其中包含位置 '0' 处的初始纬度和经度,以获取使用的初始值
double lat = object.getLatitude();
double lng = object.getLongitude();
回答by Kuvalya
You can write a method:
你可以写一个方法:
Location createNewLocation(double longitude, double latitude) {
Location location = new Location("dummyprovider");
location.setLongitude(longitude);
location.setLatitude(latitude);
return location;
}
And then call it:
然后调用它:
Location myLoc = createNewLocation(dLong, dLati);
Or you can use string with Double.parse():
或者您可以将字符串与 Double.parse() 一起使用:
Location myLoc = createNewLocation(Double.parse("s.Long"), Double.parse("s.Lati"));
回答by Shylendra Madda
In Kotlin using LocationManager
class you can pass the required location provider like:
在 Kotlin 中使用LocationManager
类,您可以传递所需的位置提供程序,例如:
val location = Location(LocationManager.NETWORK_PROVIDER) // OR GPS_PROVIDER based on the requirement
location.latitude = 42.125
location.longitude = 55.123