【问题标题】:Geolocations with javascript使用 JavaScript 进行地理定位
【发布时间】:2011-05-23 05:56:59
【问题描述】:

我正在编写一个脚本来获取地理定位(经纬度),我可以使用它来将我的谷歌地图实例居中。现在我使用两种可能的技术。一个是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);
}

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 获取 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 '';
    }
}

【问题讨论】:

    标签: javascript geolocation compatibility


    【解决方案1】:

    使用 javascript 的地理定位将适用于兼容 HTML 5 的浏览器,因此完全省去了 IE。

    您的替代方法是使用 IP 地址来确定大致的纬度/经度。

    使用此替代方法并假设您找到的提供商具有准确且完整的经纬度到 IP 映射,您将只能获得 ISP 的纬度/经度(或 ISP 连接到互联网的最近点)。

    希望这会重置您的期望(关于位置准确性)

    【讨论】:

      【解决方案2】:

      我遇到了类似的问题,对于没有地理位置的浏览器,我使用基于用户 IP 的服务器端位置。

      两种免费的地理定位服务是:

      我发现 maxmind 对我来说更准确。

      如果可能在您的项目中,您可以在呈现页面之前查询位置,或者执行 ajax 调用来查询位置。

      【讨论】:

      • 是的,这两种方法都可以。会调查的。
      • maxmind 对我来说非常好用!谢谢。 hostip 不准确 5-10 英里,因此对于需要合理精度半径的任何人来说可能都无法真正使用。
      【解决方案3】:

      【讨论】:

      • 感谢您的链接。一些建议在那里可能有用,但它高度关注移动设备。
      • 代码不是设计成可以在移动和网络之间移植(尤其是那些在 W3C API 规范下的)吗?可以理解的是,GPS 不存在,但我认为它应该会故障恢复到安全的地方。
      猜你喜欢
      • 2010-11-22
      • 2012-01-04
      • 1970-01-01
      • 2010-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多