JavaScript Google地图协调验证 [英] JavaScript Google Map Coordinate Validation
问题描述
我有一个表单,您可以在地图上选择一个点,并填充经纬度文本框,或者您可以自己输入坐标。
我需要添加验证以确保用户输入有效范围,但我不确定是否拥有正确的RegEx。这是我使用的方法:
var regex_coords =[ - ]?[0-9] * [。] { 0,1} [0-9];
// ...
valid_coords:函数(数字){
if(number.match(regex_coords)&&!isNaN(Number(number ))){
$(#btnSaveResort)。removeAttr(disabled);
返回true;
} else {
$(#btnSaveResort)。attr(disabled,disabled);
返回false;
$ b $ p $这个函数返回false,无论我输入了什么在文本框中。
任何建议都有更好的方法吗?
解决方案纬度和经度有不同的范围:纬度是(-90,90)和经度是(-180,180),所以使用单个正则表达式并不真正起作用。您可能还想检查纬度是否可以在地图上绘制 - —这意味着它需要位于大约(-85,85)的范围内。或者你可能想限制范围到一个包含特定区域的边界矩形。
为什么不明确测试范围?
$ b $如果(!isNaN(number)&&(number> = min)&&((b,$ b pre $ 函数inrange(min,number,max) number <= max)){
return true;
} else {
return false;
};
}
然后,您可以根据需要定制代码。假设你只想在经纬度都有效时启用保存按钮。
if(inrange(-90,number_lat,90)& inrange(-180,number_lng,180)){
$(#btnSaveResort)。removeAttr(disabled);
返回true;
}
else {
$(#btnSaveResort)。attr(disabled,disabled);
返回false;
}
}
I have a form where you can select a point on the map, and it populates lat and lon textboxes, or you can enter the coordinates yourself.
I need to add validation to make sure the user enters valid ranges, but I am not sure if I have the right RegEx. Here is the method I am using:
var regex_coords = "[-]?[0-9]*[.]{0,1}[0-9]";
// ...
valid_coords: function (number) {
if (number.match(regex_coords) && !isNaN(Number(number))) {
$("#btnSaveResort").removeAttr("disabled");
return true;
} else {
$("#btnSaveResort").attr("disabled", "disabled");
return false;
}
},
This function returns false no matter what I have entered in the textboxes.
Any suggestions on a better way?
Latitude and longitude have different ranges: latitude is (-90,90) and longitude is (-180,180), so using a single regex is not really going to work. You might also want to check that the latitude can be plotted on the map — which means that it needs to lie in the range (-85,85) approximately. Or you might want to limit the range to a bounding rectangle containing a particular area.
Why not explicitly test the ranges?
function inrange(min,number,max){
if ( !isNaN(number) && (number >= min) && (number <= max) ){
return true;
} else {
return false;
};
}
You can then tailor your code for what you want. Presumably you only want to enable the save button if both latitude and longitude are valid.
valid_coords: function(number_lat,number_lng) {
if (inrange(-90,number_lat,90) && inrange(-180,number_lng,180)) {
$("#btnSaveResort").removeAttr("disabled");
return true;
}
else {
$("#btnSaveResort").attr("disabled","disabled");
return false;
}
}
这篇关于JavaScript Google地图协调验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!