首页 > 解决方案 > 试图通过谷歌地理定位 API 转换经度纬度,但没有成功

问题描述

嘿伙计们,我是 JavaScript 异步编程的新手,我试图获取一个只有经度和纬度的文件并将其转换为街道地址

我将我的表转换为 json 文件并将文件导入我的小程序,之后我试图通过我的数组并从 api 获取地址,并且我不断收到各种错误取决于我所做的更改修复 f**g 的东西

const axios = require('axios');
import * as fs from 'fs';


const getResults = async () => {
    const apiKey = 'blablabla'
    const data = JSON.parse(fs.readFileSync("csvjson.json"));

    const getAddress = (lng,lat) => {
    return new Promise((resolve, reject) => {
      axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lng},${lat}&key=${apiKey}`)
      .then(response => {
        return resolve(response.data)
      })
      .catch(error => {
        return reject(error.message)
      })
    })
  }


    const newData = data.map(async item => {
    const newItem = {
        ...item,
        results_from_google: item.Longitude !== "blank" ? await getAddress(item.Longitude,item.Latitude) : 'blank'

    }

    //console.log('the results: '+ results)

    return newItem;

})

const results = await Promise.all(newData)

console.log(JSON.stringify(results, null, 2))
    console.log(results)
    fs.writeFileSync("./format-more-output.json", JSON.stringify(results, null, 2));
}

getResults()

我现在的错误是

(node:16488) UnhandledPromiseRejectionWarning: Request failed with status code 400
(node:16488) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:16488) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
PS

谢谢你们的帮助

标签: javascriptnode.jsasynchronousaxios

解决方案


我试过你的代码,我只能看到一个错误,纬度和经度是错误的,你传递的是 lng,lat 而 API 需要 lat,lng。我怀疑这就是您收到 400 错误的原因。

我已经更新了代码以更好地处理错误情况。另外我会重新考虑使用内联函数表达式,这些使代码更难阅读恕我直言,也许将它们重构出来!

这对我有用:

const axios = require('axios');
const fs = require('fs');

const getResults = async () => {
    const apiKey = API_KEY;
    const data = JSON.parse(fs.readFileSync("csvjson.json"));

    const getAddress = (lng,lat) => {
        return new Promise((resolve, reject) => {
            console.log(`Getting address for ${lat}, ${lng}...`);
            axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${apiKey}`)
            .then(response => {
                return resolve(response.data)
            })
            .catch(error => {
                return reject(error.message)
            })
        })
    }

    const newData = data.map(async item => {
        const newItem = {
            ...item,
            results_from_google: item.Longitude !== "blank" ? await getAddress(item.Longitude,item.Latitude) : 'blank'

        }
        return newItem;
    })

    try {
        const results = await Promise.all(newData);
        console.log(JSON.stringify(results, null, 2));
        console.log(JSON.stringify(results));
        fs.writeFileSync("./format-more-output.json", JSON.stringify(results, null, 2));
    } catch (error) {
        console.error("An error occurred: ", error);
    }

}

getResults();

我正在使用以下输入:

csvjson.json

[
    {
        "Latitude": 34.05016083426763,
        "Longitude": -118.47179800984532
    }
]

结果看起来像这样(只显示第一行!):

格式更多输出.json

[
  {
    “纬度”:34.05016083426763,
    “经度”:-118.47179800984532,
    “results_from_google”:{
      “加号”:{
        "compound_code": "3G2H+37 Los Angeles, CA, USA",
        “global_code”:“85633G2H+37”
      },
      “结果”: [
        {
          “地址组件”:[
            {
              "long_name": "816",
              "short_name": "816",
              “类型”:[
                “街牌号码”
              ]
            },
            {
              "long_name": "南邦迪大道",
              "short_name": "S 邦迪博士",
              “类型”:[
                “路线”


推荐阅读