Search code examples
buttongeolocation

How to bring up GPS location only after clicking button?


How do I add the button properly so the GPS or geolocation is only activated after clicking on the button?

Here is my code:

    </p><button id="Btn1" onclick="getCurrentPosition();">Get Current Position </button></p>
    <script>
    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        console.log("navigator.geolocation works well");
    }

    // onSuccess Callback
    // This method accepts a Position object, which contains the
    // current GPS coordinates
    //
    function onSuccess (position) {
        alert('Latitude: '          + position.coords.latitude          + '\n' +
              'Longitude: '         + position.coords.longitude         + '\n' +
              'Altitude: '          + position.coords.altitude          + '\n' +
              'Accuracy: '          + position.coords.accuracy          + '\n' +
              'Altitude Accuracy: ' + position.coords.altitudeAccuracy  + '\n' +
              'Heading: '           + position.coords.heading           + '\n' +
              'Speed: '             + position.coords.speed             + '\n' +
              'Timestamp: '         + position.timestamp                + '\n');
    };

    function onError(error) {
        alert('code: '    + error.code    + '\n' +
              'message: ' + error.message + '\n');
    }

    navigator.geolocation.getCurrentPosition(onSuccess, onError);

    </script>

</body>

</html> 

Solution

  • Simply change your HTML to:

    <button id="Btn1">Get Current Position </button>
    

    And add this to your jQuery:

    $('#Btn1').click(function(){
            navigator.geolocation.getCurrentPosition(onSuccess, onError);
    });
    

    Here is a working demo: https://jsfiddle.net/xnd509f2/