Get coords of map outside in variable

var t ;
var d = $.get(“http://maps.google.com/maps/api/geocode/json?address=Texas, United States”,function( data ) {
t=(data);
console.log(data);
});
console.log(t);
whenever i do console t. it shows undefined . i want/access coords out side of $.get().

Isn’t it just that you’re calling console.log(t) before the asynchronous function is done? If you look in the console, isn’t console.log(t) before console.log(data)?

how to get value outside or i do console outside that $.get. i want corrds(lat , long) coz i want to save in db. i have also another fields. i want it outside. how can i do ?

Just save it to the db inside the callback function. So instead of console.log(data), do myCollection.insert(data) :wink:

i have another fields also. so i want to save it with those fields. so thats why i want outside.
any suggestion

Either put all your code that depends on the result inside the callback function, or just don’t pass a callback function (that only works on the server though).

You could also pass the result to a ReactiveVar, ReactiveDict or Session, and set up a Tracker.autorun that checks that variable.

it can’t be possible that put code inside. if i dont use callback then how i will get coords? :frowning:

Oh right sorry, you’re using jQuery, not Meteor’s HTTP. Use that instead :wink:

when i do asyn: false it returns value. if async: true it will not give . help me how can i do with async. i saw http package it may perform same action like i used it.
function showGetResult( name )
{
var result = null;
var scriptUrl = “http://maps.google.com/maps/api/geocode/json?address=” + name;
$.ajax({
url: scriptUrl,
type: ‘get’,
dataType: ‘html’,
global: false,
async: false,
success: function(data) {
result = data;
}
});
return result;
}

I don’t know if this suits your needs but you should consider reading into using Async/Await or Promise patterns. There are tons of examples and it’s worth taking the time to learn the basics.

Here is an example I wrote for batching hundreds of addresses I call “Places” and send off to Google Maps APIs for geocode lng/lat values.

If your heavy into JS for your site, always consider breaking out your testing ideas in smaller chunks to speed up development. For me, I use Node for this so I can hammer out quick modules and test them before integrating them into my web site.

// Uses node-geocoder npm package
var NodeGeocoder = require('node-geocoder');

// Code below this line would go into your function which
// passes an argument and callback (data, cb) in my case.

var geocoder = NodeGeocoder(options);
var arrayOfPromises = [];

// Data is an array of objects
data.forEach(function (doc) {
      // Enum through each record checking for undefined geo.coordinates.
      // we only want to process lat/lng values that are outside of -180/180 bounds
      // or are null
      if (!validateCoordinates(doc.geo.coordinates)) {
        // console.log("Found null coordinates on doc._id);
        var a = doc.address;
        var place = a.street_number + ' ' +
                    a.street_name + ' ' +
                    a.city + ', ' + 
                    a.state + ' ' +
                    a.zip;
        
        // Create an array of geocoder Promise events.
        arrayOfPromises.push(
            geocoder.geocode(place, function(err, res) {
              // console.log("\nSending place data:", place);
              if (err) {
                console.error("Google rejection %s, address_primary: %s", err.message, doc._id);
                return doc;
              }
              
              if (res) {
                // Test we got a value back that can be resolved.
                if (res[0]) {
                  doc.geo = {
                    coordinates : [
                    res[0].longitude,
                    res[0].latitude
                  ]};
                  // console.log("doc.geo: %j, _id: %s", doc.geo, doc._id);
                  // MongoClient was used at the head of this function before the .forEach to connect to a database
                  // and get a reference to a collection
                  your_collection.update({
                      "address_primary" : doc._id
                    }, {
                      "$set" : {
                        "address_primary" : doc._id, 
                        "geo" : {
                          "coordinates" : [
                            res[0].longitude,
                            res[0].latitude
                          ]
                        }
                      }
                  }, {
                    "upsert" : true
                  });
                  counter++;
                  return doc;
                } else {
                  // Bad address
                  console.error("BAD place data: %s, address_primary: %s", place, doc._id);
                  doc.geo.coordinates = [0,0];
                  doc.place = place;
                  your_collection.update({
                    "address_primary" : doc._id
                  }, {
                    "$set" : {
                      "isBad" : true,
                      "place" : doc.place
                    }
                  }, {
                    "upsert" : true
                  });
                  badCounter++;
                  return doc;
                }
              }
          }).catch(() => {
            doc.geo.coordinates = [0,0];
            return doc;
          }) // end of geocoder
        ); // end of .push
      } // if/then .coordinates
    }); // end of .forEach

    // Finally, call the .all() function of the Promise object which
    // waits for all geocodes (Promises) to complete before firing 
    // Promise.all().then callback. 
    // When finished, send all data back in our cb().

    Promise.all(arrayOfPromises).then(() => {
      console.log('[%s] %s Coordinates corrected', helper.EXE_DATETIME({short:true}), formatNumber(counter, {precision: 0}));
      console.log('[%s] %s Coordinates flagged as BAD', helper.EXE_DATETIME({short:true}), formatNumber(badCounter, {precision: 0}));
      db.close();
      cb(data);
    });
  });

I hope that helps.
Cheers!

i used this but still i cant get it.
@datalifter see this example u will get it what i want . and how to use in meteor js using ur code and modify. i m not getting. thanks
@herteby plz check this code.
thanks
var result = null;
var scriptUrl = “http://maps.google.com/maps/api/geocode/json?address=Texas, United States”;
var num = $.ajax({
url: scriptUrl,
type: ‘get’,
dataType: ‘json’
});
$.when(num).done(function(data) {
console.log(data)
result=data;
// code to be executed after response received
});
console.log(result);

You mention you want to use in Meteor. Below is probably what you want.

Template.Main.onCreated(function(){
  var self = this;
  self.gdata = new ReactiveVar();
  var url = 'https://maps.google.com/maps/api/geocode/json?address=Texas,USA';
  $.when($.ajax({url: url, type: 'get', dataType: 'json'}))
  .done(function(data) {
    self.gdata.set(data);
  });
});

Template.Main.helpers({
  greturn: function() {
    if (Template.instance().gdata.get()) {
      var data = Template.instance().gdata.get().results[0].geometry.location;
      return EJSON.stringify(data, {indent: true});
    }
  }
});