0

I got a java script function and I want it to auto start but it wont.I've try the on load command and other stuff but it wont work here is the code in html .I just have to type something here who knows what.

<!DOCTYPE html>
<html>
<body onload="getlocation()">
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<script>
getlocation()
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }

function showPosition(position)
  {
  var lat=position.coords.latitude
  var lon=position.coords.longitude;
  var latlon_url="http://example.com/latlon.php?lat="+lat+"&lon="+lon;
  window.location=latlon_url;
  }

function showError(error)
  {
  switch(error.code) 
    {
    case error.PERMISSION_DENIED:
      x.innerHTML="User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML="The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML="An unknown error occurred."
      break;
    }
  }
</script>
</body>
</html>
Jay
  • 1,303
  • 3
  • 16
  • 39

6 Answers6

0

Note here getlocation() and getLocation() will be different

move getlocation() all the way down before closing script tag and change it to getLocation() or change body tag to <body onload="getLocation()">

Hamed Ali Khan
  • 1,086
  • 3
  • 21
  • 28
0

Javascript is case sensitive, so if you've called your function getLocation you should call it via getLocation() not all lowercase getlocation().

Edit: It doesn't matter where you call getLocation(). It's hoisted to the top, no need to move it further down.

Marc Dix
  • 39
  • 3
0

you also seem to be depending on the DOM with this line

var x=document.getElementById("demo")

so I would wrap the whole thing on a window.onload function

delete the getlocation() at the top because it got incorrect causing for the Location,

then go a head and call that from inside the window.onload when the DOM loads like so

window.onload = function () { getLocation(); }

Abraham Adam
  • 605
  • 1
  • 5
  • 14
0

javascript is case sensitive

getLocation() and getlocation() are different

try

<body onload="getLocation()">

or

<script>
getLocation();
<script>
Govind Singh
  • 14,083
  • 12
  • 58
  • 94
0

getlocation() not equal getLocation()

JavaScript is Case Sensitive.

7th line is unnecessary.

bedna
  • 920
  • 9
  • 20
0

These solutions will work:

    <body onload="script();">

or

     document.onload = function ...

or even

     window.onload = function ...
Ashouri
  • 869
  • 4
  • 19