1

I have created a function that tries to get lat long based on the address and after that, I want those to print on console

How to get values of coords.... am I doing it in the correct way? please help to understand it.

coords = getLocationCoords("Ambala,Haryana,India,134003");
console.log(coords)

function getLocationCoords(fa){

    var coords = [];

    $.get(location.protocol + '//nominatim.openstreetmap.org/search?format=json&q='+fa, function(data){

        coords['lat'] = JSON.parse(data[0].lat);
        coords['lon'] = JSON.parse(data[0].lon);

    });

    return coords;
}//getLocationCoords
rgoyal
  • 63
  • 2
  • 12
  • Please add a tag for the language – koen Mar 07 '20 at 20:09
  • Firstly you need to remove the `JSON.parse()` calls: `coords['lat'] = data[0].lat;` etc. Then your bigger issue is that the `$.get()` call is asynchronous so you need to change your code to work properly with the callback, or to implement promises. See the duplicates for more information – Rory McCrossan Mar 07 '20 at 20:34

1 Answers1

1

You cannot get the coords as "returned value", because there is nothing to return. That is, nothing to return until some handler is invoked, which could be 0.2 seconds later, or 3 seconds later. But if the handler returns it, you still won't be getting it since the assignment happened immediately. To solve this, you can also just make it a "promise", so that when the value is ready, you can then() it, and process the value, like follows:

getLocationCoords("Ambala,Haryana,India,134003")
  .then(data => {
    coords = data.map(loc =>
      ({
        lat: Number(loc.lat),
        lon: Number(loc.lon)
      })
    );
    console.log("GOT IT", coords);
  });

function getLocationCoords(fa) {
  return $.get(location.protocol + '//nominatim.openstreetmap.org/search?format=json&q=' + fa)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
eipione0
  • 51
  • 3
  • thanks eipione0 for your response... how to get value of coords after ".then " curly brace.... I need to place values of lat long in var map = L.map('map').setView([30.416667,77.166667], 3); – rgoyal Mar 07 '20 at 20:52
  • can you create another question... there shouldn't be two questions in one question and have it grow longer and longer – eipione0 Mar 07 '20 at 21:10