Skip to content

Location Search

Joyce Babu edited this page Aug 26, 2022 · 1 revision

We offer our API users a location search widget for use with our API.

The following script will add location search functionality to all input fields with class prokerala-location-input.

The script will inject two hidden fields named timezone and coordinates into the form, which will be updated with the timezone and coordinates of the location selected by the user.

// Visit https://api.prokerala.com/demo/birth-details.php to see the following code in action
const PK_API_CLIENT_ID = '';
(function () {
    function loadScript(cb) {
        var script = document.createElement('script');
        script.src = 'https://client-api.prokerala.com/static/js/location.min.js';
        script.onload = cb;
        script.async = 1;
        document.head.appendChild(script);
    }

    function createInput(name, value) {
        const input = document.createElement('input');
        input.name = name;
        input.type = 'hidden';

        return input;
    }
    function initWidget(input) {
        const form = input.form;
        const inputPrefix = input.dataset.locationInputPrefix ? input.dataset.locationInputPrefix : '';
        const coordinates = createInput(inputPrefix +'coordinates');
        const timezone = createInput(inputPrefix +'timezone');
        form.appendChild(coordinates);
        form.appendChild(timezone);
        new LocationSearch(input, function (data) {
            coordinates.value = `${data.latitude},${data.longitude}`;
            timezone.value = data.timezone;
            input.setCustomValidity('');
        }, {clientId: PK_API_CLIENT_ID, persistKey: `${inputPrefix}loc`});

        input.addEventListener('change', function (e) {
            input.setCustomValidity('Please select a location from the suggestions list');
        });
    }
    loadScript(function() {
        let location = document.querySelectorAll('.prokerala-location-input');
        Array.from(location).map(initWidget);
    });
})();

Usage

  1. Add the css class prokerala-location-input to the input to which you want to add location search functionality.
  2. Append the above script to the footer of the page.
  3. Update the variable PK_API_CLIENT_ID with your client id from Prokerala API Dashboard.
  4. Ensure that your website domain is whitelisted under your App's Authorized Javascript Origin on your dashboard.
  5. If you have want to add location search to multiple fields within the same form, add the attribute data-location-input-prefix to the input field. The prefix will be added to the hidden fields created for timezone and `coordinates``.

Clone this wiki locally