使用javascript进行地理定位 [英] Geolocations with javascript
问题描述
我正在研究脚本以获取Geolocations(Lat,lon),我可以使用它来居中管理我的Google地图实例。目前我使用2种可能的技术。一个是 google.loader.ClientLocation
对象。我还没有测试过这个,因为它为我返回null。我想因为我不是住在一个固定的位置(威廉斯塔德,库拉索使用无线互联网连接,所以我的调制解调器是无线的)。
因此,我使用 navigator.geolocation
制定了备份计划。这在Chrome中效果很好,但firefox提供了超时功能,并且在IE中完全不起作用。
有没有人知道获取用户地理位置的好方法,或者是否有人在我的代码上推荐它如何变得更稳定。
我为 navigator.geolocation
因为我不希望我的用户等待5秒钟以上。
函数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();
函数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);
}
函数handleError(positionError){
alert('尝试获取位置失败:'+ positionError.message);
}
geo.getCurrentPosition(updatePosition,handleError);
更新2: navigator.geolocation
在我的工作地点可正常工作。
最终结果
这很好。从ipinfodb.org获取api密钥
var Geolocation = new geolocate(false,true);
Geolocation.checkcookie(函数(){
alert('Visitor latitude code:'+ Geolocation.getField('Latitude'));
alert('Visitor Longitude code:'+ Geolocation。 getField('Longitude'));
});
函数geolocate(timezone,cityPrecision){
alert(Using IPInfoDB);
var key ='您的api代码';
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);
}
//实现JSON.stringify序列化
JSON.stringify = JSON.stringify ||函数(obj){
var t = typeof(obj);
if(t == =object|| obj === null){
//简单数据类型
if(t ==string)obj =''+ obj + '';
return String(obj);
}
else {
//递归数组或对象
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?]:});
}
};
//实现JSON.parse反序列化
JSON.parse = JSON.parse ||函数(str){
if(str ===)str ='';
eval(var p =+ str +;);
return p;
};
//检查cookie是否已经存在。如果没有,查询IPInfoDB
this.checkcookie = function(callback){
geolocationCookie = getCookie('geolocation');
if(!geolocationCookie){
getGeolocation(callback);
}
else {
geodata = JSON.parse(geolocationCookie);
callback();
//返回地理位置字段
this.getField = function(field){
try {
return geodata [领域];
} catch(err){}
}
//请求IPInfoDB
函数getGeolocation(callback){
try {
$ .getJSON(url,
function(data){
if(data ['Status'] =='OK')){
geodata = data;
JSONString = JSON.stringify (geodata);
setCookie('geolocation',JSONString,365);
callback();
}
});
} catch(err){}
}
//设置cookie
函数setCookie(c_name,value,expire){
var exdate =新日期();
exdate.setDate(exdate.getDate()+ expire);
document.cookie = c_name +=+ escape(value)+((expire == null)?:; expires =+ exdate.toGMTString());
}
//获取cookie内容
函数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'';
}
}
地理定位使用JavaScript将与HTML 5兼容的浏览器一起工作,从而完全消除IE。
您的替代方法是使用IP地址确定近似经纬度。
使用这种替代方法并假设您找到一个准确且完整的经纬度/长距IP映射的提供商,您只能获得ISP的纬度/经度(或ISP连接到互联网的最近点)。
希望这会重置您的预期(关于位置准确性)
I'm working on a script to get the Geolocations (Lat, lon) that I can use to center my instance of google maps. For now i work with 2 possible technologies. One is the google.loader.ClientLocation
object. I haven't tested this one yet because it returns null for me. I think because I'm not living on a regular location (Willemstad, Curacao using a wireless internet connection. So my modem is wireless.).
Therefore I made a backup plan using navigator.geolocation
. This works great in Chrome, but firefox gives a timeout and it doesn't work at all in IE.
Does anyone know a good alternative method to get the users geolocation, or does anyone have recommendation on my code how it can become more stable.
I set a timeout for navigator.geolocation
because I don't want my users to wait for more as 5 seconds. Increasing the timeout does not improve the reliability of 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. I'm aware there are more questions like this on SO but couldn't find a clear answer. I'm hoping that people made some new discovery's.
Update: Tried google gears aswell. Succesfull in chrome again. Fails in FF and 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);
}
Update 2: navigator.geolocation
works fine in FF from my work location.
Final Result
This works great. Get an api key from 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 '';
}
}
geolocation using javascript will work with HTML 5 compliant browsers, so that leaves out IE completely.
Your alternative is to use the IP address to ascertain the approximate lat/long.
Using this alternative method and assuming you find a provider with an accurate and complete lat/long-to-IP mapping, you will only get the lat/long of the ISP (or the nearest point where the ISP connects to the internet).
Hope this resets your expectation (about location-accuracy)
这篇关于使用javascript进行地理定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!