node.js - 有没有办法从 node.js 访问 google.maps.LatLng?
问题描述
作为 html 页面的一部分,我让这段代码运行良好。触发搜索后,它会在传入的点的一定半径内找到感兴趣的地方。
(index.html)
...
<script src="https://apis.google.com/js/api.js" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js?key={myapikey}&libraries=places&callback=initMap"></script>
...
(脚本.js)
function googlePlaces(points) {
points = [
[2.627365, 49.215369],
[2.760591, 49.647163],
[2.952975, 50.057504],
[3.344742, 50.280862],
[3.768293, 50.451306],
[4.21659, 50.534029] // for sake of example
var i=0;
var placesOfInterest = [];
for (point of points){
var latLng = new google.maps.LatLng(point[1],point[0])
var request = {
location: latLng,
radius: '10000'
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request,
function(results,status){
if (status == google.maps.places.PlacesServiceStatus.OK) {
placesOfInterest.push(results);
};
});
i++;
}
return placesOfInterest;
}
我现在想在 node.js 设置(无 html)中使用此代码以将 placesOfInterest 作为 JSON 返回。我已将所有相关代码移动到我的 API 的“controller.js”文件中。
但现在我收到“谷歌”未定义的错误。
我试过的
所以我尝试以这种方式导入谷歌库https://github.com/googlemaps/google-maps-services-js,添加一行
var googleMapsClient = require('@google/maps').createClient({
key: 'myAPIkey'
});
并将我的google
引用更改为...
// service.nearbySearch(request,
googleMapsClient.nearbySearch(request,
//var latLng = new google.maps.LatLng(point[1],point[0])
var latLng = googleMapsClient.LatLng(point[1],point[0])
但我收到一个错误,即 googleMapsClient.LatLng 不是函数。如何将谷歌库直接导入到我的 js 文件中?
解决方案
您尝试将用于 Google 地图服务的 Node.js 客户端和 Google 地图 JavaScript API v3 代码混合在一个地方。请注意,用于 HTTP Web 服务的 NodeJs 客户端库是为服务器端代码设计的,通常不适用于来自客户端 Google Maps JavaScript API v3 的代码。
NodeJs 客户端库定义了它自己的 LatLng 接口,在
https://googlemaps.github.io/google-maps-services-js/docs/LatLng.html
界面:LatLng
纬度、经度对。API 方法接受:
[纬度,经度]的两项数组;
逗号分隔的字符串;
具有“lat”、“lng”属性的对象;或者
具有“纬度”、“经度”属性的对象。
因此,在您的 NodeJs 代码中,您可以执行以下操作
var latLng = [41.3848421,2.1841461];
var latLng = "41.3848421,2.1841461";
var latLng = {lat: 41.3848421, lng: 2.1841461};
var latLng = {latitude: 41.3848421, longitude: 2.1841461};
然后将此值传递给附近的搜索方法。
var googleMapsClient = require('@google/maps').createClient({
key: 'myAPIkey'
});
googleMapsClient.placesNearby({
location: latLng,
radius: 10000,
type: myType
}, function(err, response) {
....
});
我希望这有帮助!
推荐阅读
- javascript - OnClick 处理程序用于获取不适用于选项卡的数据
- graphql - Apollo Graphql 返回结果而不发送请求
- python - Python - 数据集值的比例
- r - Blogdown - 提交/接收电子邮件以访问/下载 R 中的文件
- mysql - 如何在列表中为每个对象拥有一个组件?
- python - 列中相应值的 NaN 值百分比
- reactjs - 如何使用 zustand 将对象键设置为状态
- reactjs - 使用 i18next 翻译问题
- r - R:在变量列表中使用 gam::gam 和 lapply
- java - 在 SoapFault 或异常中弹簧捕获肥皂请求