我有兩個UITextFields,用戶可以輸入經緯度,然後這些座標用於在MKMapView上創建一個pin。如何驗證經度和緯度
我想找到一種方法來驗證它們輸入的值是實際的GPS座標還是隻是垃圾的負載。有沒有辦法做到這一點?
我有兩個UITextFields,用戶可以輸入經緯度,然後這些座標用於在MKMapView上創建一個pin。如何驗證經度和緯度
我想找到一種方法來驗證它們輸入的值是實際的GPS座標還是隻是垃圾的負載。有沒有辦法做到這一點?
我會做這樣的事情
numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *latitude = [numberFormatter numberFromString:theInputString];
if((latitude != nil)
{
//check it is within lat/long range
} else {
//not even a valid number, reject it
}
CLLocationCoordinate2D p1;
p1.latitude = [[punto latitud] doubleValue];
p1.longitude = [[punto longitud] doubleValue];
if (CLLocationCoordinate2DIsValid(p1))
{
[Mapa addAnnotation:annotationPoint];
}
此答案位於低質量帖子評論隊列中,因爲它只是代碼而沒有解釋。請通過解釋您的代碼的作用以及它如何回答問題來改進您的答案。請閱讀[有關回答編程問題的建議](http://msmvps.com/blogs/jon_skeet/archive/2009/02/17/answering-technical-questions-helpfully.aspx)。 –
使用後續的緯度和經度正則表達式,我們可以驗證。
隨着Objective-C的轉義字符:
緯度的正則表達式:
@"^(\\+|-)?((\\d((\\.)|\\.\\d{1,6})?)|(0*?[0-8]\\d((\\.)|\\.\\d{1,6})?)|(0*?90((\\.)|\\.0{1,6})?))$"
經度正則表達式:對於這兩個緯度&經度
@"^(\\+|-)?((\\d((\\.)|\\.\\d{1,6})?)|(0*?\\d\\d((\\.)|\\.\\d{1,6})?)|(0*?1[0-7]\\d((\\.)|\\.\\d{1,6})?)|(0*?180((\\.)|\\.0{1,6})?))$"
普通的正則表達式:
緯度RegEx:
^(\+|-)?((\d((\.)|\.\d{1,6})?)|(0*?[0-8]\d((\.)|\.\d{1,6})?)|(0*?90((\.)|\.0{1,6})?))$
經度正則表達式:
^(\+|-)?((\d((\.)|\.\d{1,6})?)|(0*?\d\d((\.)|\.\d{1,6})?)|(0*?1[0-7]\d((\.)|\.\d{1,6})?)|(0*?180((\.)|\.0{1,6})?))$
通過大量的StackOverflow的問題去後,我想這個問題被問了說明什麼,我一直在尋找解決我的緯度/經度簡單和直接的方式驗證AMZO:A Global Map Based Station for Reporting Aliens, Monsters, Zombies and Other Interesting Events(iPhone/iPad應用程序)。我知道,無恥的,但我認爲我應該得到一個完整和優雅的答案/解決方案(適應克雷格上面的簡要答案)!
我正在使用新的AlertController,它調用緯度和經度文本輸入的以下每個驗證。
- (BOOL) validateInput1: (NSString *) latitude
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *latitude1 = [numberFormatter numberFromString:latitude];
if (latitude1 != nil)
{
//check it is within lat/long range
if ((latitude1.floatValue > -90.0) && (latitude1.floatValue < 90.0)) {
NSLog(@"Hello Latitude!!!");
return 1;
}
} else {
//not even a valid number, reject it
return 0;
}
return 0;
}
- (BOOL) validateInput2: (NSString *) longitude
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *longitude1 = [numberFormatter numberFromString:longitude];
if (longitude1 != nil)
{
//check it is within lat/long range
if ((longitude1.floatValue > -180.0) && (longitude1.floatValue < 180.0)) {
NSLog(@"Hello Longitude!!!");
return 1;
}
} else {
//not even a valid number, reject it
return 0;
}
return 0;
}
很酷,這是真的嗎? – Pacerier
答案與解釋,http://stackoverflow.com/a/6536279/368691。是的,這是正確的答案。但是,這是假設土地和海洋。 – Gajus
我們是否應該包含邊界? (long> = -180 && long <= 180)或(long> -180 && long <180)? – Mehmed