最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Geolocations with javascript - Stack Overflow

programmeradmin2浏览0评论

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 remendation on my code how it can bee 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

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

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 remendation on my code how it can bee 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

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.';
    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 '';
    }
}
Share Improve this question edited Dec 17, 2010 at 14:18 Mark Baijens asked Dec 10, 2010 at 2:10 Mark BaijensMark Baijens 13.3k11 gold badges50 silver badges76 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

geolocation using javascript will work with HTML 5 pliant browsers, so that leaves out IE pletely.

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 plete 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)

you should read this Which Devices Support Javascript Geolocation via navigator.geolocation?

I had a similar problem and, for browsers without geolocation, went with server-side location based on the user's IP.

Two free geolocation services are:

  • http://www.maxmind./app/geolitecity
  • http://www.hostip.info/

I found maxmind to me much more accurate.

If it's possible within your project you could query the location before rendering the page, or perform an ajax call to query the location.

发布评论

评论列表(0)

  1. 暂无评论