Is there a way to calculate the distance in kilometers between two sets of longitude and latitude in an Android application?

Explanation: This question may sound repetitive, but I have encountered some confusion while working on a live application. The JSON data contains longitude and latitude values which I need to compare with the current coordinates. Despite attempting various methods, I haven't achieved the desired outcome.

I aim to determine whether the user's current location (longitude and latitude) is within a five-kilometer radius of the coordinates provided in the JSON. If the user is outside this range (more than five kilometers), a message should be displayed indicating that the user is out of range.

Here is the code snippet for obtaining longitude and latitude:

public class HomeFragment extends Fragment implements ConnectionCallbacks, OnConnectionFailedListener,LocationListener{
    // Code here

JSON RESPONSE: https://i.stack.imgur.com/weRjF.png

In the above code block, particularly in the `getUcgCallApi()` method, I attempted to compare old and current longitude and latitude values without success.

Your assistance in resolving this issue would be greatly appreciated.

Thank you in advance.

Answer №1

To find the distance between two sets of latitude and longitude coordinates, you can use the following code snippet:

float[] results = new float[1];
Location.distanceBetween(startLatitude, startLongitude, endLatitude, endLongitude, results); 

The computed distance is then accessible at `results[0]`. If `results` array has a length greater than 1, the initial bearing value will be stored in `results[1]`. Similarly, if the length is greater than 2, the final bearing value will be stored in `results[2]`.

Answer №2

don't miss out on this helpful resource:

Calculate distance in meters when longitude and latitude are known in Java

public static float calculateDistance(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }

Use the method like this:

float meter= calculateDistance(LOCATION_LATITUDE1,LOCATION_LONGITUDE2,LOCATION_LATITUDE2,LOCATION_LONGITUDE2);


final float kilometer=meter/1000;

You can easily convert the distance from meters to kilometers.

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

Troubles encountered while parsing nested JSON objects with a streaming parser

I'm currently using the code provided in this helpful resource for parsing my JSON: Although it successfully handles most of the JSON data I have, it encounters issues when a JSON object is directly nested as a child within another one. To illustrat ...

Cricket score update features on the client side

Looking for assistance with client-side code development! I am currently working on an Android application using Ionic that involves live cricket scores. I have purchased a cricket API and understand how to connect to it using Node.js on the server side. ...

Fill a dropdown menu with options from a JSON object, arranging them in ascending order

I have a JSON hash that I am using to populate a combo box with the following code: $.each(json_hash, function(key, value) { $("#select").append("<option value='" + key + "'>" + value + "</option>"); }); The functionality w ...

Converting Basic JSON Data into an SQL SELECT Query

Presented is the subsequent JSON data: DECLARE @json NVARCHAR(MAX) SET @json = N'[ {"@odata.context":"http://www.example.com","value":[ {"financialmovements_ID":1,"Data":"2020-02-10T00:00:00Z","ES":"E","Descri\u00e7\u00e3o":"FIV-005 3& ...

What is the best way to send a JSON object in Vue.js?

<template> <div id="app"> <div id="bee-plugin-container"></div> </div> </template> <script> // import axios from "axios"; // import Bee from "@mailupinc/bee-plugin"; import $ from 'jquery' ...

What could be the reason for Express not setting the JSON content type?

I have utilized Express on numerous occasions in the past, and I do not recall encountering this particular issue before. It seems like there might be a mistake on my end, but I am struggling to identify what exactly that could be. My objective is quite s ...

Dynamic JSON property addition in C# at runtime

Below is an example of my JSON structure: [ { "id": "test.txt", "fields": { "_str.application": [ "Text File" ], "_str.body": [ "asdsadasd" ], "_str.mimetype": [ "text/plain" ] } } ] Is there a way to dynamically add new ...

Jquery Ajax failing to retrieve a response

Here's the jQuery script I am using to fetch data from my server: $(".login_button").click(function () { var username = $(".username").val(); var userkey = $(".userkey").val(); $.ajax({ type: "GET", url: "http://192.168.0. ...

Having trouble with the JSON Parse function in my code, but it seems to be functioning correctly

As a beginner programmer, I am currently working on developing an application using Json. In order to accomplish this, I have created a Json parser class and incorporated the following code into my main activity: JSONObject json = ...

jsoup - locate element and delete it along with the element preceding it

In my Android app, I am working on extracting data from a stock market historical prices table. However, there are certain rows in the table that need to be removed for clarity. Specifically, I am trying to remove a row in the third tr. I have managed to r ...

Retrieve the value of an AngularJS expression and display it in a window alert using AngularJS

Hey there, I am in the process of trying to display the value of an expression using AngularJs As a beginner in angular, I am working on figuring out how to retrieve the value of the expression either with an alert or in the console. I'm utilizing A ...

What is the reason dynamic colors cannot be applied in XML?

I have been trying to incorporate dynamic color support into my XML+Compose app. While I have successfully implemented dynamic colors in Compose, it doesn't seem to work for the XML screen. What could be the issue here? This is a snippet from my frag ...

Exploring and organizing JSON data with PostgreSQL

I have a database table named api_details where I store a JSON value in the column raw_data. Now, I want to generate a report based on this JSON data with an expected outcome like the following: action_name sent_timestamp Sent ...

Spring JSON Neo4j is a powerful combination for building robust

Imagine a scenario where there is a Person node with 3 hobbies: Peter -> Hockey Peter -> Soccer Peter -> Basketball When querying the data from a string using Neo4jRepository: interface PersonRepository extends Neo4jRepository<Person, Long>{ ...

SCRIPT438: The operation failed because the object does not have the ability to use the 'forEach' property or method

Issue with IE8: Property or method 'forEach' not supported $('.tabs').tabs(); $('#search-consumables [data-ajax-call]').change(function() { var $this = $(this), settings = $this.data(), $target = $(setti ...

Ways to insert user data into a hidden input field

I am facing an issue with the input field on my website. Users can enter their desired input, and this data is copied into a hidden input field. However, the problem arises when new data replaces the old data. This is where I copy all the data: $('# ...

Seeking assistance with dilemmas related to jQuery (specifically kendo), .NET Web Service (asmx), and Json

After conducting extensive research on the subject, I was unable to find any satisfactory answers or complete examples. Since I have limited experience with jquery, I am in search of a straightforward sample that demonstrates what I'm trying to achiev ...

I am having trouble authorizing a GET request with fetch

I've been attempting to utilize fetch in the browser, but it's not cooperating. Here's what I tried: fetch('https://api-2sizcg3ipa-uc.a.run.app/fats', { headers: {'Authorization': 'Basic ' + btoa('username ...

"Upon parsing the JSON data, the decoder yielded a null

This question has been asked many times before, but I am still struggling to get it working. I have a JSON and when I dump the $TenentsAccessible output, it looks like this: string(71) "[{`TenantID`:`test.com`,`Name`:`12thdoor`}]" I need to extract the ...

Query in JSONPath to retrieve elements in an array depending on a specified key's value

I am working with a JSON Array that contains multiple JSON objects: [ { "s3_uri":"s3://fake-s3-bucket/fact_table/fact_table.csv", "dataset":"fact_table" }, { "s3_uri":"s3://f ...