【问题标题】:Fill fields with geolocation coordinates使用地理位置坐标填充字段
【发布时间】:2013-09-08 13:41:32
【问题描述】:

我正在尝试用地理位置查询的结果填充两个字段。这是我写的第一个 javascripts。

这是我当前的代码: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);
    }

});

我哪里出错了?

【问题讨论】:

    标签: javascript jquery geolocation


    【解决方案1】:

    这是因为您使用的是input.html(...) 而不是input.val(...)input.html(...) 设置元素的innerHTML 属性。但是,这不是您设置输入元素值的方式。您想设置value 属性/属性,因此使用input.val(...)

    FIDDLE

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

    【讨论】:

    • 感谢您的帮助。有用!不过我只有一个问题,它似乎在我每次访问页面时都会自动填充字段,而不是等待我按下按钮。你能明白为什么会这样吗?
    • @Jimmy 是的,这是因为$ 函数会在文档准备好后立即执行作为参数传递的函数。
    • 如果我删除 $ 它不起作用。我只希望它在单击称为获取坐标的按钮时执行
    • 它不尊重最佳实践,因为一切都是全球性的,但这只是为了示例,看看这里jsfiddle.net/aGupn/6
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多