Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/matlab/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Google距离矩阵Api无法将距离设置为状态_Javascript_Reactjs_Google Maps Api 3 - Fatal编程技术网

Javascript Google距离矩阵Api无法将距离设置为状态

Javascript Google距离矩阵Api无法将距离设置为状态,javascript,reactjs,google-maps-api-3,Javascript,Reactjs,Google Maps Api 3,我有它的工作,它会记录到控制台的响应,但我不能设置距离的状态,我会把所有的代码放在下面 getDist(dest){ var self = this; var origin = this.state.location, destination = this.state.dest, service = new window.google.maps.DistanceMatrixService(); service.getDistanceMatrix( {

我有它的工作,它会记录到控制台的响应,但我不能设置距离的状态,我会把所有的代码放在下面

getDist(dest){
var self = this;
var origin = this.state.location,
    destination = this.state.dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      }, 
      this.callback
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        var dist = response.rows[0].elements[0].distance.text;
        return response;
    } else {
        alert("Error: " + status);
    }
  }
我试图在回调函数中设置状态,它说
setState({})
不是一个函数。我试着通过这样做来设置状态
this.setState({distFromLoc:self.callback})
,但这只是将回调函数代码设置为我不想要的状态,我的知识已经达到极限,与我一起工作的其他web开发人员对我们的逻辑毫无意义

我只需要能够设置状态2秒钟,因为我在一个大约36份工作的列表中循环,每次搜索后,它将检查该工作是否与搜索的人足够接近

提前谢谢-安迪

编辑1:我已经编辑了我的代码,它不再出错,但它仍然不允许我返回数据。你能告诉我我做错了什么吗

将添加调用它的类,因为它表示我不能使用。然后在函数上将函数转换为承诺函数

updateSearchResults(data) {
this.setState({
  searching: true,
});
var self = this;
var output = [];
console.log('Here we will search the db using user data for suitable jobs');
console.log('do some math to work out how many pagination we need for the amount of returned jobs and update the state accordingly');
data.forEach(item => {
  console.log('before');
  this.getDist(item.postcode).then(function (res){
    console.log('after');
    console.log(this.state.distFromLoc);
    if (this.state.location === '') {
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('1');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('2');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('3');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('4');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('5');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('6');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('7');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('8');
          output.push(item);
        }
      }
    } else if (this.state.distFromLoc <= this.state.distance) {
      console.log(this.state.distFromLoc);
      console.log(this.state.distance);
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('9');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('10');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('11');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('12');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('13');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('14');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('15');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('16');
          output.push(item);
        }
      }
    }
  })
  .catch(function (err){
    console.log(err);
  });
});
window.setTimeout(function() {
self.setState({
  dataToShow: output,
  searching: false,
  current: 1,
});
const dataLength = self.state.dataToShow.length
self.setState({
  amountOfJobs: dataLength
})}, 10000)
}

getDist(dest){
var self = this;
const wrappedCallback = (...args) => this.callback(...args);
var origin = this.state.location,
    destination = dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      }, wrappedCallback 
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        if (response.rows[0].elements[0].status === "ZERO_RESULTS"){

        } else if (response.rows[0].elements[0].status === "OK"){
          var dist = response.rows[0].elements[0].distance.text;
          this.setState({
            distFromLoc: dist
          })
        }
    } else {
        alert("Error: " + status);
    }
  }
