Enter zipcode and display users within a certain radius

青春壹個敷衍的年華 提交于 2019-12-11 05:59:55

问题


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!


回答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:

  • zipcodes NPM library
  • MongoDB: Geospatial Queries
  • MongoDB: $near
  • MongoDB: $geometry
  • MongoDB: 2dsphere Indexes


来源:https://stackoverflow.com/questions/44697282/enter-zipcode-and-display-users-within-a-certain-radius

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!