Extract latitude and longitude data using Mapbox's autocomplete feature

Currently, I have integrated Mapbox with autocomplete in a Vue component:

<template>
    <div>
        <div id='geocoder'></div>
    </div>
</template>

<script>
    import mapboxgl from 'mapbox-gl';

    export default {
        data() {
            return {
                map: null
            }
        },

        created() {
            Event.$on('map-created', (map) => {
                this.map = map;

                let geocoder = new MapboxGeocoder({
                    accessToken: mapboxgl.accessToken,
                });

                document.getElementById('geocoder').appendChild(geocoder.onAdd(this.map));
            });
        }
    }
</script>

The current functionality is satisfactory, but I am facing an issue. How can I retrieve the longitude and latitude when a user clicks on a result?

Is there a specific event that I should listen for? I couldn't find relevant information in the documentation.

Thanks in advance for your help!

Answer №1

If you're looking to retrieve the longitude and latitude of a selected location from an autocomplete feature, the following code snippet will do just that:

var geolocation = new GoogleGeocoder({
    apiKey: googleMapsAPIKey,
    type: 'location',
    googleMaps: google.maps
});

//Wait for the result event to be triggered by the geocoder.
//'result' event occurs when a user selects a location
geolocation.on('result', function(event) {
    var coordinates = event.result.coordinates;
});

Answer №2

Give this a shot:

this.map.on('click', '[YOUR LAYER ID]', (event) => {

    console.log(event.features[0].geometry.coordinates);

});

This little trick has been really handy for me when I'm working with my custom layers.

Answer №3

Implement Autocomplete Feature with Mapbox API

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Add Autocomplete with Geocoder</title>
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no"/>

    <script src="https://code.jquery.com/jquery-3.4.1.js" type="text/javascript"></script>
    <script src="https://unpkg.com/@mapbox/mapbox-sdk/umd/mapbox-sdk.min.js"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        * {
            box-sizing: border-box;
        }

        body {
            font: 16px Arial;
        }

        /* Styling for autocomplete input field */
        .autocomplete {
            position: relative;
            display: inline-block;
        }

        input {
            border: 1px solid transparent;
            background-color: #f1f1f1;
            padding: 10px;
            font-size: 16px;
        }

        input[type=text] {
            background-color: #f1f1f1;
            width: 100%;
        }

        input[type=submit] {
            background-color: DodgerBlue;
            color: #fff;
            cursor: pointer;
        }

        .autocomplete-items {
            position: absolute;
            border: 1px solid #d4d4d4;
            border-bottom: none;
            border-top: none;
            z-index: 99;
            top: 100%;
            left: 0;
            right: 0;
        }

        .autocomplete-items div {
            padding: 10px;
            cursor: pointer;
            background-color: #fff;
            border-bottom: 1px solid #d4d4d4;
        }

        .autocomplete-items div:hover {
            background-color: #e9e9e9;
        }

        .autocomplete-active {
            background-color: DodgerBlue !important;
            color: #ffffff;
        }
    </style>
</head>
<body>

<h2>Autocomplete Example</h2>

<p>Start typing to see suggestions:</p>

<form autocomplete="off" action="/action_page.php">
    <div class="autocomplete" style="width:300px;">
        <input id="myInput" type="text" name="myCountry" placeholder="Enter Country Name">
    </div>
    <input type="submit">
</form>

