Londinium.com set location javascript Londinium.com set location javascript

February 18, 2022

londinium openstreetmap

My londinium.com website has 2 types of maps, fixed locations like postcodes, train stations and places, but also features and brands which are more relevant to the users location.

Today I tackled the issue of setting the user location with a cookie so that the features and brand maps are more relevant to the users location.

This was a project for javascripting.

I created a new page setLocation with the following function to set the cookie at the point of click.

function onMapClick(e) {
    //map click event object (e) has latlng property which is a location at which the click occured.
    popup
        .setLatLng(e.latlng)
        .setContent("<h2>LOCATION COOKIE SET</h2> <strong>Lat " + e.latlng.lat + "</strong><br><strong>Long " +
            e.latlng.lng +
            "</strong>")
        .openOn(mymap);
    lat = "lat=" + e.latlng.lat + '; path = /; sameSite=Lax;';
    long = "long=" + e.latlng.lng + '; path = /; sameSite=Lax;';
    document.cookie = lat;
    document.cookie = long;
}

And some new functionality to use the new cookie variables if set on the features and brand pages.

    function getCookie(name) {
        // Split cookie string and get all individual name=value pairs in an array
        var cookieArr = document.cookie.split(";");

        // Loop through the array elements
        for (var i = 0; i < cookieArr.length; i++) {
            var cookiePair = cookieArr[i].split("=");

            /* Removing whitespace at the beginning of the cookie name
            and compare it with the given string */
            if (name == cookiePair[0].trim()) {
                // Decode the cookie value and return
                return decodeURIComponent(cookiePair[1]);
            }
        }
        // Return null if not found
        return null;
    }
window.onload = function () {
    var Lat = 51.5
    var cookieLat = getCookie("lat");
    if (cookieLat != null) {
        Lat = getCookie("lat");
    }
    var Long = -0.144
    var cookieLong = getCookie("long");
    if (cookieLong != null) {
        Long = getCookie("long");
    }

    map = L.map('map').setView([Lat, Long], 14);

I am sure it could be improved, but it works and allows both a default and user set value.


If you would like to contact me you can either use this form on londinium.com or via Twitter @andylondon