RobVH RobVH - 2 months ago 11
Javascript Question

How to retrieve a variable with coordinates from a JSON object

I'm trying to GET an object with a name and a location property. I need the coordinates of the location property to create a marker at that location. Running this code however results in Uncaught SyntaxError: Unexpected token o in JSON at position 1. I used JSON.stringify(data) in my PUT method.



function getLocation(){
var name = $("#username").val();
console.log('getLocation()');
if(name != ''){
$.ajax({
type: 'GET',
url: '../../' + name,
async: true,
success:function(data){
var oData = JSON.parse(data);
var marker = new L.marker(oData.location);
marker.addTo(map);
$("#username").val('');
},
error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Not found'); }
});
}
}




Answer

Could be your result is already JSON parsed the

  function getLocation(){
    var name = $("#username").val();
    console.log('getLocation()');
    if(name != ''){
      $.ajax({
        type: 'GET',
        url:  '../../' + name,
          async: true,
          success:function(data){
            var marker = new L.marker(data.location);
          marker.addTo(map);
            $("#username").val('');
          },
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Not found'); }
      });
    }
  }

or if you obtain an array

  function getLocation(){
    var name = $("#username").val();
    console.log('getLocation()');
    if(name != ''){
      $.ajax({
        type: 'GET',
        url:  '../../' + name,
          async: true,
          success:function(data){
            var marker = new L.marker(data[0].location);
          marker.addTo(map);
            $("#username").val('');
          },
        error: function(XMLHttpRequest, textStatus, errorThrown) { alert('Not found'); }
      });
    }