Using geolocation data in your web application

Categories 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.

Leave a Reply

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