简体   繁体   中英

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

Can anyone help with getting my current longitude and latitude on-click of a button, and display on two separate input form in HTML. Below is what my form will be like and on click of the "Get" button it will get my current LNG and LAT then display on forms 1 and 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>



This can be done using some simple 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');
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM