Hello everyone,
I am building a webapp that requires me to geocode an address into coordinates on the server.
After the offer is inserted into the collection, I have setup a collection-hook, that calls a method (offers.geocode
) that should geocode the address into coordinates and insert them then into the collection. Unfortunately I cannot get it to work. Can someone help me?
My schema:
/* eslint-disable consistent-return */
import { Mongo } from "meteor/mongo";
import SimpleSchema from "simpl-schema";
const Offers = new Mongo.Collection("offers");
Offers.allow({
insert: () => false,
update: () => false,
remove: () => false,
});
Offers.deny({
insert: () => true,
update: () => true,
remove: () => true,
});
Offers.schema = new SimpleSchema({
address: Object,
// [..]
"address.street": {
type: String,
label: "Street and house number",
},
"address.city": {
type: String,
label: "City",
},
"address.zip": {
type: Number,
label: "Postal code",
regEx: SimpleSchema.RegEx.ZipCode,
},
"address.country": {
type: String,
label: "Country",
},
"address.lat": {
type: Number,
label: "Latitude",
optional: true,
},
"address.lon": {
type: Number,
label: "Longitude",
optional: true,
},
});
Offers.attachSchema(Offers.schema);
export default Offers;
The collection hook:
import Offers from "../Offers";
Offers.after.insert(((userId, offer) => {
if (!offer.address.lat) {
Meteor.call("offers.geocode", offer, offer.address);
}
}));
My method looks like this:
import Meteor from "meteor/meteor";
import NodeGeocoder from "node-geocoder";
import { Offers } from "../Offers";
export default function (offer, address) {
const geocoder = new NodeGeocoder({
provider: "google",
httpAdapter: "https",
apiKey: Meteor.settings.private.GoogleMapsGeoCodingApiKey,
});
const result = geocoder.geocode(address.street + address.zip + address.city + address.country + address.state );
Offers.update({
_id: offer._id,
}, {
$set: {
"offer.address.lat": result[0].latitude,
"offer.address.lon": result[0].longitude,
},
}, {
validate: false,
});
}