updateSearchResults(数据){
这是我的国家({
搜索:是的,
});
var self=这个;
var输出=[];
log('在这里,我们将使用用户数据搜索数据库以找到合适的作业');
log('计算出返回作业数量需要多少分页,并相应地更新状态');
data.forEach(项=>{
console.log('before');
this.getDist(item.postcode).then(function(res){
console.log('after');
console.log(this.state.distFromLoc);
if(this.state.location===''){
如果(item.option=='partTime'&&this.state.partTime&&this.state.weekend){
if(item.title.toLowerCase().match(this.state.keywords.toLowerCase())!==null){
console.log('1');
输出推送(项目)
}else if(this.state.keywords===''){
console.log('2');
输出推送(项目);
}
}else if(item.option==='Weekends'&&this.state.weekend&&this.state.partTime){
if(item.title.toLowerCase().match(this.state.keywords.toLowerCase())!==null){
console.log('3');
输出推送(项目)
}else if(this.state.keywords===''){
console.log('4');
输出推送(项目);
}
}else if(item.option==='both'&&this.state.weekend&&this.state.partTime){
if(item.title.toLowerCase().match(this.state.keywords.toLowerCase())!==null){
控制台日志('5');
输出推送(项目)
}else if(this.state.keywords===''){
console.log('6');
输出推送(项目);
}
}否则如果(!this.state.weekend&!this.state.partTime){
if(item.title.toLowerCase().match(this.state.keywords.toLowerCase())!==null){
console.log('7');
输出推送(项目)
}else if(this.state.keywords===''){
console.log('8');
输出推送(项目);
}
}
}else if(this.state.distFromLoc this.callback(…args);
var origin=this.state.location,
目的地=目的地,
service=newwindow.google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
来源:[来源],
目的地:[目的地],
travelMode:window.google.maps.travelMode.DRIVING,
避免:错误,
避免:错误,
unitSystem:window.google.maps.unitSystem.IMPERIAL
},wrappedCallback
);
}
回调(响应、状态){
const self=这个;
如果(状态==“正常”){
控制台日志(响应);
var dest=response.destinationaddress[0];
if(response.rows[0]。elements[0]。status==“ZERO\u RESULTS”){
}else if(response.rows[0]。元素[0]。状态==“OK”){
var dist=response.rows[0].元素[0].距离.text;
这是我的国家({
distFromLoc:dist
})
}
}否则{
警报(“错误:+状态”);
}
}
我知道我做错了什么,我就是搞不清楚到底是什么


当前我遇到的错误是:无法读取未定义的属性“then”为什么我不能对函数作出承诺。

这是一个绑定问题,也是避免在javascript中使用类的主要原因之一。这里是您的问题所在:

updateSearchResults(data) {
this.setState({
  searching: true,
});
var self = this;
var output = [];
console.log('Here we will search the db using user data for suitable jobs');
console.log('do some math to work out how many pagination we need for the amount of returned jobs and update the state accordingly');
data.forEach(item => {
  console.log('before');
  this.getDist(item.postcode).then(function (res){
    console.log('after');
    console.log(this.state.distFromLoc);
    if (this.state.location === '') {
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('1');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('2');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('3');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('4');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('5');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('6');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('7');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('8');
          output.push(item);
        }
      }
    } else if (this.state.distFromLoc <= this.state.distance) {
      console.log(this.state.distFromLoc);
      console.log(this.state.distance);
      if (item.option === 'Part Time' && this.state.partTime && !this.state.weekend){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('9');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('10');
          output.push(item);
        }
      } else if (item.option === 'Weekends' && this.state.weekend && !this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('11');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('12');
          output.push(item);
        }
      } else if (item.option === 'both' && this.state.weekend && this.state.partTime){
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('13');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('14');
          output.push(item);
        }
      } else if (!this.state.weekend && !this.state.partTime) {
        if (item.title.toLowerCase().match(this.state.keywords.toLowerCase()) !== null ) {
          console.log('15');
          output.push(item)
        } else if (this.state.keywords === ''){
          console.log('16');
          output.push(item);
        }
      }
    }
  })
  .catch(function (err){
    console.log(err);
  });
});
window.setTimeout(function() {
self.setState({
  dataToShow: output,
  searching: false,
  current: 1,
});
const dataLength = self.state.dataToShow.length
self.setState({
  amountOfJobs: dataLength
})}, 10000)
}

getDist(dest){
var self = this;
const wrappedCallback = (...args) => this.callback(...args);
var origin = this.state.location,
    destination = dest,
    service = new window.google.maps.DistanceMatrixService();

    service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: window.google.maps.TravelMode.DRIVING,
        avoidHighways: false,
        avoidTolls: false,
        unitSystem: window.google.maps.UnitSystem.IMPERIAL
      }, wrappedCallback 
    );
}

callback(response, status) {
    const self = this;
    if(status === "OK") {
        console.log(response);
        var dest = response.destinationAddresses[0];
        if (response.rows[0].elements[0].status === "ZERO_RESULTS"){

        } else if (response.rows[0].elements[0].status === "OK"){
          var dist = response.rows[0].elements[0].distance.text;
          this.setState({
            distFromLoc: dist
          })
        }
    } else {
        alert("Error: " + status);
    }
  }
service.getDistanceMatrix({
    origins: [origin],
    destinations: [destination],
    travelMode: window.google.maps.TravelMode.DRIVING,
    avoidHighways: false,
    avoidTolls: false,
    unitSystem: window.google.maps.UnitSystem.IMPERIAL
  }, 
  this.callback
);
当您以
this.callback
的形式提供回调时,您传递的是一个函数。但是,当调用该函数时,它不再具有需要知道
this
实际是什么的上下文,因为调用代码现在在Google的API中。有3种解决方案

1) 绑定函数,以便它知道这是什么

 //boundCallback will now always have the correct value for "this"
const boundCallback = this.callback.bind( this ); 
2) 用粗箭头函数包装它(仅限ES6)

3) 对组件使用
React.createClass()

这是我的首选解决方案-如果使用
React.createClass()创建组件
所有函数都会自动为您绑定,而不是使用
类Comp-extends-React.Component
,因此您无需对此进行任何处理-
回调总是正确的。

可能有其他解决方案,但它使用了一个全局变量:

window.callback = function( ) {};

window.callback = (code, name) => {
    me.setState({stateVariable: code});     
};

您可以相应地更改此代码,并在代码的任何位置使用回调(因为它是使用保留上下文的arrow函数全局声明的,这是一个闭包)

因此,对于数字2),我只需将“this.callback”更改为“const boundCallback=this.callback.bind(this)我说得对吗?然后我把wrappedCallback放回我开始的地方。我用我修改代码的内容更新了我的问题,以便你能让我成为React的小提琴手。createClass()我不知道如何使用React.createClass(),因为我不使用它。