67

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?

Skizit
  • 43,506
  • 91
  • 209
  • 269

4 Answers4

123

The API documentation is quite clear on this. First create a new Location instance:

Location loc = new Location("dummyprovider");

And then use the setter methods to set the location parameters you need, e.g.:

loc.setLatitude(20.3);
loc.setLongitude(52.6);
Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • Location loc = new Location(""); – Gennady Kozlov Nov 30 '16 at 20:53
  • 4
    @AdamJohns: The provider is supposed to specify what exactly acquired the specific coordinate fix. In the `Location` object it's just a string field and can be anything. When dealing with actual location fixes it'll often be equal to one of the constants in `LocationManager` such as [`GPS_PROVIDER`](https://developer.android.com/reference/android/location/LocationManager.html#GPS_PROVIDER) which equals `"gps"`, which would mean that the specific location was acquired via GPS. – Matti Virkkunen Dec 21 '16 at 11:57
7
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

double lat = object.getLatitude();
double lng = object.getLongitude();
Itai Sagi
  • 5,537
  • 12
  • 49
  • 73
Atta Ullah
  • 71
  • 1
  • 4
6

In Kotlin using LocationManager class you can pass the required location provider like:

val location = Location(LocationManager.NETWORK_PROVIDER) // OR GPS_PROVIDER based on the requirement
location.latitude = 42.125
location.longitude = 55.123
Shailendra Madda
  • 20,649
  • 15
  • 100
  • 138
2

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():

Location myLoc = createNewLocation(Double.parse("s.Long"), Double.parse("s.Lati"));
Kuvalya
  • 1,094
  • 1
  • 15
  • 26