我有一个CalcDistanceBetweenGoogle函数,它进行提取,将坐标传递给"和"来自",应该返回两个坐标之间的距离。
如果距离小于20000(20 km),则将其插入阵列。
但它无法正常工作,稍后会打印出来。
我做错了什么?
世博会示例:https://snack.expo.io/H1NianjoG
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
export default class App extends Component {
state = {};
componentDidMount() {
this.calc();
}
calc() {
var markers = [
{
id: '269849444',
name: 'Ziano Piacentino',
lat: 45,
lng: 9.4,
},
{
id: '649296407',
name: 'Monte Bondone',
lat: 46.0315,
lng: 11.05685,
},
{
id: '300151628',
name: 'Cima Calisio',
lat: 46.0977158258,
lng: 11.1443512052,
},
{
id: '266239592',
name: 'Trient, Trentino-Alto Adige, Italy',
lat: 46.0667,
lng: 11.1333,
},
{
id: '130313194355778',
name: 'Monte Celva',
lat: 46.0695882,
lng: 11.1783065,
},
{
id: '217942785',
name: 'Trento, Italy',
lat: 46.0667,
lng: 11.1333,
},
{
id: '478657266',
name: 'Mercatino di Natale a Levico Terme città da amare',
lat: 46.0099217576,
lng: 11.3052625593,
},
{
id: '288554028181059',
name: 'Fontana Del Nettuno, Trento',
lat: 46.0675553413,
lng: 11.1213752236,
},
{
id: '252747884',
name: 'Duomo di Milano - Milan Cathedral',
lat: 45.4646680426,
lng: 9.1904055604,
},
{
id: '213183830',
name: 'Piacenza',
lat: 45.0167,
lng: 9.66667,
},
{
id: '213183830',
name: 'Home',
lat: 45.0167,
lng: 9.66667,
},
];
var group = [];
for (var i = 0; i < markers.length; i++) {
var array = [];
for (var j = 0; j < markers.length; j++) {
if (i != j) {
var ci = markers[i];
var cj = markers[j];
this.CalcDistanceBetweenGoogle(ci, cj).then(async el => {
if (el.dist <= 20000) {
console.log(el)
array.push(el.to);
}
});
}
}
group.push(array);
}
console.log(group);
}
async CalcDistanceBetweenGoogle(from, to) {
var lat1 = from.lat, lon1 = from.lng, lat2 = to.lat, lon2 = to.lng;
try {
const response = await fetch(
'https://maps.googleapis.com/maps/api/distancematrix/json?origins=' +
lat1 +
',' +
lon1 +
'&destinations=' +
lat2 +
',' +
lon2 +
'&mode=driving&language=it-IT',
{
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
}
);
const json = await response.json();
return {
from: from,
to: to,
dist: json.rows[0].elements[0].distance.value,
};
} catch (error) {
console.error(error);
}
}
render() {
return <View style={styles.container} />;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: 80,
backgroundColor: '#ecf0f1',
},
});