Geolocation using javascript

I am working on a script to get Geolocations (Lat, lon), which I can use to center my copy of google maps. At the moment I am working with two possible technologies. One of them is an object google.loader.ClientLocation. I have not tested this one yet because it returns null for me. I think because I do not live in the usual place (Willemstad, Curacao, using a wireless Internet connection, so my modem is wireless).

So I made a backup plan using navigator.geolocation. This works fine 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 users geolocation, or anyone has recommendations on my code on how it can become more stable.

I set a timeout for navigator.geolocationbecause I do not want my users to wait more than 5 seconds. Increasing the timeout does not increase 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 know there are more such questions on SO, but I couldn’t find a clear answer. I hope people make a new discovery.

Update: I also tried google gears. Successfully in chrome again. Failure 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 workstation.

Final result

This works great. Get 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 '';
    }
}
+5
3

javascript , HTML 5, IE.

IP- lat/long.

, lat/long-to-IP, / ISP ( , - ).

, ( )

+2

I had a similar problem, and for browsers that did not have geolocation, they went to the server location based on the user's IP address.

Two free geolocation services:

I found maxmind much more accurate for me.

If possible within your project, you can request a location before displaying the page or make an ajax call to request a location.

0
source

All Articles