-1

任何人都可以通过单击按钮帮助获取我当前的经度和纬度,并在 HTML 中的两个单独的输入表单上显示。下面是我的表格的样子,点击“获取”按钮,它将获得我当前的 LNG 和 LAT,然后显示在表格 1 和 2 上。




<form>  


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


<script>
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 = long;

        // 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>



4

1 回答 1

0

这可以使用一些简单的 JavaScript 来完成:

/* Add an onsubmit method to your form */
<form onsubmit="onFormSubmit()">
/*...*/
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 = long;

    // 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');
    }
}
于 2020-12-06T05:05:45.913 回答