NANG
NANG

Reputation: 21

How can i approximate latitude and longtitude in html?

How can i approximate latitude and longitude in html?
I want 4 decimal places and I want it that circled in the picture to hidden picture.jpg
Thank you very much.

This is a code

<!DOCTYPE html>
<html>

<body>

  <p>Click the button to get your coordinates.</p>

  <button onclick="getLocation()">Try It</button>

  <p id="demo"></p>
  <input type="text" id="lat" name="lat">
  <input type="text" id="lon" name="lon">

  <script>
    var x = document.getElementById("demo");

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    }

    function showPosition(position) {
      x.innerHTML = "Latitude: " + position.coords.latitude +
        "<br>Longitude: " + position.coords.longitude;
      $("#lat").val(position.coords.latitude);
      $("#lon").val(position.coords.longitude);
    }
  </script>
  <script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
  <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</body>

</html>

Upvotes: 2

Views: 683

Answers (2)

Fergus
Fergus

Reputation: 2982

Use the parseFloat() function and toFixed() method together

  • toFixed(4) method to format the latitude and longitude to 4 decimal places.

  • parseFloat() global function to convert the result back to a number (since toFixed() returns a string)

Like this:

let latitude = 52.12345678;
let longitude = -0.98765432;

let shortenedLatitude = parseFloat(latitude.toFixed(4));
let shortenedLongitude = parseFloat(longitude.toFixed(4));

console.log(shortenedLatitude);  // Outputs: 52.12346
console.log(shortenedLongitude); // Outputs: -0.98765

Upvotes: 0

Andrew Sklyarevsky
Andrew Sklyarevsky

Reputation: 2135

If the aim is to format the number as a string with a given precision then use the toFixed function, e.g.

var numberOfDecimals = 4;
var latitude = position.coords.latitude.toFixed(numberOfDecimals);
var longitude = position.coords.longitude.toFixed(numberOfDecimals);

If the intention is to limit the precision of the original number, then the rounding might be used:

var rounded = Math.round(value * 10000) / 10000; // leaves only 4 digits    

Upvotes: 1

Related Questions