8

How do you validate Location? seems that setting it to these values Location.setLatitude(999) & Location.setLongitude(999) are valid (means there's no any validation). Is there a Android way to validate it? (i know the maximum and minimum values of it but just wondering if there's already available using Android)

Cœur
  • 37,241
  • 25
  • 195
  • 267
eros
  • 4,946
  • 18
  • 53
  • 78

3 Answers3

18

Here is the simple function that validates latitude and longitude

public boolean isValidLatLng(double lat, double lng){
    if(lat < -90 || lat > 90)
    {
        return false;
    }
    else if(lng < -180 || lng > 180)
    {
        return false;
    }
    return true;
}

Latitude measures how far north or south of the equator a place is located. The equator is situated at 0°, the North Pole at 90° north (or 90°, because a positive latitude implies north), and the South Pole at 90° south (or –90°). Latitude measurements range from 0° to (+/–)90°.

Longitude measures how far east or west of the prime meridian a place is located. The prime meridian runs through Greenwich, England. Longitude measurements range from 0° to (+/–)180°.

Reference taken from https://msdn.microsoft.com/en-us/library/aa578799.aspx

Arun
  • 273
  • 3
  • 13
2

I don't think there is anything in Android to do this. Like you said, it's probably best to just define the min and max.

On a side note, you could call Google's Geocoding service and pass in your lat and long as input parameters to check the result for a valid location before calling Location.setLatitude(): http://code.google.com/apis/maps/documentation/geocoding/

Ben Jakuben
  • 3,147
  • 11
  • 62
  • 104
  • >check the result for a valid location before calling Location.setLatitude() -> can't understand this phrase, would you elaborate it more? How can I check the result? – eros Sep 09 '11 at 02:58
  • I was thinking you could call the service and get a JSON or XML result. Here's an example of a JSON response; you could check for the "OK" status and allow or deny the parameters based on this return code: http://code.google.com/apis/maps/documentation/geocoding/#JSON – Ben Jakuben Sep 09 '11 at 15:11
  • Got it. but i opt to create my own simple validation by defining min and max because I am not using google's api. – eros Sep 12 '11 at 00:39
0

A Kotlin solution that I made on the playground can be found here. Logic is from another stack overflow answer

data class LatLng(val latitude: Double, val longitude: Double) {
    val isValid: Boolean by lazy {
        latitude >= -90 && latitude <= 90
                && longitude >= -180 && longitude <= 180
    }
}
Andrew Steinmetz
  • 1,010
  • 8
  • 16