用javascript进行地理定位

Mar*_*ens 5 javascript compatibility geolocation

我正在编写一个脚本来获取Geolocations(Lat,lon),我可以使用它来集中我的谷歌地图实例.现在我使用2种可能的技术.一个是google.loader.ClientLocation对象.我还没有测试过这个,因为它为我返回null.我想因为我不住在普通的地方(威廉斯塔德,库拉索岛使用无线互联网连接.所以我的调制解调器是无线的.).

因此我制作了一个备用计划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);
}
Run Code Online (Sandbox Code Playgroud)

PS.我知道有这样的SO更多的问题,但无法找到一个明确的答案.我希望人们做出一些新的发现.

更新: 尝试谷歌齿轮以及.再次成功镀铬.在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);
}
Run Code Online (Sandbox Code Playgroud)

更新2: navigator.geolocation从我的工作位置在FF中正常工作.

最后结果

这非常有效.从ipinfodb.org获取api密钥

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 '';
    }
}
Run Code Online (Sandbox Code Playgroud)