blueHula
blueHula

Reputation: 1581

Geocoding with Google Maps API via Parse Cloud Code

I am tackling some JavaScript- of which i know very little about in order to geocode an address stored on an object in a class i have on Parse.com. Via Cloud Code, I have a property on a PFObect which I need to pass into the geocoder and then parse the resulting JSON return for the lat and long, then eventually save that as a property on the same PFObject.

I've spent considerable time searching for a solution, and most recommendations seem to be to use Google Maps JavaScript API v3 rather than an HTTP request.

Here is my code:

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 ();

                   });

I'm hoping someone with some experience with this can guide me in the right direction. The above code is deployed correctly in Parse Cloud Code, however i'm not sure it's actually called as there is nothing in the log or error consoles. I feel like I'm missing something fundamental- and I appreciate any help or suggestions.

Upvotes: 2

Views: 2519

Answers (2)

Chandan C
Chandan C

Reputation: 138

google.maps.Geocoder is a javascript meant to work in browser, to use geocode, Make use of Parse.Cloud.httpRequest as below, (You need to have Geocoding API enabled in goolge API console)

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); } });

Upvotes: 5

mamarx
mamarx

Reputation: 91

You don't call the functions, so the code is not executed. Try:

initialize();

codeAddress();

If the code does not work as you expect it, you can debug it by calling:

console.log("Your info");

Upvotes: 0

Related Questions