简体   繁体   中英

How to find nearest coupon from cosmos db with current Latitude and Longitude

I've a Coupon container in Cosmos db which have id, name, category, Latitude and Longitude fields. I'm saving Coupon for different areas and saving Latitude and Longitude of those. I want to search coupons that are within current user mile radius for example within 50 miles. I'm getting latitude and longitude of user location from their device. Format of Latitude and Longitude is lat: 24.8779 long: 67.0641. I'm using SQL API for cosmos db to query data. Please guide me what will be the query for this?

first make sure to store the coupon coordinates in the GeoJSON format. For example, see the location field below:

{
  "country": "AD",
  "name": "Sant Julià de Lòria",
  "location": {
    "type": "Point",
    "coordinates": [
        42.46372,
        1.49129
    ]
  },
}

Then, query using the ST_DISTANCE function, for example:

SELECT * FROM c
WHERE ST_DISTANCE(c.location, {'type': 'Point', 'coordinates':[42.54277, 1.73361]}) < (50 * 1609.344)

ST_DISTANCE uses meters, so the multiplication times 1609.344 is to convert miles to meters.

See https://docs.microsoft.com/en-us/azure/cosmos-db/geospatial for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM