Search code examples
javascriptjquerygeolocation

Fill fields with geolocation coordinates


I am trying to fill two fields with the result of a geolocation query. This is one of the first javascripts I have written.

Here is my current code: http://jsfiddle.net/spadez/aGupn/2/

$(function (getLocation) {

    var Geo = {};

    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(success, error);
    }

    //Get the latitude and the longitude;
    function success(position) {
        Geo.lat = position.coords.latitude;
        Geo.lng = position.coords.longitude;
        populateHeader(Geo.lat, Geo.lng);
    }

    function error() {
        console.log("Geocoder failed");
    }

    function populateHeader(lat, lng) {
        $('#lat').html(lat);
        $('#lng').html(lng);
    }

});

Where have I gone wrong?


Solution

  • It's because you are using input.html(...) instead of input.val(...). input.html(...) sets the innerHTML property of an element. However, that's not how you set the value of input element. You want to set the value attribute/property, therefore use input.val(...).

    FIDDLE

    $('#lat').val(lat);
    $('#lng').val(lng);