2

I am creating a Chrome extension that collects your geolocation when you click on it - syncing data so that it stores the past 20 longitude-latitude coordinates you were at. But the chrome.storage.sync.set seems to not be working!

    var locations = [];
//get past locations and put them into 'locations' array
    chrome.storage.sync.get("locations", function(data){
        console.log("Getting Locations");
        var index;
        for (index = 0; index < data.length; ++index) {
            locations.unshift(data);
        }
    });
//add current location to 'locations' array
    navigator.geolocation.getCurrentPosition(function(position) 
    {
        initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    });
    locations.unshift(initialLocation);

//sync locations to cloud
    var obj = {};
    obj["locations"] = locations;
    chrome.storage.sync.set(obj, function() {
        console.log("Location Saved");
        console.log(locations);
    });

So each time I run this code - it should (a) get past locations (b) add current location and (c) store it back in the cloud. But each time I run the program the 'locations' array stays size [1] aka nothing is getting get/set ! I've looked at a few other posts about this concerning the correctness of the arguments but I've checked mine and I believe they are sound.

What's happening?!? Can anybody shed some light on how to make this code work? Thanks so much to my Code Heroes :D

Steve H
  • 151
  • 1
  • 1
  • 6

1 Answers1

0

chrome.storage.sync.get is asynchronous as you can see it here

So, when you try to save the result in locations variable, the execution of the method as not finished.

chrome.storage.sync.get('locations', function(data){
    console.log("Getting Locations");
    console.log(data.locations); // The locations object.
    });

Please refer to this post.

Community
  • 1
  • 1
Coyolero
  • 2,353
  • 4
  • 25
  • 34