views:

364

answers:

3

I'm kind of a javascript noob, and I'm trying to use the new geolocation API in Firefox 3.5 to get an estimation of the user's coordinates and put that into a text box in a form. What I have doesn't seem to be working; it seems like the boxes are filled before the location is actually retreived. Here's what I have so far:

<html>
<head>
 <script type="text/javascript">
  var lati =0;
  var longi =0;
  function getPosition(position) 
  {
   lati = position.coords.latitude;
   longi = position.coords.longitude;
  }

  function writeLati(form)
  {
   if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(getPosition);
    lati = position.coords.latitude;
    longi = position.coords.longitude;
    form.latitude.value = lati;
    form.longitude.value = longi;
   } else {
    form.latitude.value = "3";
    form.longitude.value = "5";
    document.write("Your shitty browser can't do geolocation. Get Firefox 3.5.");
   }

  }



 </script>
</head>
<body onLoad="writeLati(locform)">



 <form name="locform" action="submit.php" method="post" >
 Latitude: <input type="text" name="latitude" value=""/>
 Longitude: <input type="text" name="longitude" value="" />
 Gender: <input type="radio" name="gender" value="Male" /> Male <input type="radio" name="gender" value="Female" checked="checked" /> Female
 <input type="submit"  />
 </form> 


</body>

A: 

this is not very practical - here is a javascript solution that is cross-browser and does exactly what you want to do, using 3rd party apis from yahoo etc.

http://icant.co.uk/geofill/index.php?demo=suggestion

Dimitar Christoff
A: 

Native Geolocation is a cool new feature of FF3.5, but for now a cross browser solution is to use the Google API

This has given me reasonable results when I've used it but be aware that the accuracy will vary quite a lot be region, if your doing this it's nice to give your users a map so that they can refine the automatically generated position.

edeverett
+1  A: 

The form fields are getting filled early because getCurrentPosition is asynchronous. You want to fill the form fields in the callback function (at which point position will actually be filled with the data), something more like this:

function getPosition(position) 
{
    lati = position.coords.latitude;
    longi = position.coords.longitude;
    form.latitude.value = lati;
    form.longitude.value = longi;
}

Of course, you should add some error handling because the existence of navigator.geolocation isn't a guarantee that the location will be available. (Also, you should make it clear to users that you're not storing the location until the form is submitted -- a lot of people may be scared off by a form that fills in one's location automatically.)

npdoty