问题
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