使用地理位置坐标填充字段

Fill fields with geolocation coordinates

本文关键字:填充 字段 坐标 地理位置      更新时间:2023-09-26

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

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

我哪里做错了?

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

小提琴

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