-1

I am trying to read some json format rest-api which is in my local host and then show their points on my google map, but there is a problem because I cannot get the latitude and longitude out of the getJSON block, I am new in JavaScript and rest-api. please help me and feel free to ask any question, BTW this is my code:

<script>
var b=true;
var lon=0.0;
var lat=0.0;
var center=null;
function myMap() {

$.getJSON('http://localhost:4567/game-net/name/megafun', function(data) {

    console.log(data);
    lat+=data[0].lattitude;
    lon+=data[0].longtitude;
    console.log(lat);
    console.log(lon);
    center= new google.maps.LatLng(lat,lon);
    console.log(center);
});
console.log(lat);//this is 0 and if I dont initialize by zero will be undefined
console.log(center);
var myCenter = new google.maps.LatLng(35.741635,51.448145);
var mapCanvas = document.getElementById("map");
var mapOptions = {center: myCenter, zoom: 15};
var map = new google.maps.Map(mapCanvas, mapOptions);
....

1 Answers1

0

Your problem is that the code in the callback is executed after the code where you work with google maps. $.ajax is an asynchronous operation, which means that it starts, but does not finish yet by the time console.log and further operations launch. Look at the following example:

setTimeout(function() {
  console.log("foo");
}, 1000);
console.log("bar");

In this snippet,

1.The timer is set 2. Further code runs, and "bar", is loged 3. Callback fires, and "foo" is loged.

In your case,

  1. Client starts connecting to the server
  2. Some data are loged into console, all the google maps code is run
  3. Only after that, the response from server is delivered.

So the simplest solution is just to put the rest of the code into the callback function.

But overusing callbacks can make your code ugly and lead to callback hell, so there are some alternatives in javascript to do it in a more beautiful way, but they can seem a bit sophisticated at the first glance. Please don’t hesitate to ask if you need any additional information.

You can use async functions instead of callbacks. Your code will still be asynchronous but it will look as if it were synchronous and will be more readable. First, define your function as async: async function myMap() {…}.

Second, use fetch api instead of $.ajax, and use the await keyword.

var unparsedData = await fetch(“your url here”);  // the engine will stop execution here and will wait for the server to respond
var data = JSON.parse(data);
console.log(data); // your data is now here

Some links:

Here you can find an explanation of asynchrony in javascript, some examples of callback hell and some info about promises.

Here comes a very good guide about Promises and async-await.

Kit Isaev
  • 680
  • 8
  • 19