我一直在尝试创建一些种子文件,同时也使用google api,为每个城市创建一些经度和纬度。整个过程和代码都有效,但我相信异步调用存在问题,因为我无法正确保存坐标。以下是我的代码片段:
var coordinates = getCoordinates("syndey", "australia");
console.log("these are the coordinates " + coordinates);
function getCoordinates(city, country) {
var coordinates = {
lat: Number,
lng: Number
};
const url = "https://maps.googleapis.com/maps/api/geocode/json?components=locality:"+city+"|country:"+country +"&key=MYAPIKEY";
request(url, (err, resp, body)=> {
body = JSON.parse(body);
console.log("this is the body: " + JSON.stringify(body.results[0].geometry.location.lat));
if (err) {
res.status(401).json({message: "error"});
} else {
coordinates.lat = body.results[0].geometry.location.lat;
coordinates.lng = body.results[0].geometry.location.lng;
}
console.log("before exit: " + JSON.stringify(coordinates));
return coordinates;
});
}
当代码执行时,我在终端中获得以下控制台:
这些是未定义的坐标
这是正文:-33.8688197
退出前:{“lat”: - 33.8688197,“lng”:151.2092955}
正如您所看到的,坐标是未定义的,并且它清楚,因为之前退出控制台日志是在执行之后执行的。
我确实尝试过回调但是没有用。
有什么想法吗?
由于 安德烈亚斯