Ashu
Ashu

Reputation: 81

Unable to redirect the output in another page(HTML,Javascript)

I want to find the latitude and longitude of current location and print the same on another page on button click. Though i am successful in getting the latitude and longitude but unable to print/redirect on another page.

can someone please help. please find the code below:

<!DOCTYPE html>
<html>
<head>
<script>
<p id="demo"></p>
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;
}
</script> 
</head>

<body>
<h2 >Geo-Logical Application</h2><br>
<p>Click the button to get Longitude and Latitude for your current position.</p><br>

<form action="Listing.html">
<button type="submit" onclick="getLocation()">Submit</button>
</form>

</body>
</html>

I want to redirect the output to listing page. thanks

Upvotes: 2

Views: 162

Answers (2)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93353

  • Use window.location to redirect to another page &
  • pass event to getLocation to stop default submission :

Modify as following :

function getLocation(event) {
     event.preventDefault();
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function(p){
               showPosition(p);
                // 
               window.location="Listing.html?lat="+p.coords.latitude+"&lgt="+p.coords.longitude; 
         });
    } else { 
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}

And HTML becomes :

<form action="Listing.html">
<button type="submit" onclick="getLocation(event)">Submit</button>
</form>

If your page handles GET parameters :

window.location="Listing.html?lat="+p.coords.latitude+"&lgt="+p.coords.longitude; 

else, use sessionStorage to have stateful application :

sessionStorage.setItem('POS',JSON.stringify(position.coords)) and in Listing.html , get it by : JSON.parse(sessionStorage.getItem('POS'))

Upvotes: 2

alexm
alexm

Reputation: 51

First off, you should not have a p element in the script. It should be in the body. Also, your script tag should be at the end of the body because it has code that modifies the DOM. The showPosition(position) function should come before the getLocation() function because you use showPosition in getLocation.

Upvotes: 0

Related Questions