2

What I am trying to do is find a user's location using html5 geolocation and store the latitude and longitude coordinates into an array for further use with google maps and sql statements. When I try putting them into the array and writing it to the window, nothing shows up or it says it is undefined. The code below is just a way to show me whether or not it is being put into the array. Thanks in advance!

<script>
var array = [];
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}

function showPosition(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;
    array.push(lat, lon);
}

document.write(array);
</script>
2
  • geocoding is asynchronous...you have to wait for the data to be returned and consume it in the callback. Also you never call getLocation() Commented May 23, 2015 at 0:34
  • Yes, I'm still looking for a solution of this too. Commented Jul 8, 2021 at 11:28

2 Answers 2

3

It is easy to manage aSynchronous function. You just need to put all your code into another function, and then call that function inside the success portion.

//Here is what you were trying to do

WRONG

(This will not work because it will execute the alert and "other cool stuff" code before getCurrentPosition has finished.)*

var array = [];
navigator.geolocation.getCurrentPosition(function(position) {
   var lat = position.coords.latitude;
   var lon = position.coords.longitude;
   array.push(lat, lon);   
});

alert(array); 
/* All of the other cool
stuff you are going to do
with the array /*

RIGHT

var array = [];
navigator.geolocation.getCurrentPosition(function(position) {
   var lat = position.coords.latitude;
   var lon = position.coords.longitude;
   array.push(lat, lon); 
   locationCode()  
});

function locationCode() {
   alert(array); 
   /* All of the other cool
      stuff you are going to do
      with the array /*
}
Sign up to request clarification or add additional context in comments.

4 Comments

Can I not access the array elements outside of the function?
aSynchronous processes take some getting used to. When JavaScript runs "getCurrentPosition()" it runs it in the background, and immediately moves on to the next line of code in your script. Your alert was returning nothing because it always executed before getCurrentPosition() was done loading up the array. By putting alert(array) where we did, it is inside the success function, so it will only run after getCurrentPosition is done, and the array has been populated.
This doesn't help me at all. I want to be able to access the elements in the array when I use the array outside of the function. Do you know of a way I can do that?
Hi The_Perfect_Username; I have updated my example to show you how you can still access the elements in the array, you just have to put all of your code into function so that it doesn't execute until AFTER the success of getCurrentPosition(). I hope that helps. Please upvote if this was useful.
0

This is a simple script I wrote that does pretty much what you're looking for.

<!DOCTYPE html>
<html>
<head>

    <title>Geolocation - Presented in HTML5</title>

    <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
    <script>
    navigator.geolocation.getCurrentPosition( 
        function(position) {

         function handle_errors(error)  
         {  
             switch(error.code)  
             {  
                 case error.PERMISSION_DENIED: document.getElementById("status").innerHTML = "you did not share geolocation data";  
                 break;  

                 case error.POSITION_UNAVAILABLE: document.getElementById("status").innerHTML = "I could not detect current your position";  
                 break;  

                 case error.TIMEOUT: document.getElementById("status").innerHTML = "your browser has timed out";  
                 break;  

                 default: document.getElementById("status").innerHTML = "an unknown error has occurred.";  
                 break;  
             }  
         }  

            var lat = position.coords.latitude;
            var lon = position.coords.longitude;
            var accuracy = position.coords.accuracy;
            var heading = position.coords.heading;
            var alt = position.coords.altitude;
            var altAcc = position.coords.altitudeAccuracy;
            var speed = position.coords.speed;

            document.getElementById("lat").innerHTML = "Latitude: <b>" + lat + "</b><br/>";
            document.getElementById("lon").innerHTML = "Longitude: <b>" + lon + "</b><br/>";

            document.getElementById("heading").innerHTML = "Heading: <b>" + heading + "</b> degrees clockwise from true North.<br/>";

            document.getElementById("accuracy").innerHTML = "Accuracy: I am <b>" + (accuracy * 3) + "</b> feet away from you.<br/>";

            document.getElementById("alt").innerHTML = "Sea Level: <b>" + alt + "</b> meters. <br/>";

            document.getElementById("altAcc").innerHTML = "Sea Level Accuracy: <b>" + altAcc + "</b> meters. <br/>";

            document.getElementById("speed").innerHTML = "Windspeed: <b>" + speed + "</b> meters/second.<br/>";

            document.getElementById("status").innerHTML = "";

            success(position);
        }
    );
    </script>

    <script>
    var map; // Define a global to hold the map object
    function success(position)
    {
         // Define the coordinates as a Google Maps LatLng Object
         var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

         // Prepare the map options
         var mapOptions = {
                        zoom: 20,
                        center: coords,
                        mapTypeControl: true,
                        navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
                        mapTypeId: google.maps.MapTypeId.SATELLITE 
                };
         // Create the map, and place it in the map_canvas div
         map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

         // Place the initial marker
         var marker = new google.maps.Marker({
                        position: coords,
                        map: map,
                        title: "Your current location!"
                });
    }
    </script>
</head>
<body>

<div style="font-family: Verdana, Arial; font-size: 12px; color: black;">
    <div id="lat">Latitude:</div>
    <div id="lon">Longitude:</div>
    <div id="heading">Heading:</div>
    <div id="accuracy">Accuracy:</div>
    <div id="alt">Sea Level:</div>
    <div id="altAcc">Sea Level Accuracy:</div>
    <div id="speed">Windspeed:</div>
    <div id="status"></div>
</div>

<br/><br/>

<div id="map_canvas" 
    style="
        width: 600px; 
        height: 400px; 
        border-right: 
        1px solid #666666; 
        border-bottom: 1px solid #666666; 
        border-top: 1px solid #AAAAAA; 
        border-left: 1px solid #AAAAAA; 
        margin: 20px;
    ">
</div>

</body>
</html>

1 Comment

That's not exactly what I'm looking for at all. I want to be able to put the latitude and longitude coordinates into an array and be able to access the array elements outside of the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.