How do I make a function only cast when a previous function has finished its job?
<p>I'm trying to use some functions to calculate and show the distance of only the markers within a certain distance from their position, but the function is being cast as soon as the page loads so it's using an incorrect value</p>

<p>Here is my function for generating markers from the database:</p>

<pre><code>&lt;?php while($stmt -&gt; fetch()) { ?&gt;
var longi = "&lt;?php echo $gLongitude; ?&gt;";
var lati = "&lt;?php echo $gLatitude; ?&gt;";
var title = "&lt;?php echo $gTitle; ?&gt;";
createMarker(lati, longi, title);
&lt;?php } $stmt -&gt; close(); $mysqli -&gt; close();?&gt;
</code></pre>

<p>Which then calls createMarker</p>

<pre><code>function createMarker(lati, longi, title) {
    var latLongMarker = new google.maps.LatLng(lati, longi);
    marker = new google.maps.Marker({
        position: latLongMarker,
        map: map,
        title: title
    });
    arrMarker.push(marker);
    marker.setMap(null);
    setMarker(latLongMarker);
}
</code></pre>

<p>Which then calls setmarker</p>

<pre><code>function setMarker(position) {
    console.log(arrMarker.value);
    for (var i = 0; i &lt; arrMarker.length; i++) {
        var latLong = arrMarker[i].getPosition();
        distance = google.maps.geometry.spherical.computeDistanceBetween(latLong, position);
        if (distance &lt; 4000) {
            addMarker(arrMarker[i].getPosition());
        }
    }
}
</code></pre>

<p>The problem is it keeps getting called before the geolocation is set using: </p>

<pre><code>function locateMe() {
if (navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
            initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
            map.setCenter(initialLocation);
            map.setZoom(15);
            setMarkerPosition(position.coords.latitude,position.coords.longitude);
        }, function() {
            handleNoGeolocation(browserSupportFlag);
        });
    }
}
</code></pre>
