Discover how to measure the distance between two clickable points using OpenLayers 6 API

In my api.py file, I have defined some points like this:

(...)
@app.route('/api/pontos/', methods=['GET'])
def get_pontos():
    return jsonify({
        'pontos': [
            [-44.3001,-2.52001, 3, "name1"],
            [-44.309468, -2.509284, 4, "name2"],
            [-44.307802, -2.557744, 5, "name3"],
(...)

These points can be selected and their characteristics are displayed in the browser.

var selec = new ol.interaction.Select()
selec.getFeatures().on('add', function(e){

    var label = typeof (e.element.getProperties().text) != 'undefined' ? e.element.getProperties().text : ''
    if(label != ''){
        alert(e.element.getProperties().text)
    }

})

(...)

function loadPoints(){
    axios.get(`/api/pontos`)
        .then(function(response){
            if(response.status === 200){
                var coordsArray = response.data.pontos;

                coordsArray.map(coords =>{

                    var point = new ol.Feature({
                        geometry : new ol.geom.Point(ol.proj.fromLonLat(coords)), 
                        text : `Preco: ${coords[2]} reais, Bar:${coords[3]} `
                    });

                    point.setStyle(pointStyle);
                    vectorSource.addFeature(point)
                }); 

                //Fit nos pontos
                map.getView().fit(vectorSource.getExtent());
            }

        })
}

loadShape('ma')
loadPoints()

Now, I am interested in clicking on two points to calculate the distance between them and display it in the browser.

Despite researching documentation and other questions, I have not been able to find a solution that fits my specific issue.

Answer №1

Using the getDistance() function is a simple way to determine the distance between two sets of coordinates.

calculateDistance(toLonLat(first) , toLonLat(second));
function calculateDistance(src , dest ){
let finalmeasure = getDistance(src , dest);
//let finalmeasure = Math.round(line.getLength() * 100) / 100; //for rounding
console.log(finalmeasure); //in meters
}

Warm regards

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

Displaying all components simultaneously instead of displaying placeholders and awaiting image downloads

Is there a way to instruct the browser to load all images first before displaying the page, rather than rendering img elements and then loading the images afterwards? I am working with asp.net on the server side, but I believe the solution may involve DOM ...

Create a new URL using `window.URL.createObjectURL` and specify the filename to open the PDF

Is there a way to customize the filename in createObjectURL of the blob? Currently, it generates a URL like this: <URL>/bfefe410-8d9c-4883-86c5-d76c50a24a1d const data = window.URL.createObjectURL(newBlob); const pdfWindow = window.open(); pdfWindo ...

JSON Array Position Sequence

I have a system that takes input in the form of lines of text stored as an array, for example: array[123,556,"test",0,0]. By using val().split('\n'), I am able to add each new line to the array so that each line index is incremented by 1. He ...

Unable to successfully perform DELETE or UPDATE operations with Axios MySQL, encountering errors

I am currently working on a project that involves using Axios with Node.Js to perform a delete request in a MySQL table. However, I seem to be encountering an issue as I am not receiving any errors in the console despite having an error catch console.log s ...

Is there a way to skip the current page in an Ajax GET request?

As an example, I am currently viewing the /users page and when I send a request from that location, it directs me to /users/conversations/id instead of just conversations/id. How can this be adjusted? users.js $('.start-conversation').click(fun ...

I encountered an error in the console stating, "Uncaught ReferenceError: req is not defined," while trying to access req.query.id

Encountering the error 'Uncaught ReferenceError: req is not defined' when attempting to use req.query.id. Below is the content of my index.js file: const express = require("express"); const path = require("path"); const port = 8000; ...

Loading an external script is causing a total style overhaul on my website

Every time I load my page to check the remaining balance of a gift card (using a third-party script), it seems to mess up the styles that are already set on my website. Here is a snippet of the code causing the issue: <div id="main" class=&quo ...

When activating a bootstrap class button, I must ensure the reply-box remains hidden

let replyButton = document.getElementById('reply-button'); let cardBody = document.getElementById('card-body'); let responseBox = document.getElementById('reply-box'); let cancelButton = document.getElementById('btn btn-d ...

Tips for retrieving a URL from a prop in a VueJS for loop

I am facing an issue with accessing the URL in my props to open them. Currently, I can only open them by right-clicking and selecting 'open in new tab,' but I want them to open when clicked. How can I correctly reference the href prop from the @c ...

Error in Sequelize and Express JS: Cannot access undefined properties while attempting to read 'findAll'

I am currently facing an issue while working with Express JS and Sequelize in connection to a MSSQL database. The error message "Cannot read properties of undefined (reading 'findAll')" is blocking me from making any requests. Can anyone provide ...

How can I control the direction of a CSS change when hovering using JavaScript?

When you hover over the green section in the code snippet below, the height of the two red boxes will change. However, the height currently expands downwards. Is there a way to make the height expand upwards instead? CSS: .one{ position: absolute; ...

Is there a way to clear or reset the previous values set in addEventListener?

Imagine a scenario where you have an event calendar, and when you click on an event, a modal window pops up with various buttons. The issue here is that although the code works, when I click on different events, the values of previously clicked events are ...

"Which is better for handling form data: using $.ajax with hidden fields or PHP form

Creating a streamlined admin tool using PHP and JQuery to handle image data management is my current project. The main goal of this utility is to enable an admin to retrieve images from a database, view associated tags for each image, and add new tags as n ...

Is there a way to shade the entire webpage background in HTML?

Instead of affecting other DOM classes, I tried using another div but it doesn't darken the whole page. This means I have to manually modify each DOM class. Is there a way to overlay the entire document with a semi-transparent gray plane? ...

Is it possible to identify the beginning of a download using Selenium?

Currently, I am using Python and Selenium to download a large batch of files. To ensure that each file is successfully downloaded, I am implementing a basic time.sleep() function, but I want to enhance efficiency and guarantee the completion of each downlo ...

Switching on Closed Captions for HTML5 video while deactivating the standard video controls

I am facing two issues. Whenever I include the track tag in my video element, the default controller of the video pops up, which is causing conflicts with my custom controls. Secondly, I am unable to figure out how to turn closed captions on and off. Thi ...

Adding a modifier to multiple elements within an object

My document structure includes the following: { _id: ..., name: ..., keywords: { group_a: [1, 2, 5], group_b: [4, 7, 6] } } I've figured out how to add elements to one of the elements in the keywords object like this: db.coll.update ...

Angular JS plugin that locates image links within plain text and transforms them into HTML <img> tags using JavaScript

I am faced with a situation in which I need to show images if the chat messages contain image links, but currently I am only displaying the links as text. One idea I had was to check for the lastIndexOf('.') and extract the file extension to mat ...

Creating a unique function to map an array in VueJS specifically designed for table manipulation

I am currently working on displaying and sorting data in a bootstrap table within VueJS. My goal is to change the date format within an array retrieved from an API endpoint. The original date format is in "January 21, 2010" and I need it to be in "MM/DD/Y ...

AngularJS: Handling multiple asynchronous calls simultaneously in a function

In my AngularJS function, I need to make two asynchronous calls that are independent of each other. However, the function should only return when both calls have completed and the results are stored in the return variable. I have tried various solutions a ...