簡體   English   中英

如何獲取我當前位置的經度和緯度並顯示在兩個單獨的 HTML 表格上

[英]How to get longitude and latitude of my current location and display on two separate HTML form

任何人都可以通過單擊按鈕來幫助獲取我當前的經度和緯度,並在 HTML 中的兩個單獨的輸入表單上顯示。 下面是我的表單的樣子,點擊“獲取”按鈕,它將獲得我當前的 LNG 和 LAT,然后顯示在 forms 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>



這可以使用一些簡單的 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');
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM