javascript的地理位置
我正在研究一个脚本来获取地理位置(Lat,lon),我可以用它来居中管理我的Google地图实例。目前我使用2种可能的技术。一个是google.loader.ClientLocation
对象。我还没有测试过这个,因为它为我返回null。我想因为我不是住在一个固定的位置(威廉斯塔德,库拉索使用无线互联网连接,所以我的调制解调器是无线的)。javascript的地理位置
因此我使用navigator.geolocation
做了一个备份计划。这在Chrome中效果很好,但是Firefox会超时并且在IE中完全不起作用。
有谁知道一个很好的替代方法来获取用户的地理位置,或没有人有我的代码推荐如何可以变得更加稳定。
我设置了navigator.geolocation
的超时时间,因为我不希望我的用户等待5秒钟。增加超时并不会提高Firefox的可靠性。
function init_tracker_map() {
var latitude;
var longitude;
if(google.loader.ClientLocation) {
latitude = (google.loader.ClientLocation.latitude);
longitude = (google.loader.ClientLocation.longitude);
buildMap(latitude, longitude);
}
else if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
latitude = (position.coords.latitude);
longitude = (position.coords.longitude);
buildMap(latitude, longitude);
},
function errorCallback(error) {
useDefaultLatLon();
},
{
enableHighAccuracy:false,
maximumAge:Infinity,
timeout:5000
}
);
}
else {
useDefaultLatLon();
}
}
function useDefaultLatLon() {
latitude = (51.81540697949437);
longitude = (5.72113037109375);
buildMap(latitude, longitude);
}
ps。我知道在SO上还有更多这样的问题,但找不到明确的答案。我希望人们提出一些新的发现。
更新: 尝试谷歌齿轮以及。再次在chrome中成功。在FF和IE中失败。
var geo = google.gears.factory.create('beta.geolocation');
if(geo) {
function updatePosition(position) {
alert('Current lat/lon is: ' + position.latitude + ',' + position.longitude);
}
function handleError(positionError) {
alert('Attempt to get location failed: ' + positionError.message);
}
geo.getCurrentPosition(updatePosition, handleError);
}
更新2:navigator.geolocation
工作正常FF从我的工作地点。
最终结果
这个伟大的工程。从ipinfodb.org
var Geolocation = new geolocate(false, true);
Geolocation.checkcookie(function() {
alert('Visitor latitude code : ' + Geolocation.getField('Latitude'));
alert('Visitor Longitude code : ' + Geolocation.getField('Longitude'));
});
function geolocate(timezone, cityPrecision) {
alert("Using IPInfoDB");
var key = 'your api code';
var api = (cityPrecision) ? "ip_query.php" : "ip_query_country.php";
var domain = 'api.ipinfodb.com';
var version = 'v2';
var url = "http://" + domain + "/" + version + "/" + api + "?key=" + key + "&output=json" + ((timezone) ? "&timezone=true" : "&timezone=false") + "&callback=?";
var geodata;
var JSON = JSON || {};
var callback = function() {
alert("lol");
}
// implement JSON.stringify serialization
JSON.stringify = JSON.stringify || function (obj) {
var t = typeof (obj);
if (t != "object" || obj === null) {
// simple data type
if (t == "string") obj = '"'+obj+'"';
return String(obj);
}
else {
// recurse array or object
var n, v, json = [], arr = (obj && obj.constructor == Array);
for (n in obj) {
v = obj[n]; t = typeof(v);
if (t == "string") v = '"'+v+'"';
else if (t == "object" && v !== null) v = JSON.stringify(v);
json.push((arr ? "" : '"' + n + '":') + String(v));
}
return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
}
};
// implement JSON.parse de-serialization
JSON.parse = JSON.parse || function (str) {
if (str === "") str = '""';
eval("var p=" + str + ";");
return p;
};
// Check if cookie already exist. If not, query IPInfoDB
this.checkcookie = function(callback) {
geolocationCookie = getCookie('geolocation');
if (!geolocationCookie) {
getGeolocation(callback);
}
else {
geodata = JSON.parse(geolocationCookie);
callback();
}
}
// Return a geolocation field
this.getField = function(field) {
try {
return geodata[field];
} catch(err) {}
}
// Request to IPInfoDB
function getGeolocation(callback) {
try {
$.getJSON(url,
function(data){
if (data['Status'] == 'OK') {
geodata = data;
JSONString = JSON.stringify(geodata);
setCookie('geolocation', JSONString, 365);
callback();
}
});
} catch(err) {}
}
// Set the cookie
function setCookie(c_name, value, expire) {
var exdate=new Date();
exdate.setDate(exdate.getDate()+expire);
document.cookie = c_name+ "=" +escape(value) + ((expire==null) ? "" : ";expires="+exdate.toGMTString());
}
// Get the cookie content
function getCookie(c_name) {
if (document.cookie.length > 0) {
c_start=document.cookie.indexOf(c_name + "=");
if (c_start != -1){
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end == -1) {
c_end=document.cookie.length;
}
return unescape(document.cookie.substring(c_start,c_end));
}
}
return '';
}
}
我也有类似的问题,并针对浏览器不地理位置,与服务器端的位置就根据用户的IP获取API密钥。
两个免费的地理定位服务主要有:
我发现的MaxMind我更准确。
如果可能在您的项目中,您可以在呈现页面之前查询位置,或执行ajax调用以查询位置。
使用javascript的地理位置将与HTML 5兼容的浏览器一起使用,以便完全忽略IE。
您的替代方案是使用IP地址来确定近似经纬度。
使用这种替代方法,并假设您找到一个准确完整的经纬度/长距IP映射的提供商,您只能得到ISP的纬度/经度(或者ISP连接到的最近点互联网)。
希望这会重置您的期望(关于位置精度)
感谢您的链接。有些建议可能在那里有用,但它非常专注于移动设备。 – 2010-12-10 02:47:04
设计的移动和网页之间的移动代码(特别是那些在W3C API规范下)不是可移植的代码吗?可以理解的是,GPS并不存在,但我认为它应该会失败回到安全的地方。 – jocull 2010-12-14 16:07:17