spgeise
spgeise

Reputation: 73

Wait for user response to geolocation prompt, then submit form

I have a button that users can click to use their location to find places nearby. How can I write the if/else statements to prompt the user to allow access to their location, wait for a response, then either submit the form or cancel out if they deny it?


<button id="submit_latlng" class="btn btn-secondary my-2 my-sm-0" type="submit">Use Current Location</button>

$('#submit_latlng').click(function() {
        getLocation(),
        $('#geo-loc-form').submit()
    })

    function getLocation(){
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                getPosition,
                positionError
            )
        }

        function getPosition(position) {
            document.getElementById('user_lat').value = position.coords.latitude;
            document.getElementById('user_lng').value = position.coords.longitude;
        }

        function positionError(error) {
            if (error.PERMISSION_DENIED) alert('Location services are off. Please enable location services, or use zip code search.');
                showError('Geolocation is not enabled.');
        }

    };

Upvotes: 0

Views: 1657

Answers (2)

spgeise
spgeise

Reputation: 73

I got it working with the following:


$('#submit_latlng').click(function() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                getPosition,
                positionError
            )
        }

        function getPosition(position) {
            document.getElementById('user_lat').value = position.coords.latitude;
            document.getElementById('user_lng').value = position.coords.longitude;
            $('#geo-loc-form').submit();
        }

        function positionError(error) {
            if (error.PERMISSION_DENIED) alert('Location services are off. Please enable location services, or use zip code search.');
                showError('Geolocation is not enabled.');
        }

    });

Upvotes: 0

Musevarg
Musevarg

Reputation: 181

This is the code I use. The user will be prompted by its web browser like this:

enter image description here

The first block is what you do if the user grants permission, and the second block function(error) is what you do if the user denies permission.

function getCoordinates()
{
  navigator.geolocation.getCurrentPosition(function(location) {
    var lat = location.coords.latitude;
    var lng = location.coords.longitude;
    console.log("Location permission granted");
    console.log("lat: " + lat + " - lng: " + lng);
  },
  function(error) {
    console.log("Location permission denied");
  });
}

Upvotes: 1

Related Questions