2014-09-19 96 views
2

我正在處理一些我並不瞭解的JavaScript,以便對我在Parse.com上的類中的對象上存儲的地址進行地理編碼。通過Cloud Code,我有一個PFObect的屬性,我需要將其傳遞給地理編碼器,然後解析生成的經緯度返回值,然後最終將其保存爲同一個PFObject的屬性。通過Parse Cloud使用Google Maps API進行地理編碼代碼

我花了大量時間尋找解決方案,而且大多數建議似乎都是使用Google Maps JavaScript API v3而不是HTTP請求。

這裏是我的代碼:

Parse.Cloud.afterSave ('incidentDetails', function(request, status) { 

        var address = request.object.get("address1"); 
        var geocoder; 

        function initialize() { 

        geocoder = new google.maps.Geocoder(); 
        codeAddress(); 

        } 

        function codeAddress() { 

        console.log("test"); 

        geocoder.geocode({ 'address':address}, function (results, status) { 

            if (status == google.maps.GeocoderStatus.OK) { 

            var latLng = results[0].geometry.location; 
            request.object.set("latLng", latLng); 

            } else { 

            alert('Geocode was not successful for the following reasons: ' + status); 
            } 
            }); 
        } 

        initialize(); 

        }); 

我希望有人與此有些經驗可以指導我在正確的方向。上述代碼在Parse Cloud Code中正確部署,但是我不確定它是否被實際調用,因爲日誌或錯誤控制檯中沒有任何內容。我覺得我錯過了一些根本性的東西 - 我感謝任何幫助或建議。

回答

5

google.maps.Geocoder是意味着瀏覽器工作JavaScript,爲使用地理編碼,運用Parse.Cloud.httpRequest的如下,(你必須GOOLGE 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); } });

+0

如果您在參數中討論YourKey:{ address:address, key:YourKey },則它是Google地理編碼API密鑰而不是解析應用密鑰。 – 2015-02-09 03:16:34

0

您不調用函數,因此代碼不會執行。嘗試:

initialize(); 

codeAddress(); 

如果你期望它的代碼不能正常工作,你可以通過調用調試它:

console.log("Your info"); 
+0

好吧,我現在已經運行的代碼,我能夠打印到日誌,但正如我懷疑我需要定義Google的某個地方,因爲它返回以下錯誤:ReferenceError:谷歌沒有定義...我認爲我需要提供谷歌API的來源...只是不知道確切地在哪裏?幫助那裏將不勝感激。 – blueHula 2014-09-19 21:26:26

相關問題