<script>

    var geocodingClient = mapboxSdk({accessToken: 'ADD_YOUR_ACCESS_TOKEN_HERE'});

    function autocompleteSuggestionMapBoxAPI(inputParams, callback) {
        geocodingClient.geocoding.forwardGeocode({
            query: inputParams,
            countries: ['In'],
            autocomplete: true,
            limit: 5,
        })
        .send()
        .then(response => {
            const match = response.body;
            callback(match);
        });
    }

    function autocompleteInputBox(inp) {
        // Functionality for autocomplete
        var currentFocus;
        inp.addEventListener("input", function (e) {
            var a, b, i, val = this.value;
            closeAllLists();
            if (!val) {
                return false;
            }
            currentFocus = -1;
            a = document.createElement("DIV");
            a.setAttribute("id", this.id + "autocomplete-list");
            a.setAttribute("class", "autocomplete-items");
            this.parentNode.appendChild(a);

            // Call Mapbox API endpoint for suggestions
            autocompleteSuggestionMapBoxAPI($('#myInput').val(), function (results) {
                results.features.forEach(function (key) {
                    b = document.createElement("DIV");
                    b.innerHTML = "<strong>" + key.place_name.substr(0, val.length) + "</strong>";
                    b.innerHTML += key.place_name.substr(val.length);
                    b.innerHTML += "<input type='hidden' data-lat='" + key.geometry.coordinates[1] + "' data-lng='" + key.geometry.coordinates[0] + "'  value='" + key.place_name + "'>";
                    b.addEventListener("click", function (e) {
                        let lat = $(this).find('input').attr('data-lat');
                        let long = $(this).find('input').attr('data-lng');
                        inp.value = $(this).find('input').val();
                        $(inp).attr('data-lat', lat);
                        $(inp).attr('data-lng', long);
                        closeAllLists();
                    });
                    a.appendChild(b);
                });
            })
        });

        // Keyboard functionality
        inp.addEventListener("keydown", function (e) {
            var x = document.getElementById(this.id + "autocomplete-list");
            if (x) x = x.getElementsByTagName("div");
            if (e.keyCode == 40) {
                currentFocus++;
                addActive(x);
            } else if (e.keyCode == 38) { 
                currentFocus--;
                addActive(x);
            } else if (e.keyCode == 13) {
                e.preventDefault();
                if (currentFocus > -1) {
                    if (x) x[currentFocus].click();
                }
            }
        });

        function addActive(x) {
            if (!x) return false;
            removeActive(x);
            if (currentFocus >= x.length) currentFocus = 0;
            if (currentFocus < 0) currentFocus = (x.length - 1);
            x[currentFocus].classList.add("autocomplete-active");
        }

        function removeActive(x) {
            for (var i = 0; i < x.length; i++) {
                x[i].classList.remove("autocomplete-active");
            }
        }

        function closeAllLists(elmnt) {
            var x = document.getElementsByClassName("autocomplete-items");
            for (var i = 0; i < x.length; i++) {
                if (elmnt != x[i] && elmnt != inp) {
                    x[i].parentNode.removeChild(x[i]);
                }
            }
        }

        document.addEventListener("click", function (e) {
            closeAllLists(e.target);
        });
    }

    autocompleteInputBox(document.getElementById("myInput"));
</script>


</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When an HTML input button within a table fails to trigger any jQuery function upon being clicked

I currently have a table set up with multiple rows and columns. <table style="width: 100%;" class='table_result'> <tr><td>Text</td><td>Text</td><td>Text</td><td>Text</td> ...

Vue.js - storing information within a component instead of utilizing a dynamically created modal

