Firebase云函数typescript引用错误:未定义google
我有一个云函数,它向谷歌地图api发出请求,从latlng获取地理编码位置信息。当我发出请求时,它在日志Firebase云函数typescript引用错误:未定义google,typescript,firebase,google-maps,google-maps-api-3,google-cloud-functions,Typescript,Firebase,Google Maps,Google Maps Api 3,Google Cloud Functions,我有一个云函数,它向谷歌地图api发出请求,从latlng获取地理编码位置信息。当我发出请求时,它在日志ReferenceError:google在/user\u code/lib/file\u name中没有定义 我不知道这背后的原因是什么,我将键入的包添加到package.json文件中 package.json { "name": "functions", "scripts": { "lint": "tslint --project tsconfig.json",
ReferenceError:google在/user\u code/lib/file\u name中没有定义
我不知道这背后的原因是什么,我将键入的包添加到package.json文件中
package.json
{
"name": "functions",
"scripts": {
"lint": "tslint --project tsconfig.json",
"build": "tsc",
"serve": "npm run build && firebase serve --only functions",
"shell": "npm run build && firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"main": "lib/index.js",
"dependencies": {
"@google/maps": "^0.4.6",
"@types/googlemaps": "^3.30.10",
"firebase-admin": "^5.12.1",
"firebase-functions": "^1.0.4",
"nodemailer": "^4.6.4",
"twilio": "^3.16.0"
},
"devDependencies": {
"tslint": "^5.10.0",
"typescript": "^2.9.2"
},
"private": true
}
加载位置信息的函数
async function getAddressFromLatAndLang(location) {
const maps = require('@google/maps')
const googleMapsClient = maps.createClient({
key: 'API_KEY',
Promise: Promise
});
const latlng = new google.maps.LatLng(location.latitude, location.longitude)
const result = await googleMapsClient.geocode({ latlng: latlng }).asPromise()
console.log(result)
}
您尝试使用Google地图web服务
请注意,google.maps.LatLng
对象未在NodeJs库中定义,该对象在可在客户端使用的google-maps JavaScript API v3中定义。根据github文档,在NodeJs客户机库中,您可以将以下对象作为LatLng对使用
纬度、经度对。API方法可接受以下任一种:
- [纬度,经度]的两项数组李>
- 逗号分隔的字符串李>
- 具有“lat”、“lng”属性的对象;或
- 具有“纬度”、“经度”属性的对象
资料来源:
由于函数中的位置
具有属性纬度
和经度
,因此您可以在中直接使用它
const result = await googleMapsClient.reverseGeocode({ latlng: location }).asPromise()
请注意,要将坐标解析为地址,必须使用reverseGeocode()
方法。geocode()
方法用于将地址字符串解析为坐标
我希望这有帮助 有谷歌/地图npm软件包吗?你能让我参考一个url来查看它吗?是的,我添加了它,然后也许你可以尝试在main上定义上面的getAddressFromLatAndLang
函数的映射常量。可能不支持动态导入/require。例如const-maps=google.maps
?const-maps=require(“@google/maps”)
在函数之前的全局上。感谢您的帮助,我尝试了位置和数组解决方案,但结果是giveinvalidValueError:Object上意外的属性“latlng”。validator
我不知道为什么@xomenai也使用分隔符尝试字符串,显示相同的错误哦,我没有注意到这一点,但您必须使用.reverseGeocode()
方法来解析纬度和经度。我更新了我的答案。请在文档中查看此方法:但这里有一个问题,为什么新的google.map.LatLng不起作用,我添加了types包?因为google.map.LatLng
不构成您包含的包的一部分。google.map.LatLng
是在客户端定义的,但是您使用的是另一个没有此类的服务器端NodeJs库。