HTML 中的输入表单中未显示 LAT 和 LNG

LAT and LNG not showing on input form in HTML

我正在使用以下代码获取我当前位置的 LAT 和 LNG 以将其显示在输入表单中,但出于某种原因,它没有按需要显示我的 LAT 和 LNG,而是会显示 LAT 和 LNG瞬间消失。我试图更改我的浏览器权限以允许位置,但仍然在一瞬间显示并消失。谁能帮忙?下面是我的代码:




<form>  

<button onclick="onFormSubmit()">GET CURRENT LOCATION</button>



<script type="text/javascript">
function onGeoSuccess (position) {
        var lat = position.coords.latitude;
        var lng = position.coords.longitude;

        // NEXT 2 LINES WILL SET VALUE OF RESPECTIVE INPUTS
        document.getElementById('lat').value = lat;
        document.getElementById('lng').value = lng;

        // MAKE API CALL HERE, OR ANY OTHER NEXT STEPS
    }

    function onGeoError (err) {
        console.error("Error while trying to get position", err);
    }

    function onFormSubmit () {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(onGeoSuccess, onGeoError);
        } else {
            alert('GeoLocation not supported or not allowed');
        }
    }</script>

              <div class="form-group">
                <input type="text" name="lat" class="form-control" id="lat" placeholder="Your Latitude" data-msg="Please enter your latitude">
                <div class="validate"></div>
              </div>

<div class="form-group">
                <input type="text" name="lng" class="form-control" id="lng" placeholder="Your Longitude" data-msg="Please enter your Longitude">
                <div class="validate"></div>
              </div>

              <div class="form-group">
                <input type="text" name="subject" class="form-control" id="contact-subject" placeholder="Subject" data-rule="minlen:4" data-msg="Please enter at least 8 chars of subject">
                <div class="validate"></div>
              </div>


</form>



我只想在输入表单上显示 LAT 和 LNG 以及每个 ID,但我不知道哪里做错了。它没有按要求显示。

所以我追溯我的代码并排查错误,发现这仅仅是因为我使用了 <button onclick="onFormSubmit()">GET CURRENT LOCATION</button> 而不是 <button onclick=" return onFormSubmit()">GET CURRENT LOCATION</button>。当我出于某种原因只在 onclick 上调用 onFormSubmit 时,它会出现一瞬间然后消失,但是当我在 onclick 上调用 return onFormSubmit() 时,一切正常。