Seeking help to modify how descriptions are displayed alongside terms in a list. Currently, the descriptions appear in a modal when clicked, but I want them to show right next to the term. Below is the Vue component code: Vue.component('taxonomy-li ...

Exploring the world of Bootstrap Twitter 3.0 alongside the wonders of Knockout

When utilizing Twitter Bootstrap, the validation classes like has-error or has-warning must be added to the wrapping form-group element to style both the input and its label. However, Knockout-Validation directly adds the class to the input element itself. ...

Generate a custom website using React to display multiple copies of a single item dynamically

As a newcomer to React and web development, I've been pondering the possibility of creating dynamic webpages. Let's say I have a .json file containing information about various soccer leagues, structured like this: "api": { "results": 1376, ...

Combining arrays based on a key in Node.js

I have the following two objects that need to be merged: [ { "response_code": 1, "response_message": [{ "a": 1000, "b": 1000001, "c": 10000002 }] }] [ { "response_code": 1, ...

Can someone explain how to use JavaScript to make table data fill the entire row in a table?

After clicking the button, the layout of the table changes. I want to keep the original table layout even after the JavaScript function runs. I am still learning about JavaScript. function toggle(button) { if(document.getElementById("1").value=="Show ...

Deciphering unconventional JSON formats

Can anyone identify the format of this JSON (if it even is JSON!) from the code snippet below? I've extracted this data from a website's HTML and now I'm struggling to parse it in C# using a JSON parser. The data requires significant preproc ...

Learn how to pass data as props to child components in Vue3

I'm facing an issue where props are initialized, but they disappear after using .mount. Can anyone advise on the correct way to set up props with dynamically loaded components? import {createApp} from 'vue' blockView = createApp(Block); blo ...

Updating data scope in AngularJS using $http request not functioning properly

I am facing an issue where the $scope.user_free_status is not updating when I set a user free, but works perfectly fine when I unset the parameter. It's strange that I need to reload the page in one case and not the other. The data fetched is stored i ...

Combining the keys of two objects in JSON

console.log(a) ; // output in console window= 1 console.log(b);// output in console window= 2 var c = {a : b};// Is there a better way to do this? var d = JSON.stringify(c); d = encodeURIComponent(d); I want the final value of d to be {1:2}. ...

Encountering difficulties importing in Typescript and ts-node node scripts, regardless of configuration or package type

I am facing a challenge with my React Typescript project where multiple files share a similar structure but have differences at certain points. To avoid manually copying and pasting files and making changes, I decided to create a Node script that automates ...

How can I substitute a specific capture group instead of the entire match using a regular expression?

I'm struggling with the following code snippet: let x = "the *quick* brown fox"; let y = x.replace(/[^\\](\*)(.*)(\*)/g, "<strong>$2</strong>"); console.log(y); This piece of code replaces *quick* with <strong& ...

Tips on getting the dropdown value to show up on the header when it changes using Angular 2 and TypeScript

I need assistance with creating a dropdown field in Angular2. When the user selects "car", I want it to display beside the heading. Can anyone provide guidance on how to achieve this? HTML: <h1>Heading <span *ngFor= "let apps of apps">({{apps ...

Issue detected with Bundler: Configuration object is not valid. The initialization of Webpack used a configuration object that does not align with the API schema

I am currently struggling to make my bundler compile properly. When trying to get it working, I encountered this error message in my terminal along with my webpack.config.js file. Here is the issue reported by the terminal: Invalid configuration object. ...

Identify modifications in the input and at the same time update another input

I currently have two input text boxes. My goal is to synchronize the content of the second input box whenever the first input box is changed. I attempted to achieve this using this code snippet. However, I encountered an issue where the synchronization on ...

Can a div with float: left; be centered?

Currently, I am attempting to create a dock (similar to the iOS dock) for my website. Below is the full code that I have implemented: function addPrevClass(e) { var target = e.target; if (target.getAttribute('src')) { // check if it is img ...

A sleek Javascript gallery similar to fancybox

I'm currently working on creating my own custom image gallery, inspired by fancybox. To view the progress so far, please visit: I've encountered some issues with the fade effects of #gallery. Sometimes the background (#gallery) fades out before ...

What steps do I need to take to link my form with Ajax and successfully submit it?

Here is my HTML code: {% extends 'base.html' %} {% block content %} <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Create a Recipe ...

In Reactjs, you can prevent users from selecting future dates and times by modifying the KeyboardDateTimePicker component

I am currently using the Material UI KeyboardDateTimePicker component and have successfully disabled future dates with the disabledFuture parameter. However, I am now looking for a way to disable future times as well. Any suggestions or solutions would b ...

Having trouble getting the sorting/search function to work with a click event to display content. It seems to only work with a single item - possibly an issue with the

Creating a function that involves multiple boxes with a search function. The search function is working for the most part, but when clicking on a result, certain content should display. function filterFunction() { var input, filter, ul, li, a, i; ...