开发者

Android: How to: validate Location's latitude and longitude values

开发者 https://www.devze.com 2023-04-03 12:17 出处:网络
How do yo开发者_JAVA百科u 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 A

How do yo开发者_JAVA百科u 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)


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


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/


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
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消