1

I have a Meteor app where product providers enter their zip code when registering. This data is stored in users.profile.zipcode.

Flow: 1. Anyone visiting the site can enter a zip code in a search field. 2. A list of product providers with zipcodes within 10 kilometers of that zip code is displayed.

The app will be for Norwegian users to begin with, but will maybe be expanded to different countries in the future.

Can someone provide me with example code of how this can be done, i guess using the Google API or something similar? I'm pretty new to JavaScript so a complete example would be very much appreciated. Hopefully using Meteor.Publish and Meteor.Subscribe, including the display of the data.

Thank you in advance!

user3323307
  • 243
  • 4
  • 13
  • I recommend to start with MongoDB [geospatial indexes](https://docs.mongodb.com/manual/applications/geospatial-indexes/) – dr.dimitru Jun 22 '17 at 11:14
  • Thank you. A code example of how this can be easily implemented would be very much appreciated. Thank you! – user3323307 Jun 22 '17 at 12:42

1 Answers1

1

First you will have to convert ZIP code to coordinates, there is a zipcodes lib - for US and Canada only, if you're targeted other region/country libs can be easily found on NPM.

For example we have a Meteor Method which accepts form with zipcode field:

import zipcodes from 'zipcodes';

// Create `2dsphere` index
const collection = new Mongo.Collection('someCollectionName');
collection._ensureIndex({zipLoc: '2dsphere'});

Meteor.Methods({
  formSubmit(data) {
    const zipData = zipcodes.lookup(data.zipcode);
    // Save location as geospatial data:
    collection.insert({
      zipLoc: {
        type: "Point",
        coordinates: [zipData.longitude, zipData.latitude]
      }
    });
  }
});

To search within radius use next code:

const searchRadius = 10000; // 10km in meters
const zip = 90210;
const zipData = zipcodes.lookup(zip);

collection.find({
  zipLoc: {
    $near: {
      $geometry: [zipData.longitude, zipData.latitude],
      $maxDistance: searchRadius
    }
  }
});

Further reading:

dr.dimitru
  • 2,645
  • 1
  • 27
  • 36