Uncaught TypeError: Cannot read property '0' of null - leaflet

若如初见. 提交于 2021-02-08 10:35:16

问题


I'm trying update my leaflet map via JS + AJAX, but leaflet return me an error Uncaught TypeError: Cannot read property '0' of null on leaflet.js:5

I have function, which get data from server, everything works, when I call function getData, I get data and function printRoute writes data to "test" element, but L.polyline([... still returns error. Data ( output of xhttp.responseText ) are in right format, which L.polyline needs ( [ 49.999319, 13.897081 ], [ 49.997681, 13.905933 ], ... , [ 49.996141, 13.913901 ], [ 49.994664, 13.921527 ] )

When I do it only on server, only with PHP, without AJAX, everything works fine. Please, do you have some hints?

function getData( url, cFunction, postedData ) {
  var xhttp;
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      cFunction( this );
    }
  };
  xhttp.open( "GET", url, true );
  xhttp.send();
}

function printRoute( xhttp ) {
  document.getElementById("test").innerHTML = xhttp.responseText;
  var route = L.polyline([ xhttp.responseText ], {color: 'red'} ).addTo(map);
} 

回答1:


The coordinates being past from the server are in array notation, however the xhttp.responseText property is actually a String type. The polyline function is looking for an array of arrays but gets past an array of a single string.

['[ 49.999319, 13.897081 ], [ 49.997681, 13.905933 ]']

instead of

[[ 49.999319, 13.897081 ], [ 49.997681, 13.905933 ]]

configure the server to return a proper json object to fix this.

using eval('[' + xhttp.responseText + ']') to convert your string into an array is not recomemeded as it creates a security vulnerabilitie in your code.



来源:https://stackoverflow.com/questions/55680201/uncaught-typeerror-cannot-read-property-0-of-null-leaflet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!