Using geolocation data in your web application

ASP.NET, PHP, Tutorials

Knowing where your web applications users location is a useful feature, that can help you provide a better service. For instance, you can show them results that are tailored to their location or display their location on the map or convert latitude/longitude to a street address. There is a handy Geolocation API in Javascript that can provide the user’s location, we just need to find the way to pass this data to the server-side and save it in session variables.

We want to get this data as soon as possible so some of the code needs to the added to the start page of your application, i.e. login page or menu page.

1. Javascript OnLoad event of the start page (login or menu)

If we haven’t acquired geolocation data yet and Geolocation API is supported by the web browser we will get latitude/longitude values and pass it via AJAX post to our application.

PHPRunner

if(!proxy.haveLocation){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    function showPosition(position) {
        $.post("menu.php",{
             lat:position.coords.latitude,
            lng:position.coords.longitude
        })
    }
}

ASPRunner.NET

if(!proxy.haveLocation){
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    function showPosition(position) {
        $.post("menu",{
             lat:position.coords.latitude,
            lng:position.coords.longitude
        })
    }
}

The browser will ask user if they want to disclose their location.

2. BeforeDisplay event of the start page.

PHP

if($_SESSION["geoLatitude"] && $_SESSION["geoLongitude"])
    $pageObject->setProxyValue('haveLocation', true);

C#

if(XSession.Session["geoLatitude"] && XSession.Session["geoLongitude"])
    pageObject.setProxyValue ("haveLocation", true);

3. AfterAppInit event

This code processes the AJAX post and saves data in session variables.

PHP

if(postvalue("lat") && postvalue("lng")){
    $_SESSION["geoLatitude"] = postvalue("lat");
    $_SESSION["geoLongitude"] = postvalue("lng");
    exit();
}

C#

if(MVCFunctions.postvalue("lat") && MVCFunctions.postvalue("lng")){
    XSession.Session["geoLatitude"] = MVCFunctions.postvalue("lat");
    XSession.Session["geoLongitude"] = MVCFunctions.postvalue("lng");
    MVCFunctions.Exit();
}

Now, on any page, you can use session variables $_SESSION[“geoLatitude”] and $_SESSION[“geoLongitude”] (XSession.Session[“geoLatitude”] and XSession.Session[“geoLongitude”] in C#) to do something useful with it.

4 thoughts on “Using geolocation data in your web application

  1. How to get the closest lat , long of this code from the database would help us use it. otherwise it is useless.

  2. Awesome code – the trouble for me was that it only stored the Lat/Long in the session variables once – so they got stuck there. This code in the Javascript Page Load refreshes those session variables every time

    function OnPageLoad(pageObj,pageid,proxy,row)
    {

    var options = {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
    };

    function success(pos) {
    //use proxy to store lat and lon in session variables on server
    $.post(“menu.php”,{
    lat:pos.coords.latitude,
    lng:pos.coords.longitude
    })

    }

    function error(err) {
    console.warn(`ERROR(${err.code}): ${err.message}`);
    }

    var watchID = navigator.geolocation.watchPosition( success, error, options );
    var timeout = setTimeout( function() { navigator.geolocation.clearWatch( watchID ); }, 5000 );

    //call get position with options that force a recently aquired location
    navigator.geolocation.getCurrentPosition(success, error, options);

    //probably not nesessary too lazy to take it out –
    function showPosition(position) {
    $.post(“menu.php”,{
    lat:position.coords.latitude,
    lng:position.coords.longitude
    })
    }

    }

  3. I learned it hard way that this method requires page to be loaded twice at first to set coordinates in session variables of longitude and latitude. How can I get the variables in one go? or am I wrong?

Leave a Reply

Your email address will not be published. Required fields are marked *