-1

So I've been researching this topic like crazy, and I get the same results each time, and I'm not really getting anymore answers that are becoming helpful. I understand what the idea of a callback function is, but perhaps I am implementing it wrong. So here's what I've got.

I'm working on a Google Maps task, I have everything else working correctly, it's just when they come to the page I would like their current location stored away in the 'start' variable at the top. It can be stored as an Object or an array, that doesn't make a difference.I'v been using an alert box to test my output, but I'm getting nowhere fast. I'll post my code below here.

//set global variables that will be used for the maps later on in the script
var pj; 
var tifton;
var nlv;
var direction;
var start ='default';

function initialize(){    
    pj = new google.maps.LatLng(41.048899, -95.822685); //map for pacific junction
    tifton = new google.maps.LatLng(31.417032, -83.498785); //map for tifton
    nlv = new google.maps.LatLng(36.228928, -115.112426); //map for north las vegas
    //set the directions for the user

    updateCoords(function(point){
        if(point){
            start = point.latitude;
        }
    });

    alert(start); //it will not stop showing default as the result

    drawMap(pj,"pj-map", "Pacific Junction, IA");
    drawMap(tifton, "tifton-map", "Tifton, GA");
    drawMap(nlv, "nlv-map", "North Las Vegas, NV")
}

function drawMap(coords, div, title){
    var opts = {
        zoom: 8,
        center: coords,
        panControl: false,
        zoomControl: false,
        scaleControl: false,
        scrollwheel: false,
        draggable: false,
        disableDoubleClickZoom: true
    }; //generate map options for each individual map

    var map = new google.maps.Map(document.getElementById(div), opts); //set the canvas that the map will be drawn to
    var marker = new google.maps.Marker({
        position: coords,
        title: title
    });
    marker.setMap(map);
}
function updateCoords(callback){
    navigator.geolocation.getCurrentPosition(function(position){
         var pos = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude
         };

        callback(pos);
    });
}

google.maps.event.addDomListener(window, 'load', initialize);

EDIT: In response to having this question marked as a duplication, I will add some more detail. The link to the question that was provided to me, did not assist me any further than I already was. All it did was re iterate was asynchronous and synchronous functions and processes were to me. I do not need any more of that.

What I'm looking for is a response that can help me break down the interior of this

function updateCoords(callback){
    navigator.geolocation.getCurrentPosition(function(position){
         var pos = {
            latitude: position.coords.latitude,
            longitude: position.coords.longitude
         };
         if()
        callback(pos);
    });
}

and why this

updateCoords(function(point){
    if(point){
        start = [ point.latitude, point.longitude];
    }
});

is completely missing the timing when it is called in the example code that I provided at the very start of this question. I know that the function 'updateCoords' is asynchronous, I do not need that repeated to me further. I read that entire response on the question that was linked to me, and again it provided me no new information. So to sum up my question and the bulk of my frustrations here:

  1. I have asynchronous and sychronous behaviors going on here.
  2. I am missing the timing at a specific point during the call of the function, I can not pinpoint it.
  3. I have tried several different examples that I have found including those that were in the question linked to me, results failed.
  4. Can someone help me identify what the errors is, where the timing of the functions is being missed, and why that occurs, and then assist me in indentifying a proper solution to that issue.
Mark Hill
  • 1,769
  • 2
  • 18
  • 33

2 Answers2

0

The geolocation function is asynchronous. You need to use the result in the callback function.

function initialize(){    
    pj = new google.maps.LatLng(41.048899, -95.822685); //map for pacific junction
    tifton = new google.maps.LatLng(31.417032, -83.498785); //map for tifton
    nlv = new google.maps.LatLng(36.228928, -115.112426); //map for north las vegas
    //set the directions for the user

    updateCoords(function(point){
        if(point){
            start = point.latitude;
            alert(start); //it will not stop showing default as the result

        }
    });
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • I'm aware that the function is asynchronous, but I want the result outside of the function. I know that it is possible to do that, did you even read what I was looking to do before you marked it? – Mark Hill Sep 22 '14 at 19:11
  • Does the answer above not answer your question? You can get the result outside of the function (in the start variable), but obviously, the value won't be set until the asynchronous callback returns, that would be a timing problem with your code (if you are expecting it to be available before it is). – geocodezip Sep 22 '14 at 20:17
  • It does not provide the answer I am looking for no. I'm already aware that the result you provided will occur, the problem with that is that it forces me to work with that updateCoords function. which is something that I can't do. I would like to set start as the page finishes loading, outside of the callback, and able to be used for global access. – Mark Hill Sep 22 '14 at 20:33
  • Unfortunately you can't do that (unless you put a hardcoded delay in your code to ensure that the callback has already run). The data is not available to your page/the browser until the callback runs. – geocodezip Sep 22 '14 at 20:39
  • there, that is an answer that helps me out. Would you hate me if I asked for an edit on your code, so that you could show me a small example of how you would do something like that? – Mark Hill Sep 22 '14 at 20:42
0

i'm student , i'm also gone through from this problem recently but found one easy way to tackle it with the help of promises in javascript.

JavaScript is asynchronous first we need to learn about a nature of javascript , when we want to change a value of global variable inside a callback function but because nature of javascript callbacks take some time to execute and javascript run your global synchronous code before callback (asynchronous code) and value of global scope variable remain same to initial value you assign to variable or undefined

learn with the help of example of simple callback

const fs = require("fs");

let outer_data = null;

fs.readFile("example.txt", { encoding: "utf-8" }, (error, data) => {
   if (error) console.log(error); ;

   outer_data = data;
});  

console.log(outer_data);

in above example we are trying to set a value of outer_data variable to data fetched from "example.txt" file in our example inside the callback of readLine() function but still result is null

Now solve problem using promises in javascript

approach is bind a asynchronous code (which take time to run) inside a promise and use async , await or .then to retrive a data

Read more about promises

what is Promise in js

how to use Promises

const fs = require("fs");

let outer_data;

let promise = new Promise((resolve, reject) => {
    fs.readFile("example.txt", { encoding: "utf-8" }, (error, data) => {
       if (error) reject(error.message);

       resolve(data);
    });
 });


 const getData = async () => {
    outer_data = await promise;
    console.log(outer_data);
 };

 getData();

another way to define and call a function at same time

(async ()=>{
   outer_data = await promise;

   console.log(outer_data);
})();