使用Google Maps API和分析云代码时定义地理编码器变量时出错

Error defining geocoder variable while using Google Maps API and Parse Cloud Code

本文关键字:定义 编码器 出错 变量 代码 Maps Google API 使用      更新时间:2023-09-26

我正在尝试使用解析云代码来使用Google Maps API v3对地址进行地理编码。根据谷歌的建议代码,我正在使用以下代码:

 Parse.Cloud.afterSave ('IncidentDetails', function(request, status) {
                   var address = request.object.get("address1");
                   var geocoder;
                   function initialize () {
                   geocoder = new google.maps.Geocoder();
                   codeAddress (address);
                   }
                   function codeAddress () {
                   geocoder.geocode( { 'address':address}, function (results, status) {
                                    if (status == google.maps.GeocoderStatus.OK) {
                                        var lat = results[0].geometry.location.lat();
                                        var lng = results[0].geometry.location.lng()
                                        request.object.set("lat", lat);
                                        request.object.set("lng", lng);
                                    } else {
                                    alert('Geocode was not successful for the following reasons: ' + status);
                                    }
                                    });
                   }
                   initialize ();
                   });

保存PFObject后,代码运行良好,但在上失败

geocoder = new google.maps.Geocoder ();

错误:ReferenceError:谷歌没有定义

我在HTML中看到了定义源代码和设置api密钥的情况,但在纯java脚本示例中却看不到相同的情况。

如有任何关于正确初始化地理编码器变量的帮助,我们将不胜感激。

google.maps.Geocoder是一个javascript,用于在浏览器中工作,使用地理编码,使用Parse.Client.httpRequest如下,(您需要在googlegenenenebb API控制台中启用地理编码API) Parse.Cloud.httpRequest({ method: "POST", url: 'https://maps.googleapis.com/maps/api/geocode/json', params: { address : address, key:YourKey }, success: function(httpResponse) { var response=httpResponse.data; if(response.status == "OK"){ var langLat=response.results[0].geometry.location; console.log(langLat); } }, error: function(httpResponse) { console.error('Request failed with response code ' + httpResponse.status); } });